Skip to content

feat(rocm/cuda): auto-enable GPU peer access so multi-GPU quantization stays on the interconnect - #3479

Merged
Qubitium merged 3 commits into
mainfrom
rocm/p2p-peer-access
Nov 2, 2026
Merged

Qubitium merged 3 commits into
mainfrom
rocm/p2p-peer-access

Conversation

@ZX-ModelCloud

@ZX-ModelCloud ZX-ModelCloud commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Multi-GPU quantization moves quantized tensors between devices, but the tree had no peer-access 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 existing P2P code was diagnostic printing.

This PR makes cross-device traffic stay on the GPU interconnect (gpu1 <-> gpu2) instead of falling back to gpu1 -> CPU -> gpu2.

New gptqmodel/utils/p2p.py

  • peer_matrix(devices) — the directed matrix. i -> j and j -> i are 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 via cudaGetLastError.
  • Each 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 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.0 threshold required the direct copy to beat staging — which classified every real PCIe pair as degraded and 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):

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

Changes:

  • GPTQMODEL_P2P_MIN_RATIO defaults to 0.9 — keeps those links direct, still rejects a genuinely broken one (tests pin a 0.5x link as degraded).
  • GPTQMODEL_P2P=1 is an explicit request for the direct path, so the relative comparison no longer vetoes it; the absolute GPTQMODEL_P2P_MIN_GBPS floor still applies.
  • The probe is now robust: payload steps down (64/32/16/4 MiB) under memory pressure, and takes the best of two samples per direction. A single noisy sample previously flipped a healthy direction to degraded, silently reintroducing the CPU relay mid-run.

copy_tensor_to always issues one dst.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) 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.

No architecture dependency — p2p.py imports 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 == True while being PCIe-limited. They are not special-cased by sm_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/nccl distributed path in gsq_distributed.py is a separate mechanism, 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. ruff 0.14.2 clean.

Benchmark: scripts/benchmark_multi_gpu_p2p.py --mib 128 --iters 20.

…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.
Comment thread scripts/benchmark_multi_gpu_p2p.py Fixed
Comment thread scripts/benchmark_multi_gpu_p2p.py Fixed
Comment thread scripts/benchmark_multi_gpu_p2p.py Fixed
Comment thread gptqmodel/utils/p2p.py Fixed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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
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

Comment thread gptqmodel/models/loader.py Resolved
Comment thread gptqmodel/utils/p2p.py Resolved
Comment thread gptqmodel/utils/p2p.py Resolved
Comment thread gptqmodel/utils/p2p.py Resolved
Comment thread gptqmodel/utils/p2p.py Resolved
Comment thread gptqmodel/utils/p2p.py Resolved
Comment thread gptqmodel/utils/p2p.py Resolved
Comment thread scripts/benchmark_multi_gpu_p2p.py Resolved
Comment thread scripts/benchmark_multi_gpu_p2p.py Resolved
Comment thread scripts/benchmark_multi_gpu_p2p.py Resolved
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.

Copy link
Copy Markdown
Collaborator Author

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 fixed

1. The PR's central premise was wrong (Copilot #2753, #2770). PyTorch does enable peer access, lazily, in its own copy path (c10/cuda/PeerToPeerAccess.cpp → CUDACachingAllocator::enablePeerAccess). After a single cross-device copy_ the enable call returns 704 ("already enabled") on both ROCm 7.16 and CUDA 13.2. So the helper never "enabled" anything the copy path needed.

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 (GPTQMODEL_P2P_PROBE=1) and explicitly diagnostic — the old default moved 182 GiB across 56 pairs at startup for a verdict nothing acted on. Docs and call-site comments no longer claim degraded means "forced host staging".

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:

pair direct racy staged ordered staged
R9700 52.99 GB/s 54.92 27.35 (1.94x)
RTX 4090 26.23 GB/s 26.24 13.27 (1.98x)

The reported "0.96x parity" was this artifact. With a correct reference, direct is ~2x faster than staging, so the gate is back to 1.0 and PCIe peers stay enabled honestly. Benchmark after the fix: R9700 53.06 vs 27.23 GB/s (1.95x), 4090 26.23 vs 13.26 (1.98x).

