Skip to content

fix(awq): validate the plan path's sampled-row cache against the live host copy - #6479

Merged
Qubitium merged 1 commit into
mainfrom
fix/awq-moe-gpu-determinism
Nov 30, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/awq-moe-gpu-determinism

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

On CUDA, AWQ quantization of a routed MoE gave different results on identical runs. With the tiny qwen3_moe recovery fixture (2 layers, hidden 64, 4 experts, fp16), three back-to-back runs of tests/checkpoint_quantization_driver.py --mode baseline --device cuda:0 --method awq saved different model.layers.1.mlp.experts.3.{down,up}_proj qweight/scales. Every other tensor matched. Because of this, test_awq_checkpoint_recovery[*-qwen3_moe] failed intermittently. CPU runs were bit-identical.

Root cause. On the plan path, AWQProcessor._record_input_feature caches each host copy's sampled rows in _capture_sampled_cache. The key is (_capture_share_key(host), quota), and _capture_share_key is (batch, data_ptr, shape, stride, dtype, version, keep-mask). Calibration tensors are inference tensors, so version is None and the key comes down to the host address.

Under ExpertsRoutingOverride, every expert's down_proj input has the same shape. An expert's host copy is released as soon as the next expert's capture replaces it in _capture_host_cache. When the host allocator gave that address to a later expert's copy, the bare key matched, and the later down_proj was scaled and clipped on another expert's rows. The up_proj change is just the folded down_proj scale.

