Skip to content

fix(gptaq): accumulate per-device Hessians and pair native inputs by batch (#4237) - #4284

Merged
Qubitium merged 4 commits into
mainfrom
fix/issue-4237-gptaq-multigpu
Nov 16, 2026
Merged

Qubitium merged 4 commits into
mainfrom
fix/issue-4237-gptaq-multigpu

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #4237

TL;DR

GPTAQ/FOEM now keep one Hessian/dXXT partial per input device and reduce them in device order at quantize(), and native calibration inputs are paired by calibration batch index instead of pop(0) order. Net diff: +651/−51 across 6 files; the single-device path, routed-expert path, and dXXT = 0 fallback are unchanged.

1. The problem

run_parallel fans each module's batches across every forward device, so one quantizer task sees batches from more than one GPU. Both quantizers allocated a single accumulator on the first batch's device and then added the next device's batch into it.

flowchart TD
    A["run_parallel: batch 0 on cuda:0"] --> B["process_batch: H = zeros on cuda:0"]
    C["run_parallel: batch 1 on cuda:1"] --> D["process_batch: H += inp.matmul(inp.t())"]
    B --> D
    D --> E["RuntimeError: Expected all tensors<br/>to be on the same device"]
    F["native_inps: captured batch 0, batch 1"] --> G["native_inps.pop(0)"]
    C --> G
    G --> H["batch 1 gets batch 0's native input"]
    H --> I["shape mismatch, or silent dXXT corruption"]
    style E fill:#f8d7da,stroke:#c82333
    style I fill:#f8d7da,stroke:#c82333
Loading

Mechanisms removed, with main line evidence:

Old mechanism Where Replaced by
self.H/self.dXXT allocated once on the first batch's device gptqmodel/quantization/gptaq.py:131, gptqmodel/quantization/foem.py:213 One partial per inp.device
self.H += inp.matmul(inp.t()) on the shared accumulator gptaq.py:148, foem.py:226 Per-device recurrence
Global request/token normalization gptaq.py:140, foem.py:219 Per-device count, then count_device / count_total reduction
native_inp = self.native_inps.pop(0) gptaq.py:99, foem.py:178 (batch_index, tensor) capture + keyed lookup
Untagged capture entries gptqmodel/looper/native_processor.py:165 (batch_index, entry)

2. The new flow

flowchart TD
    A["ForwardExecutor.run_parallel<br/>one batch_idx per worker"] --> B["NativeProcessor.pre_process_fwd_hook<br/>batch_index = current_batch_index()"]
    B --> C["native_inp_caches[name] += (batch_index, sample)"]
    C --> D["module.state[NATIVE_INPUTS_STATE_KEY]"]
    D --> E["_take_native_input(batch_index)"]
    F["GPTQProcessor hook<br/>add_batch(inp, batch_index)"] --> G["process_batch(inp, batch_index)"]
    E --> G
    G --> H["_accumulate_device_batch<br/>one partial per inp.device"]
    H --> I["quantize() -> _finalize_gptaq_hessian<br/>or _finalize_foem_hessian"]
    I --> J["sorted(partials, key=_device_reduction_key)<br/>H = sum weight * H_device"]
    J --> K["self.H / self.dXXT on module.target_device"]
    E -. "no entry for batch_index" .-> X["RuntimeError: no native<br/>calibration input for batch N"]
    style X fill:#f8d7da,stroke:#c82333
Loading

The reduction is exact. For R requests and tokens x:

H_device = (2 / count_device) * sum over that device's batches of X X^T
H        = sum over devices of (count_device / count_total) * H_device
         = (2 / count_total) * sum over every batch of X X^T

dXXT uses the same weight. _device_reduction_key is the existing plain-GPTQ key (gptqmodel/quantization/gptq.py:190, used at gptq.py:1288), so both quantizers reduce in the same device order as GPTQ.

3. Failure and ambiguity contract

Situation Before After
Batch on a second device RuntimeError: Expected all tensors to be on the same device Accumulated in that device's partial
Batches complete out of capture order Wrong native sample: shape error, or silently corrupted dXXT when shapes match Keyed lookup pairs the right sample
Batch index has no captured entry Wrong sample or IndexError: pop from empty list RuntimeError naming module and batch
Single device One live accumulator Unchanged: the first device keeps the live self.H/self.dXXT; _finalize_* is a no-op when nothing was split off
Legacy/plain native list Positional pop Positional fallback retained for direct callers and older captures
Routed expert Native capture skipped, dXXT = 0 Unchanged

4. Change inventory

Area File ± Purpose
Capture gptqmodel/looper/native_processor.py +7/−2 Tag per-sample entries with the calibration batch index
GPTAQ gptqmodel/quantization/gptaq.py +171/−24 Per-device partials, keyed native lookup, device-order reduction
FOEM gptqmodel/quantization/foem.py +164/−20 Same for FOEM
Tests tests/test_gptaq_foem_multigpu.py +219 Float64 oracle, keyed pairing, fail-closed, 2-GPU coverage
Docs docs/multi_gpu_quantization.md, docs/native-calibration-batch-split.md +90/−5 New flow page + tagged-entry contract

5. Tests

Test Invariant
test_native_capture_tags_entries_with_calibration_batch_index Capture stores (batch_index, tensor) in capture order
test_native_inputs_pair_by_batch_index_not_arrival_order[gptaq/foem] Out-of-order replay with different lengths matches the float64 H/dXXT oracle
test_missing_batch_index_raises_instead_of_silently_mispairing[gptaq/foem] Missing key fails closed with the batch in the message
test_two_device_partials_reduce_to_float64_oracle[gptaq/foem] Batches on cuda:0/cuda:1 produce one partial each and reduce to the float64 oracle (≤1e-6 normalized error)
test_two_device_quantize_reduces_partials_inside_quantize[gptaq/foem] quantize() performs the reduction itself and emits finite codes

The two-device tests skip when fewer than two CUDA devices are visible.

6. Validation

Environment: CUDA 13, Python 3.14t, OMP_NUM_THREADS=4, 2x RTX 4090 (PCIe, no NVLink). GPU tests were pinned to physical indices 1 and 3 (CUDA_VISIBLE_DEVICES=<uuid-1>,<uuid-3>); index 2 (RTX 5090) was never used.

Issue repro (Qwen/Qwen2.5-0.5B-Instruct, GPTAQConfig(alpha=0.25) / FOEMConfig(alpha=0.25, beta=0.2), 16 variable-length samples, batch_size=1), run on the branch and on a clean origin/main worktree at c45c1b018:

Run main this branch
GPTAQ, 2 GPUs RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cuda:1! at gptaq.py:148 quantize() completed, qweight [112, 896]
FOEM, 2 GPUs same error at foem.py:226 quantize() completed, qweight [112, 896]
test_moe_gptaq_foem.py::test_tiny_qwen2_moe_gptaq_and_foem_quantize RuntimeError at gptaq.py:148 (loader spread the 3 layers over cuda:0 and cuda:1) 1 passed in 20.7 s

Test commands and results:

# branch, pinned 2 GPUs (physical 1,3)
pytest tests/test_gptaq_foem_multigpu.py -q          -> 9 passed
# main worktree, same file
pytest tests/test_gptaq_foem_multigpu.py -q          -> 9 failed
  capture test: untagged tensor entries
  pairing tests: AttributeError: 'tuple' object has no attribute 'to'
  two-device tests: RuntimeError ... cuda:0 and cuda:1
# branch
pytest tests/test_gptaq_foem_batch.py tests/test_moe_gptaq_foem.py -k "not slow" -q
                                                     -> 8 passed, 1 failed
pytest tests/test_gptq.py -k gptaq -q                -> 5 passed
pytest "tests/test_moe_gptaq_foem.py::test_tiny_qwen2_moe_gptaq_and_foem_quantize" -q
                                                     -> 1 passed (20.7 s)
# main worktree, same MoE test, same 2 GPUs
                                                     -> 1 failed at gptaq.py:148
ruff check gptqmodel docs/eora tests setup.py        -> All checks passed

The single failure is test_routed_expert_ignores_mismatched_native_inputs[FOEM-qcfg1] (relative_error 0.6667). It fails identically on origin/main at c45c1b018; its oracle uses GPTAQ's 2/requests normalization for FOEM, which normalizes by tokens. It is unrelated to this change and is left untouched.

7. Reviewer notes

  • native_processor.py is in the diff because it is the pairing-key source: without a tag, the consumer cannot distinguish two batches. Entries are only tagged on the per-sample path that GPTAQ/FOEM already use; every other quantizer still stores one raw tensor per batch.
  • The first device keeps the live self.H/self.dXXT until a second device appears, so task.H inspection in existing tests and the single-device numerics are unchanged.
  • Cross-device moves go through safe_move_to, matching GPTQ's ROCm-safe reduction.
  • Not exercised here: MLX (mlx_gptaq.py is a separate implementation) and ROCm multi-GPU. The CPU out-of-order test covers the pairing logic without CUDA.
  • Docs: new section GPTAQ/FOEM per-device Hessian reduction in docs/multi_gpu_quantization.md, and the tagged-entry contract in docs/native-calibration-batch-split.md (already linked from README.md under "Multi-GPU and memory").

…batch (#4237)

GPTAQ and FOEM allocated `self.H`/`self.dXXT` once, on the first batch's
device, so the next data-parallel batch from another GPU raised at
`self.H += inp.matmul(inp.t())`. Native calibration inputs were consumed with
`native_inps.pop(0)`, which pairs by arrival order; the data-parallel forward
does not preserve capture order, so a reordered batch either raised a shape
mismatch or silently corrupted `dXXT` when the shapes matched.

Keep one Hessian/dXXT partial per input device. Each partial is normalized by
that device's own request count (GPTAQ) or token count (FOEM), and `quantize()`
reduces the partials in `_device_reduction_key` order with weight
`count_device / count_total`. That reproduces the single-device recurrence over
all batches in capture order. The first device keeps the historical live
`self.H`/`self.dXXT`, so the single-device path and direct callers are
unchanged, and `_finalize_*` is a no-op when no partial was split off.

`NativeProcessor` now stores per-sample native entries as
`(batch_index, tensor)`. The consumer scans for the matching batch and fails
closed with the module and batch in the message when no entry exists. Plain
lists from direct callers and older captures keep the positional fallback.

Measured on 2x RTX 4090 (PCIe, CUDA 13), Qwen2.5-0.5B-Instruct, 16
variable-length samples, batch_size=1: both quantizers failed on main with
"Expected all tensors to be on the same device ... cuda:0 and cuda:1" at
gptaq.py:148 / foem.py:226 and now complete quantization with a finite
qweight of shape [112, 896].

Refs #4237
@Qubitium
Qubitium merged commit 625fdf2 into main Nov 16, 2026
6 of 9 checks passed
@Qubitium
Qubitium deleted the fix/issue-4237-gptaq-multigpu branch November 16, 2026 07:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant