Skip to content

fix(gptaq): give every calibrated processor the same shuffled batch order (#4869) - #4985

Merged
Qubitium merged 1 commit into
mainfrom
root/gptaq-shuffle-pairing-4869
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
root/gptaq-shuffle-pairing-4869

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #4869.

Summary

With GPTAQ (and FOEM with alpha > 0) the run plan has two calibrated
processors, NativeProcessor then GPTQProcessor
(gptqmodel/models/quantization_run_plan.py:159). Each one prepared its own
copy of the calibration data inside LoopProcessor.__init__
(gptqmodel/looper/loop_processor.py:574), and ModuleLooper captured inputs
for each processor from its own dataset
(gptqmodel/looper/module_looper.py:2252). With
CalibrationConfig(sort="shuffle") each preparation called the global
random.shuffle (gptqmodel/utils/calibration.py:1282), so the two processors
replayed different batch orders while GPTAQ pairs native and quantized
inputs by batch index (gptqmodel/quantization/gptaq.py:76).

Result on origin/main:

  • variable-length rows: RuntimeError: The size of tensor a (88) must match the size of tensor b (80) inside layer 0 (the issue saw 367 vs 528);
  • equal-length rows: silently wrong dXXT — layer 0 must be exactly 0
    (native and quantized inputs are identical there) but came out at
    ‖dXXT‖₂ = 2562.31, and deeper modules were 10–118× the correct norm;
  • PPL: 31.09 (sort="desc") → 163.69 (sort="shuffle").

What Changed

Follow-up intentionally out of scope: _eora_generate() (post-quantization
adapter generation) is a separate single-pass entry point and still prepares
its own samples.

Logic Flow Documentation

The bug and the fix, with the real symbol names:

flowchart TD
    Q["BaseQModel._quantize_with_calibration"] --> P1["NativeProcessor.__init__"]
    Q --> P2["GPTQProcessor.__init__"]
    P1 --> A["LoopProcessor.__init__:<br/>prepare_dataset(sort='shuffle')<br/>random.shuffle → order A"]
    P2 --> B["LoopProcessor.__init__:<br/>prepare_dataset(sort='shuffle')<br/>random.shuffle → order B"]
    A --> C1["ModuleLooper.cache_inputs(order A)"]
    B --> C2["ModuleLooper.cache_inputs(order B)"]
    C1 --> G["GPTAQ.process_batch(batch_index=i)"]
    C2 --> G
    G --> R["_take_native_input(i) pairs native[i] with quantized[i]<br/>→ unrelated rows → dXXT garbage / size mismatch"]
    style A fill:#fff1f0,stroke:#d4380d
    style B fill:#fff1f0,stroke:#d4380d
    style R fill:#fff1f0,stroke:#d4380d
Loading
flowchart TD
    Q["BaseQModel._quantize_with_calibration"] --> PR["prepare_calibration_dataset_once(calibration_config)<br/>one prepare_dataset + one random.shuffle"]
    PR --> BIND["calibration.bind(already_prepared_calibration_dataset,<br/>dataset=prepared_dataset)"]
    BIND --> P1["NativeProcessor.__init__"]
    BIND --> P2["GPTQProcessor.__init__"]
    P1 --> A["LoopProcessor.__init__ → passthrough<br/>order A"]
    P2 --> B["LoopProcessor.__init__ → passthrough<br/>order A"]
    A --> C1["ModuleLooper.cache_inputs(order A)"]
    B --> C2["ModuleLooper.cache_inputs(order A)"]
    C1 --> G["GPTAQ.process_batch(batch_index=i)"]
    C2 --> G
    G --> OK["native[i] and quantized[i] are the same row<br/>layer 0 → dXXT == 0"]
    style PR fill:#e6f4ff,stroke:#0958d9
    style BIND fill:#e6f4ff,stroke:#0958d9
    style OK fill:#f6ffed,stroke:#389e0d
Loading

Replaced mechanism, file:line evidence (origin/main @ 68cf61f23):

what evidence
per-processor preparation gptqmodel/looper/loop_processor.py:574 in LoopProcessor.__init__
independent shuffle per preparation gptqmodel/utils/calibration.py:1282 (random.shuffle(sorted_dataset))
two calibrated processors gptqmodel/models/quantization_run_plan.py:159
separate capture per processor gptqmodel/looper/module_looper.py:2252
pairing by batch index gptqmodel/quantization/gptaq.py:76 _take_native_input

Failure path (red) is the only one that can mix rows; the success path is drawn
separately above. No user-facing option, default, or resolution order changed,
so no docs/ reference page is added.

Tests

New tests/test_gptaq_shuffle_pairing_4869.py (CPU-only, 2-layer Qwen2
truncation, 13 rows, sort="shuffle"):

  1. test_shuffle_prepares_one_batch_order_for_every_processor — the
    (first token, length) of every prepared batch must be identical for
    NativeProcessor and GPTQProcessor (the pairing invariant).
  2. test_shuffle_keeps_layer0_gptaq_dxxt_zero — 13×128 equal-length rows;
    layer-0 q_proj dXXT must be exactly 0.
  3. test_shuffle_does_not_crash_on_variable_length_rows — 13 rows of 64…160
    tokens; quantize() must complete.

Red on origin/main @ 68cf61f23 (test file copied into a clean worktree):

FAILED tests/test_gptaq_shuffle_pairing_4869.py::test_shuffle_prepares_one_batch_order_for_every_processor
FAILED tests/test_gptaq_shuffle_pairing_4869.py::test_shuffle_keeps_layer0_gptaq_dxxt_zero
FAILED tests/test_gptaq_shuffle_pairing_4869.py::test_shuffle_does_not_crash_on_variable_length_rows
E   AssertionError: GPTAQ pairs native and quantized inputs by batch index, ...
E   AssertionError: layer-0 dXXT must be zero: ..., got 315.60595703125
E   RuntimeError: The size of tensor a (88) must match the size of tensor b (80) at non-singleton dimension 1
6 failed, 140 passed, 23 skipped in 38s   # 3 new + 3 pre-existing

Green on the PR head:

3 passed, 2 warnings in 9.04s

GPTAQ/FOEM + calibration + quantize regression set, same selection on both
trees (tests/test_gptaq_shuffle_pairing_4869.py,
tests/test_gptaq_foem_batch.py, tests/test_moe_gptaq_foem.py,
tests/test_rehome_gptaq_foem_dxxt_4312.py,
tests/test_gptaq_foem_oom_fallback_4604.py, tests/test_quantize_*.py,
tests/test_calibration_config.py, tests/test_generator_calibration_4307.py,
tests/test_looper_concurrency.py):

tree result
origin/main 6 failed, 140 passed, 23 skipped
PR head 3 failed, 149 passed, 23 skipped

Only delta: the 3 new tests. The remaining 3 failures are identical on both
trees and pre-existing:
test_rehome_gptaq_foem_dxxt_4312.py::test_quantize_aligns_dxxt_with_rehomed_hessian[gptaq|foem]
(asserts an internal safe_move_to call, unrelated) and
test_quantize_in_session_4381.py::test_rehome_qqq_initializes_torch_cache_after_class_switch
(QQQTorchLinear._torch_dropped_checkpoint missing).

Calibration suite (tests/test_calibration*.py + tests/test_moe_gptaq_foem.py

  • tests/test_gptaq_foem_multigpu.py + tests/test_mlx_*gptaq|foem*):
tree result
origin/main 2 failed, 228 passed, 11 skipped
PR head 2 failed, 228 passed, 11 skipped

Identical; the 2 failures are the known
tests/test_calibration_data_device.py ones. test_gptaq.py itself is the
full model-compat harness (whole Qwen2.5-0.5B-Instruct + lm_eval ARC) and
cannot run CPU-only here; the new test covers the same GPTAQ path end-to-end on
a tiny model. test_gptaq_foem_multigpu.py (4) and the MLX tests (2) skip for
missing hardware.

export CUDA_HOME=/usr/local/cuda PATH=/usr/local/cuda/bin:$PATH \
  TORCH_CUDA_ARCH_LIST=8.0 TORCH_NO_COMPILER_WRAPPER=1 \
  GPTQ_BYPASS_SAFETY_CHECKS=1 LOGBAR_ANIMATION=0 CUDA_VISIBLE_DEVICES="" \
  PYTHONPATH=$PWD HF_HUB_OFFLINE=1
/root/venv-kernels/bin/python /tmp/root-rt.py \
  tests/test_gptaq_shuffle_pairing_4869.py tests/test_gptaq_foem_batch.py \
  tests/test_moe_gptaq_foem.py tests/test_rehome_gptaq_foem_dxxt_4312.py \
  tests/test_gptaq_foem_oom_fallback_4604.py tests/test_quantize_run_summary.py \
  tests/test_quantize_call_signature_4868.py tests/test_quantize_config_offload_tempdir.py \
  tests/test_quantize_in_session_4381.py tests/test_quantize_device_sequence_4875.py \
  tests/test_calibration_config.py tests/test_generator_calibration_4307.py \
  tests/test_looper_concurrency.py -q -o addopts= -o log_cli=false -p no:cacheprovider
/root/venv-py3.14t-gil0/bin/ruff check gptqmodel/looper/loop_processor.py \
  gptqmodel/models/base.py tests/test_gptaq_shuffle_pairing_4869.py

Measurements

dXXT norm (‖dXXT‖₂), CPU, 2-layer Qwen2.5 truncation, 13 rows × 128 tokens,
GPTAQ 4-bit g32, batch_size=1:

module sort="desc" origin/main + shuffle PR head + shuffle
layers.0.self_attn.q_proj 0.0 2562.31 0.0
layers.0.self_attn.o_proj 0.33992 4.86833 (14.3×) 0.33992 (1.000×)
layers.0.mlp.gate_proj 21.31028 2504.83 (117.5×) 21.31028 (1.000×)
layers.0.mlp.down_proj 0.054915 0.55733 (10.1×) 0.054915 (1.000×)
layers.1.self_attn.q_proj 32.24944 2503.67 (77.6×) 32.24944 (1.000×)

sort="desc" / sort=None are unchanged bit for bit: the SHA-256 of every
recorded module's dXXT is identical on origin/main and on the PR head (8/8
leader modules; shared-input followers such as k_proj/v_proj/up_proj
adopt the leader's Hessian and record none), and desc == none.

PPL (CPU fp16, HuggingFaceTB/SmolLM2-135M, GPTAQ 4-bit g128, 64 calibration
rows × 256 tokens from wikitext-2 train, 16 × 256-token wikitext-2 test
windows, in-session model):

tree sort="desc" sort="shuffle"
origin/main 31.086 163.688
PR head 31.086 31.666

Control on the same eval (plain GPTQ 4-bit g128, no GPTAQ, so batch order
only changes float accumulation order): sort="desc" 32.388 vs
sort="shuffle" 32.621 (+0.7%). Batch order therefore moves this eval by ~1%
on its own; GPTAQ accumulates both H and dXXT, so its residual sensitivity
is a little larger. The broken run was 5.3x worse, not 1.9% worse.

Model Support / Module Plan

Not applicable — no model definitions, MODEL_MAP entries, module plans or
fusion configs change.

AWQ onboarding safety

Not applicable — no AWQ grouping/search/replay/fold code is touched.

Review Requirements

  • Reviewed this PR.
  • Matches existing project structure: the preparation step stays in
    loop_processor.py (the issue asked not to touch utils/calibration.py,
    which another change owns).
  • No monkeypatching; uses the existing CalibrationConfig.bind() extension
    point.
  • Minimal surface: one moved function plus one rebind in
    _quantize_with_calibration.
  • Regression risk considered: desc/None are bit-identical (hash check
    above); per-processor construction still prepares once, so direct
    callers and unit tests are unaffected.

Kernel Accuracy Requirements

Not applicable — no kernel, fusion or packing code changes.

Notes

sort="shuffle" now produces one order per run. It is still random per run, so
two shuffle runs are not expected to be bit-identical to each other; the
invariant is that within a run every calibrated processor sees the same
order.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Extra data point on the residual desc↔shuffle PPL gap (same setup as the
table above, independent shuffle draw because random is unseeded per run):

run PPL
GPTAQ, sort="desc" 31.086
GPTAQ, sort="shuffle" (draw 1) 31.666
GPTAQ, sort="shuffle" (draw 2) 31.496
GPTQ control, sort="desc" 32.388
GPTQ control, sort="shuffle" 32.621

So after the fix shuffle is within ~1.5% of desc, which is the same order of
magnitude as plain GPTQ's batch-order sensitivity on this eval (0.7%) — GPTAQ
accumulates H and dXXT, and with equal-length rows the incremental
accumulation weights are identical for every order, so what changes is float
rounding feeding the discrete 4-bit rounding decisions. The pairing itself is
exact: layer-0 dXXT is 0.0 and every recorded module's dXXT matches
sort="desc" to 1e-7.

GPTAQ and FOEM pair the native capture with the quantized capture by
calibration batch index. Every LoopProcessor prepared its own copy of the
calibration data, so CalibrationConfig(sort="shuffle") gave NativeProcessor
and GPTQProcessor two different batch orders: variable-length rows crashed
inside layer 0 with a tensor-size mismatch, and equal-length rows silently
mixed unrelated sequences into dXXT (layer 0 must be exactly zero).

quantize() now prepares the batches once (main and EoRA adapter samples) and
binds a passthrough preparer, so every calibrated processor in the chain
replays the same list and order. sort="desc"/None produce the same prepared
data as before.

Adds tests/test_gptaq_shuffle_pairing_4869.py: both processors must see one
batch order, layer-0 dXXT must be zero with sort="shuffle", and variable-length
rows must quantize without the size mismatch.

Fixes #4869
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