Whether an address got recycled depended on allocation timing, which is why the result changed between runs. _capture_host_cache already checks that a hit names the same live tensor through a weakref (#5267 added the same guard to the replay-side caches). The sampled cache was the one cache without that check.

Fix. Read and write the sampled cache through the existing _sibling_capture_get / _sibling_capture_put helpers, passing (share_key, quota) as extra. A hit now has to name the same live host tensor. q/k/v and gate/up siblings still sample once; a recycled address now misses. No new mechanism, config or env switch.

Where two runs first diverged (evidence)

I traced the run with debug-only hooks in a scratch wrapper, not in the PR. The hooks hashed every _AWQTokenRowOwner.submit capture, _layer_input_features output, _compute_best_scale input (x, x_mean, w_mean, FP reference), every replay chunk and every clip result:

  • Everything matched up to and including layer 1's gate/up captures for expert 3, and all layer-0 state matched too.
  • The first difference was the capture layer 1 mlp.experts.3.down_proj, batch 0. It differed across the whole tensor (max |d| 0.09), not by rounding noise.
  • In the failing runs that capture was bit-equal to mlp.experts.1.down_proj batch 0, i.e. another expert's rows. The run that differed showed no such alias.
  • A share-key probe recorded repeated host-tensor keys whose earlier tensor was already dead ("recycled address") in every GPU run; it recorded none on CPU.
  • Main runs that happened to have no alias produced output bit-identical to this branch's output.

Routing, token order, reductions, x_mean/w_mean, the scale-grid tie-break and the replay forward were all identical across runs once the capture was the same. So this is not GPU reduction or atomics nondeterminism.

AWQ GEMM Triton logits. The separate observation that AWQ GEMM Triton logits vary between runs has a different cause. That inference kernel's split-K reduction uses tl.atomic_add by design (see _single_split_required in gptqmodel/quantization/awq/modules/triton/scheduler.py, which already switches to one split under torch.use_deterministic_algorithms). AWQ quantization never runs that kernel, and the recovery matrix uses BACKEND.TORCH. Out of scope here.

What Changed

  • gptqmodel/looper/awq_processor.py: the plan-path sampled-row cache is validated against the live host tensor (+18/−5).
  • tests/test_awq_reservoir_sibling_rows_5267.py: new CPU unit regression in the sibling-cache family. It reuses one inference-mode buffer to recycle a host address deterministically, then checks that the second expert keeps its own sampled rows, both at capture and after _layer_input_features.
  • tests/test_awq_moe_gpu_determinism.py (new, # GPU=1, cuda marker): quantizes a tiny 8-expert qwen3_moe twice in one process on CUDA and asserts every saved tensor is bit-identical. Skips cleanly without CUDA.
  • No API or config changes. Follow-ups: none.

Tests

  • Unit tests have been executed and passed, or the reason they are not applicable is documented.
  • I added a new simple/fast unit test for this change, or documented why that is not applicable.
# CPU unit regression (red on origin/main, green here)
CUDA_VISIBLE_DEVICES= python -P -m pytest -q tests/test_awq_reservoir_sibling_rows_5267.py
# origin/main: 1 failed, 5 passed
#   AssertionError: the second expert received the first expert's sampled rows; assert {1.0} == {3.0}
# branch:      6 passed

# CUDA determinism regression, 6 invocations per tree, one GPU
CUDA_VISIBLE_DEVICES=<gpu> python -P -m pytest -q tests/test_awq_moe_gpu_determinism.py
# origin/main: 6/6 failed (~7 s each), e.g.
#   run 1 quantized 87 tensors differently from run 0, e.g. ['model.layers.0.mlp.experts.1.down_proj.qweight', ...]
# branch:      6/6 passed (6.5-7.0 s each)

# Touched-code families (CPU)
CUDA_VISIBLE_DEVICES= python -P -m pytest -q tests/test_awq_reservoir_sibling_rows_5267.py \
  tests/test_awq_reservoir_arrival_order_5507.py tests/test_awq_reservoir_batch_index_priority_5432.py \
  tests/test_awq_reservoir_growing_cap_5384.py tests/test_awq_reservoir_incremental_5233.py \
  tests/test_awq_token_rows_bounded_capture_5137.py tests/test_awq_sink_token_rows_5275.py \
  tests/test_awq_moe_padding_rows_5337.py tests/test_awq_moe_quant_speed_5284.py \
  tests/test_awq_capture_perf_5284.py tests/test_awq_scale_search_memory.py \
  tests/test_calibration_attention_sinks.py tests/test_awq_token_row_position_5265.py \
  tests/test_awq_moe_starved_expert_group_4675.py tests/test_awq_hash_moe_kept_rows_5015.py \
  tests/test_awq_moe_gpu_determinism.py
# 145 passed, 1 skipped (the CUDA test, CPU-only run)

# AWQ checkpoint-recovery matrix (16 cases), one GPU
python -P -m pytest -q -m checkpoint_recovery -k awq tests/test_checkpoint_method_compatibility.py
# branch, 3 consecutive runs (16 test_awq_checkpoint_recovery cases + 7 AWQ format cases):
#   run 1: 22 passed, 1 skipped in 518.54s
#   run 2: 22 passed, 1 skipped in 600.16s
#   run 3: 22 passed, 1 skipped in 691.15s
#   skip: test_format_checkpoint_recovery[awq-bitblas] (optional BitBLAS runtime not installed)
# origin/main, 1 run: 5 failed, 17 passed, 1 skipped
#   4 failures are `assert_identical_tensors`: model.layers.1.mlp.experts.3.down_proj.scales
#     ([False-kill-after-qwen3_moe], [True-term-qwen3_moe], [True-kill-after-qwen3_moe], [True-error-qwen3_moe])
#   1 failure, [True-term-llama], is unrelated: the resume refused with
#     `CheckpointError: incompatible checkpoint identity fields: device_topology` (see Notes)

bash format/check.sh   # All checks passed! (ruff 0.14.2)

test_plan_path_siblings_still_share_one_capture is the positive control: q/k/v still share one sampled capture object.

Measured Impact

Metric (unit) Before After Change
Tiny qwen3_moe AWQ driver, 3-4 CUDA runs: distinct outputs 3 of 3 pairs differ 4 runs bit-identical deterministic
Qwen2.5-0.5B-Instruct AWQ (dense, GEMM, g128, 64 wikitext rows) saved tensors reference 626/626 tensors + 5 json bit-identical none
Qwen2.5-0.5B-Instruct AWQ wall time (s), shared GPU 103 98 noise
Qwen2.5-0.5B-Instruct AWQ peak CUDA (MiB) 387 387 0
Tiny 8-expert CUDA test wall time, 2 quantizes (s) 6.7-7.2 6.5-7.0 noise

The fix adds one weakref per sampled-cache insert and one dereference per lookup, i.e. per unique host capture per batch. There's no measurable cost. Dense AWQ output is unchanged.

The MoE outputs that change are the ones that used to be corrupted: an aliased down_proj was scaled and clipped on another expert's activations. The branch's output equals the alias-free main runs bit for bit.

Model Support / Module Plan

Not applicable: no model, alias, definition or module-plan change.

Model test node IDs and results (or "not applicable"): not applicable.

AWQ onboarding safety

Not applicable for onboarding: no grouping, search, replay or fold rule changed. This fixes which activation rows the existing capture hands to the scale and clip search. Evidence is above: the per-capture trace, the dense A/B, and the MoE recovery matrix.

Logic Flow Documentation

  • This change does not alter a major logic flow, or the required diagrams and docs page are included below.

Diagram summary: not applicable. This is a local fix to one cache's hit check, and it reuses the existing weakref-validated helpers; no control flow, selection order or lifecycle changes.

Review Requirements

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

Not applicable: no kernel, dispatch or fusion change.

Notes

  • The mechanism isn't specific to any device or model. Any plan-path capture can hit it once a host copy dies and its address is reused within one batch with the same shape. CPU runs of the fixture didn't hit it because there _materialize_host_feature returns a detach() of the live activation instead of a fresh D2H allocation. The CPU unit test shows the defect without a GPU.
  • Unrelated observation, not fixed here: the single main matrix run (on a GPU shared with other jobs) also failed test_awq_checkpoint_recovery[True-term-llama] because the resume refused the checkpoint with incompatible checkpoint identity fields: device_topology. A plausible but unverified cause: _gpu_serials_by_uuid (gptqmodel/looper/checkpoint_devices.py) returns {} when nvidia-smi exceeds its 5 s timeout, so the recorded serial can differ between the run and the resume. That case passed in all three branch runs.
  • Unverified: multi-GPU / PYTHON_GIL=0 runs; I only tested a single visible GPU.

🤖 Generated with Claude Code

… host copy

AWQ on a routed MoE quantized differently from run to run on CUDA: on the
tiny qwen3_moe recovery fixture, layers.1.mlp.experts.3.{up,down}_proj
qweight/scales changed between identical runs, so
test_awq_checkpoint_recovery[*-qwen3_moe] failed intermittently.

Cause: `_record_input_feature` caches each host copy's plan-sampled rows
in `_capture_sampled_cache` under `_capture_share_key(host)`, which is
(batch, data_ptr, shape, stride, dtype, version, keep-mask). Calibration
tensors are inference tensors, so version is None and the key is just the
host address. Under ExpertsRoutingOverride every expert's down_proj input
has the same shape, and an expert's host copy is released as soon as the
next expert's capture replaces it in `_capture_host_cache`. When the host
allocator handed that address to a later expert's copy, the bare key hit
and the later down_proj was scaled and clipped on another expert's rows
(the up_proj change is the folded down_proj scale). Whether an address was
recycled depended on allocation timing, hence the nondeterminism. Traced
runs show the first divergence is exactly that capture: experts.3.down_proj
batch 0 bit-equal to experts.1.down_proj batch 0 in the failing runs, with
every other activation, x_mean/w_mean and replay identical.

Fix: store and check the entry through `_sibling_capture_get/_put`, the
weakref-validated helpers the replay-side caches already use (#5267), with
(share_key, quota) as the extra key. A hit now requires the entry to name
the same live host tensor, so q/k/v and gate/up still sample once while a
recycled address misses. The host cache already had this guard; the
sampled cache missed it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium marked this pull request as ready for review November 30, 2026 05:29
@Qubitium
Qubitium merged commit 522e4c0 into main Nov 30, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/awq-moe-gpu-determinism branch November 30, 2026 05:29
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.

1 participant