Repository navigation
feat(rocm/cuda): auto-enable GPU peer access so multi-GPU quantization stays on the interconnect - #3479
Conversation
…n stays on the interconnect
Multi-GPU quantization moves quantized tensors between devices, but the tree had
no enablement path at all: `torch.cuda.can_device_access_peer` only reports a
capability bit, and nothing ever called `hipDeviceEnablePeerAccess` /
`cuCtxEnablePeerAccess`. Copies therefore went through the driver's staging path,
and the only P2P code was diagnostic printing.
New gptqmodel/utils/p2p.py
- `peer_matrix(devices)` reports the *directed* matrix (i -> j and j -> i are
queried separately; self-access is reflexive).
- `enable_peer_access(devices=None, *, strict=False)` enables each direction
through ctypes, because PyTorch has no enable wrapper. Error 704
("already enabled") counts as success, so repeat calls are idempotent.
A HIP ctypes failure leaves a sticky error in the thread-local slot that
would otherwise poison the next torch HIP call, so the slot is drained; CUDA
has the same latch and is drained with `cudaGetLastError`.
- Every direction is classified `enabled` / `unsupported` / `degraded` after a
*measured* copy. A capability bit is never treated as proof of a usable
link. Results are cached once per device set.
The gate is what this PR fixes. On a plain PCIe topology a peer copy and a
pinned-host staged copy cross the same root complex, so a healthy link measures
at parity, not above. The original 1.0 threshold required the direct copy to be
at least as fast as staging, which classified *every* real PCIe pair as
`degraded` and forced the `gpu1 -> CPU -> gpu2` relay this feature exists to
avoid. Measured on this host (64 MiB, double-synchronized timer, best of two
samples, `GPTQMODEL_P2P=auto`):
| pair | direct GB/s | staged GB/s | ratio | state |
|--------------------------|-------------|-------------|-----------|---------|
| 2x R9700 (gfx1201) 2->3 | 53.1 | 55.0 | 0.965 | enabled |
| 2x R9700 (gfx1201) 3->2 | 53.1 | 55.0 | 0.966 | enabled |
| 2x RTX 4090 (sm_89) 0->1 | 26.2 | 26.2 | 0.999 | enabled |
| 2x RTX 4090 (sm_89) 1->0 | 26.2 | 26.2 | 1.000 | enabled |
`GPTQMODEL_P2P_MIN_RATIO` now defaults to 0.9, which keeps those links on the
direct path while still rejecting a genuinely broken one (the tests pin a 0.5x
link as `degraded`). `GPTQMODEL_P2P=1` is an explicit request for the direct
path, so the relative comparison does not veto it; the absolute
`GPTQMODEL_P2P_MIN_GBPS` floor still applies.
The probe also had to become robust: it now steps the payload down
(64/32/16/4 MiB) when an allocation cannot be served under memory pressure and
takes the best of two samples per direction. A single noisy sample used to
flip a healthy direction to `degraded`, which silently reintroduced the CPU
relay mid-run.
`copy_tensor_to` always issues one `dst.copy_(src)`; it never inserts an explicit
host relay, because that would be *pageable* host memory -- slower than the
driver's own staging and exactly the path being avoided.
Wiring: best effort (`strict=False`, one summary log line) before
`clone_module_for_devices()`, from `ModuleLooper` / `WeightOnlyLooper` over the
union of the quant/dense/MoE pools, and for multi-device `device_map` loads. A
failed probe never blocks quantization. This is independent of the RDNA4 kernel
work: `p2p.py` has no architecture dependency and applies to CUDA and ROCm
alike.
RTX 4090 is not special-cased by `sm_89`: every pair is measured. Consumer Ada
cards commonly report the capability bit while being PCIe-limited, so the
measurement decides.
P2P is not NCCL P2P. The GSQ `gloo`/`nccl` distributed path in
`gsq_distributed.py` is a separate mechanism and is validated independently by
`tests/test_gsq_distributed.py`.
Tests: tests/test_p2p.py gains mocked directed-matrix, idempotency, env-disable,
absolute-floor, parity-stays-enabled, materially-slower-is-degraded, ratio-env,
forced-mode, probe-noisy-sample and never-bounce-through-host cases, plus a real
two-GPU bit-exact direct-copy case that skips without a usable peer link.
35 passed on a 4x R9700 host.
Deps: none.
There was a problem hiding this comment.
🟡 Changes recommended
Peer-access controls do not enforce the advertised routing policy, strict-mode failures are suppressed, and unsynchronized staging copies make bandwidth verdicts unreliable.
11 open issues
Integer device-map targets are dropped before peer enablement · New Indexless CUDA strings resolve to device 0 instead of current device · New Host-staging copies race across device streams · New Invalid probe-size setting retries instead of using the default · New Cached best-effort failures bypass strict-mode errors · New Default startup probe duplicates PyTorch P2P setup · New P2P verdicts do not affect routing despite advertised policy · New Strict mode still suppresses peer-enablement exceptions · New Architecture import is missing, leaving device reports incomplete · New Dry-run initializes CUDA while collecting device metadata · New Warmup enables P2P, invalidating the off measurement · New
What changed in this PR
Introduces best-effort CUDA/ROCm peer-access setup and bandwidth diagnostics for GPU transfers during quantization, module replication, and model loading.
Changes:
- Adds directed peer detection, native runtime enablement, cached link classifications, and configurable bandwidth thresholds.
- Integrates peer setup with quantization device pools, module cloning, and multi-device loading.
- Adds benchmarks, mocked and hardware tests, and configuration documentation.
| File | Description |
|---|---|
tests/test_p2p.py |
Adds topology, classification, configuration, and direct-copy tests. |
tests/test_looper_concurrency.py |
Isolates a ROCm monitoring test from cached device failures. |
scripts/benchmark_multi_gpu_p2p.py |
Adds GPU-copy and host-staging bandwidth comparisons. |
gptqmodel/utils/p2p.py |
Implements peer enablement, bandwidth probes, status caching, and copy helpers. |
gptqmodel/utils/looper_helpers.py |
Requests peer setup before multi-device module cloning. |
gptqmodel/models/loader.py |
Adds peer setup for multi-GPU device maps. |
gptqmodel/looper/weight_only_looper.py |
Requests peer setup across weight-only quantization device pools. |
gptqmodel/looper/module_looper.py |
Requests peer setup across module quantization device pools. |
docs/multi_gpu_quantization.md |
Documents peer states, environment controls, and benchmark usage. |
Review effort: Max
PyTorch already enables peer access lazily inside its own copy path, so the
earlier claim that nothing ever called hipDeviceEnablePeerAccess was wrong.
P2P pre-enablement remains (it removes first-copy setup cost) but is now
documented and tested as such.
- Fix the staged-copy race: the D2H leg is synchronized before the H2D leg.
Without it the staged baseline measured ~2x its real rate, which produced
the bogus 0.96x "parity" numbers. Measured with ordered legs: R9700
52.99 vs 27.35 GB/s, RTX 4090 26.23 vs 13.27 GB/s. Restore the ratio gate
to 1.0 and stop documenting degraded links as forced host staging.
- Make bandwidth probing opt-in (GPTQMODEL_P2P_PROBE=1) and diagnostic; the
previous default moved ~182 GiB across 56 pairs at startup for a verdict
nothing routed on.
- Normalize integer, torch.device, and indexless "cuda"/torch.device("cuda")
targets (current device, not ordinal 0); loader device maps now use the
shared helper so integer maps enable peer access too.
- Preserve enablement errors so a cached best-effort failure still raises for
a later strict=True call; enable_for_devices re-raises in strict mode.
- Invalid GPTQMODEL_P2P_PROBE_MIB falls back to 64 MiB instead of raising
before the cache is populated.
- Benchmark: read arch from device properties instead of the missing
gptqmodel.utils.arch, keep --dry-run device-free, rename p2p_off to
pre_enable (PyTorch already peers there), and order the staging legs.
- Replace the empty except with a debug log; make SKU-note concatenation
explicit.
Review verification and fixes (14e9151)Thanks for the detailed review. I verified each point on real hardware (2x R9700 gfx1201 + 2x RTX 4090) and pushed fixes. Confirmed and fixed1. The PR's central premise was wrong (Copilot #2753, #2770). PyTorch does enable peer access, lazily, in its own copy path ( Pre-enablement is kept (it removes first-copy setup cost) but is now documented and tested as that, not as a routing feature. Bandwidth probing is now opt-in ( 2. The 0.9 ratio was derived from a measurement bug (Copilot #2704) — this one mattered most. The staging probe issued the D2H and H2D legs on two device streams with no dependency, so the H2D read raced the D2H write and the staged rate was the pipelined sum. Measured with the legs ordered:
The reported "0.96x parity" was this artifact. With a correct reference, direct is ~2x faster than staging, so the gate is back to 3. Indexless devices (Copilot #2692). 4. Integer device maps (Copilot #2674). Loader normalization is now a shared helper covering 5. Strict mode (Copilot #2739, #2779). 6. Invalid 7. Benchmark script. Architecture now comes from 8. Lint. Empty Verification
One note on #2753's suggestion to remove pre-enablement entirely: I kept it, since it does make the first cross-device copy direct rather than paying lazy setup mid-quantization. If you'd rather drop it, that's a one-line follow-up. |
- scripts/benchmark_multi_gpu_p2p.py: the 4090 SKU notes are now one literal each. Both prior shapes were flagged on this PR: adjacent literals inside a list (py/implicit-string-concatenation-in-list) and an explicit '+' join (ruff ISC003). Output text is preserved. - gptqmodel/utils/p2p.py: the HIP/CUDA last-error drains log the failure at debug instead of `except Exception: pass` (py/empty-except). Verified with a local token-accurate replica of both CodeQL queries: it reproduces all four original findings on 09750af and reports none now.
github-code-quality findings cleared (
|
#3489) * feat(multi-gpu): add GIL-safe peer-copy batch and P2P lifecycle wiring Build on the P2P module merged in #3479 rather than replacing it. P2P copies - Add `peer_copy_batch`: enqueue `cudaMemcpyPeerAsync`/`hipMemcpyPeerAsync` through `ctypes` (GIL released), with an event join from the source stream to the destination stream. It is gated on `enable_peer_access(...).can_copy` and drains the sticky CUDA/HIP last error on failure. - Add `move_module_to_device` / `move_nested_to_device` and route module moves, calibration input/mask/position_ids staging, and per-layer moves through them. The module fast path refuses non-contiguous and tied leaves, and waits for the destination stream before returning. - Reuse one Hessian staging buffer only when every ordered pair is enabled and free VRAM exceeds 1.1x the buffer; adopt shared Hessians with non-blocking CUDA-to-CUDA copies. - Skip `torch.nn.parallel.replicate` when the GIL is disabled, since it funnels into the broken `broadcast_coalesced` entry point. Warning - Log exactly one actionable warning when a multi-GPU run cannot enable every ordered pair: motherboard/BIOS/hardware compatibility and sub-optimal speed. GIL=0 ledger - Add `pytorch_gil_0_compat.md` recording the measured GIL=0 status of every PyTorch API we use, plus workarounds. `broadcast_coalesced` is documented as broken on both ROCm (6/6: 4 hangs, 2 torn copies) and CUDA (6/6 torn copies). - Add `scripts/gil0_api_probe.py` (per-API subprocess timeout) and the `gptqmodel-pytorch-gil0` skill, and require the ledger in AGENTS.md. Tests - Add `tests/test_p2p_copy_utils.py`: batch roundtrip, heterogeneous and non-contiguous rejection, module/nested moves, cross-stream visibility, CPU fallback, an 8-thread concurrency test, a no-`torch.cuda.comm` regression guard, and the once-only warning. * feat(p2p): configure peer access through BaseQuantizeConfig Replace the GPTQMODEL_P2P* and GPTQMODEL_USE_TORCH_REPLICATE environment variables with a P2PConfig dataclass exposed as BaseQuantizeConfig.p2p and as the p2p= argument of GPTQModel.load/from_pretrained/from_quantized. - P2PConfig: mode (auto/on/off), probe, probe_mib, min_gbps, min_ratio, use_torch_replicate; dicts are accepted anywhere a config is. - configure_p2p()/get_p2p_config() install the process-wide policy; the loopers install BaseQuantizeConfig.p2p before enabling peer access and the inference loader installs load(..., p2p=...). - clone_module_for_devices reads use_torch_replicate at call time. - Update tests, benchmark script, README, multi-GPU guide, AGENTS rule, skill and the GIL=0 ledger; record the measured payload dependence of broadcast_coalesced and the NCCL hang in reduce_add. * docs(p2p): P2PConfig is a no-op for CPU<->CPU Peer access is an accelerator concept. Document that P2PConfig does not affect CPU-only runs, and add a regression test that a forced probing policy still leaves CPU transfers on their regular path: no pairs, no warning, and the peer helpers return not-applicable. * fix(p2p): bind peer copies to the destination device context HIP associates a stream with the calling thread's current device context, not with the device that owns the stream. peer_copy_batch enqueued the copy while the source device was current, so the work landed on the source device's queue and the destination stream -- and Tensor.cpu() -- never waited for it. Measured on 4x R9700 with PYTHON_GIL=0: p2p_move_nested of a dict whose first leaf is 32 KiB read back uninitialised memory in 24/24 single-threaded trials, and a concurrent 8-thread run tore 3/3 processes. torch.cuda.synchronize(destination) did not fix it; synchronising the source did, which pinned the copy to the wrong queue. Wrap the stream lookup, the event join and the copy loop in `with torch.cuda.device(target_device)`. After the fix: 24/24 concurrent tasks byte-exact in 3/3 processes, no synchronize needed before a read on the destination device. CUDA ordered the copy correctly either way, so the defect is HIP-specific, but the explicit scope is correct on both. Add test_p2p_move_nested_is_ordered_on_destination_stream (fails on the pre-fix tree) and record the finding in pytorch_gil_0_compat.md and the multi-GPU docs. Also correct the copy-path docs: they claimed coalescing and a speedup, but peer_copy_batch issues one peer copy per leaf. Interleaved A/B on 2x RTX 4090 shows module moves at parity across 12 shapes and calibration staging ~11% slower; end-to-end quantization is within run-to-run noise. * perf(p2p): use peer copies only for small leaves; drop coalescing The peer-copy path allocates a destination and enqueues an event join per leaf, so it only wins when dispatch overhead dominates the transfer. Measured within one process against Tensor.to (2x RTX 4090, median of 3 runs x 10 roundtrips, 12 module shapes): 128-256 KiB leaves are 3-15% faster (256x256 -10.9%, 64x256 -15.2%), while 2 MiB and larger leaves are 0-6% slower (2x2048 +6.3%). Gate both the module and the nested path on average leaf size (256 KiB, _PEER_COPY_MAX_AVG_LEAF_BYTES). Large leaves fall back to the regular move, which brings every large-leaf shape back within 1.6% of the pre-change tree while keeping the small-leaf win. Real coalescing (pack into one buffer, one peer copy, scatter) was prototyped and measured 7-17% slower on every shape: it replaces N peer transactions with 2N local ones plus one peer transaction. Not used; the docs record the result so it is not re-attempted blind. Tests: add test_p2p_move_nested_skips_large_leaves and move the peer-path tests onto leaves inside the win region. * test(model): enforce the contiguous-tensor invariant on init and post-init Kernels and the P2P peer-copy path both assume contiguous parameters and buffers. That already holds, so this adds a check rather than a rewrite. Measured before adding anything: a tiny Qwen3 MoE quantized on CPU is 0/26 non-contiguous after load, 0/74 after quantize, 0/74 after save and 0/106 after reload. On CUDA, TORCH, GPTQ_TORCH and GPTQ_TRITON are all contiguous through load+quantize. The remaining backends (Marlin, ExLlamaV2, Swordfish, BitBLAS, W4AFP8) could not be instantiated in this environment, so they stay unverified rather than assumed good. Contiguity is also not the reason coalescing needs a pack step, so forcing tensors contiguous would not remove it: leaves are contiguous but live in separate allocations (4x Linear(256,256) gives 8 distinct storages with allocator gaps), which no single memcpy can span. - add gptqmodel/utils/tensor_layout.py with iter_model_tensors, find_non_contiguous_tensors and assert_model_tensors_contiguous; tied weights are reported once and meta tensors are skipped - assert the invariant across load, quantize and reload in the tiny MoE smoke test - log the non-contiguous fallback in broadcast_module_to_device instead of silently skipping the peer path, since it usually means a load path or kernel dropped its .contiguous() - document the contiguity/adjacency distinction next to the coalescing result so it is not mistaken for the blocker again

Multi-GPU quantization moves quantized tensors between devices, but the tree had no peer-access enablement path at all:
torch.cuda.can_device_access_peeronly reports a capability bit, and nothing ever calledhipDeviceEnablePeerAccess/cuCtxEnablePeerAccess. Copies therefore went through the driver's staging path, and the only existing P2P code was diagnostic printing.This PR makes cross-device traffic stay on the GPU interconnect (
gpu1 <-> gpu2) instead of falling back togpu1 -> CPU -> gpu2.New
gptqmodel/utils/p2p.pypeer_matrix(devices)— the directed matrix.i -> jandj -> iare queried separately (HIP/CUDA peer links are directed); self-access is reflexive.enable_peer_access(devices=None, *, strict=False)— enables each direction through ctypes, because PyTorch has no enable wrapper. Error 704 ("already enabled") counts as success, so repeat calls are idempotent. A HIP ctypes failure leaves a sticky error in the thread-local slot that would otherwise poison the next torch HIP call, so the slot is drained; CUDA has the same latch and is drained viacudaGetLastError.enabled/unsupported/degradedafter a measured copy. A capability bit is never treated as proof of a usable link. Results are cached once per device set.The gate is the actual bug
On a plain PCIe topology a peer copy and a pinned-host staged copy cross the same root complex, so a healthy link measures at parity, not above it. The original
1.0threshold required the direct copy to beat staging — which classified every real PCIe pair asdegradedand forced exactly the CPU relay this feature exists to avoid.Measured on this host (64 MiB, double-synchronized timer, best of two samples,
GPTQMODEL_P2P=auto):gfx1201) 2→3gfx1201) 3→2sm_89) 0→1sm_89) 1→0Changes:
GPTQMODEL_P2P_MIN_RATIOdefaults to 0.9 — keeps those links direct, still rejects a genuinely broken one (tests pin a 0.5x link asdegraded).GPTQMODEL_P2P=1is an explicit request for the direct path, so the relative comparison no longer vetoes it; the absoluteGPTQMODEL_P2P_MIN_GBPSfloor still applies.64/32/16/4MiB) under memory pressure, and takes the best of two samples per direction. A single noisy sample previously flipped a healthy direction todegraded, silently reintroducing the CPU relay mid-run.copy_tensor_toalways issues onedst.copy_(src)and never inserts an explicit host relay — that relay used pageable memory, which is slower than the driver's own pinned staging and is precisely the path being avoided.Wiring
Best effort (
strict=False, one summary log line) beforeclone_module_for_devices(), fromModuleLooper/WeightOnlyLooperover the union of the quant/dense/MoE pools, and for multi-devicedevice_maploads. A failed probe never blocks quantization.No architecture dependency —
p2p.pyimports nothing from the RDNA4 work, so this PR is standalone and applies to CUDA and ROCm alike.RTX 4090
Consumer Ada cards commonly report
can_device_access_peer == Truewhile being PCIe-limited. They are not special-cased bysm_89: every pair is measured, and the measurement decides. On this host the pair keeps the direct path (ratio 1.000).Not NCCL P2P
The GSQ
gloo/nccldistributed path ingsq_distributed.pyis a separate mechanism, validated independently bytests/test_gsq_distributed.py.Tests
tests/test_p2p.pygains mocked directed-matrix, idempotency, env-disable, absolute-floor, parity-stays-enabled, materially-slower-is-degraded, ratio-env, forced-mode, probe-noisy-sample, and never-bounce-through-host cases, plus a real two-GPU bit-exact direct-copy case that skips without a usable peer link.35 passed on a 4x R9700 host.
ruff 0.14.2clean.Benchmark:
scripts/benchmark_multi_gpu_p2p.py --mib 128 --iters 20.