Repository navigation
fix(gptaq): accumulate per-device Hessians and pair native inputs by batch (#4237) - #4284
Merged
Merged
Conversation
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #4237
TL;DR
GPTAQ/FOEM now keep one Hessian/
dXXTpartial per input device and reduce them in device order atquantize(), and native calibration inputs are paired by calibration batch index instead ofpop(0)order. Net diff: +651/−51 across 6 files; the single-device path, routed-expert path, anddXXT = 0fallback are unchanged.1. The problem
run_parallelfans 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:#c82333Mechanisms removed, with
mainline evidence:self.H/self.dXXTallocated once on the first batch's devicegptqmodel/quantization/gptaq.py:131,gptqmodel/quantization/foem.py:213inp.deviceself.H += inp.matmul(inp.t())on the shared accumulatorgptaq.py:148,foem.py:226gptaq.py:140,foem.py:219count_device / count_totalreductionnative_inp = self.native_inps.pop(0)gptaq.py:99,foem.py:178(batch_index, tensor)capture + keyed lookupgptqmodel/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:#c82333The reduction is exact. For
Rrequests and tokensx:dXXTuses the same weight._device_reduction_keyis the existing plain-GPTQ key (gptqmodel/quantization/gptq.py:190, used atgptq.py:1288), so both quantizers reduce in the same device order as GPTQ.3. Failure and ambiguity contract
RuntimeError: Expected all tensors to be on the same devicedXXTwhen shapes matchIndexError: pop from empty listRuntimeErrornaming module and batchself.H/self.dXXT;_finalize_*is a no-op when nothing was split offdXXT = 04. Change inventory
gptqmodel/looper/native_processor.pygptqmodel/quantization/gptaq.pygptqmodel/quantization/foem.pytests/test_gptaq_foem_multigpu.pydocs/multi_gpu_quantization.md,docs/native-calibration-batch-split.md5. Tests
test_native_capture_tags_entries_with_calibration_batch_index(batch_index, tensor)in capture ordertest_native_inputs_pair_by_batch_index_not_arrival_order[gptaq/foem]H/dXXToracletest_missing_batch_index_raises_instead_of_silently_mispairing[gptaq/foem]test_two_device_partials_reduce_to_float64_oracle[gptaq/foem]cuda:0/cuda:1produce 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 codesThe 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 cleanorigin/mainworktree atc45c1b018:RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cuda:1!atgptaq.py:148quantize()completed,qweight[112, 896]foem.py:226quantize()completed,qweight[112, 896]test_moe_gptaq_foem.py::test_tiny_qwen2_moe_gptaq_and_foem_quantizeRuntimeErroratgptaq.py:148(loader spread the 3 layers overcuda:0andcuda:1)1 passedin 20.7 sTest commands and results:
The single failure is
test_routed_expert_ignores_mismatched_native_inputs[FOEM-qcfg1](relative_error 0.6667). It fails identically onorigin/mainatc45c1b018; its oracle uses GPTAQ's2/requestsnormalization for FOEM, which normalizes by tokens. It is unrelated to this change and is left untouched.7. Reviewer notes
native_processor.pyis 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.self.H/self.dXXTuntil a second device appears, sotask.Hinspection in existing tests and the single-device numerics are unchanged.safe_move_to, matching GPTQ's ROCm-safe reduction.mlx_gptaq.pyis a separate implementation) and ROCm multi-GPU. The CPU out-of-order test covers the pairing logic without CUDA.GPTAQ/FOEM per-device Hessian reductionindocs/multi_gpu_quantization.md, and the tagged-entry contract indocs/native-calibration-batch-split.md(already linked fromREADME.mdunder "Multi-GPU and memory").