3. Indexless devices (Copilot #2692). "cuda" / torch.device("cuda") now resolve to current_device(); non-accelerator values are skipped instead of becoming ordinal 0.

4. Integer device maps (Copilot #2674). Loader normalization is now a shared helper covering str, int, and torch.device; a {...: 0, ...: 1} map enables peer access like cuda:0/cuda:1.

5. Strict mode (Copilot #2739, #2779). PeerStatus.errors retains failures, so a cached best-effort result still raises for a later strict=True; enable_for_devices re-raises in strict mode.

6. Invalid GPTQMODEL_P2P_PROBE_MIB (Copilot #2717) falls back to 64 MiB via _probe_mib() instead of raising before caching.

7. Benchmark script. Architecture now comes from torch.cuda.get_device_properties(...).gcnArchName (no missing gptqmodel.utils.arch import, Copilot #2801); --dry-run no longer initializes CUDA or emits device_info (Copilot #2819); p2p_off renamed to pre_enable with a note that PyTorch already peers there (Copilot #2839); staging legs ordered.

8. Lint. Empty except now logs at debug; SKU-note concatenation is explicit (+ → parenthesized literals, satisfying ISC).

Verification

  • tests/test_p2p.py + tests/test_looper_concurrency.py: 42 passed (CUDA, gp_314t); tests/test_p2p.py 21 passed on ROCm (gp_314t_rocm, HIP_VISIBLE_DEVICES=2,3).
  • New tests cover opt-in probing, indexless normalization, integer/torch.device map targets, invalid PROBE_MIB, cached-failure strictness, and staged-leg ordering.
  • ruff clean on changed files.

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.

@Qubitium
Qubitium marked this pull request as ready for review November 2, 2026 02:44
- 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.

Copy link
Copy Markdown
Collaborator Author

github-code-quality findings cleared (160067020)

Both review threads (#pullrequestreview-5731138570 and the quality findings) are resolved. I re-checked with a local token-accurate replica of the two CodeQL queries in play.

Validation method. The replica reproduces all four original findings at 09750afe7 (scripts/benchmark_multi_gpu_p2p.py:105,108,110 implicit concatenation; gptqmodel/utils/p2p.py:527 empty except) and reports 0 findings on the current HEAD in both files. CI agrees: CodeQL, Analyze (python) ×2, Analyze (actions) and ruff-check ×2 all completed with success on 160067020.

What changed.

  1. Implicit string concatenation in a list (3 findings, _sku_notes). Adjacent literals are now one literal per note. Note the two intermediate shapes were also flagged: ("a" "b") is still an implicitly concatenated part, and "a" + "b" trips ruff ISC003 (explicitly concatenated string should be implicit) in the repo's own gate. One literal per element satisfies both tools and keeps the note text.

    • ISC001/ISC002 → implicit concatenation; ISC003 → explicit +. The repo's format/check.sh runs plain ruff check, whose default rule set includes ISC, so a + join would have failed ruff-check.
  2. Empty except (gptqmodel/utils/p2p.py). The HIP and CUDA last-error drains now log at debug instead of except Exception: pass:

    except Exception as exc:  # pragma: no cover - never let cleanup raise
        log.debug("hipGetLastError drain failed: %s", exc)

    The device-restore handler called out in the review already logs the device and exception; that one had been fixed in 14e915108.

Note. Two remaining except Exception: pass handlers exist in gptqmodel/looper/module_looper.py (lines ~844 and ~1200). They are pre-existing on main, on a different path, and CodeQL did not flag them (they were not touched by this PR), so I left them out of scope.

Verification. tests/test_p2p.py 21 passed on ROCm (gp_314t_rocm, GPUs 2,3); tests/test_p2p.py + tests/test_looper_concurrency.py 42 passed on CUDA (gp_314t); ruff clean on the changed files; SKU notes still print the same intent.

@Qubitium
Qubitium merged commit f41b953 into main Nov 2, 2026
6 checks passed
@Qubitium
Qubitium deleted the rocm/p2p-peer-access branch November 2, 2026 03:50
Qubitium added a commit that referenced this pull request Nov 9, 2026
#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants