Repository navigation
Description
Found on main @ c1807f8, CPU (the logic is device-independent).
What is wrong
#5236 (fix of #5233, 0cf4d8e1a) keeps each routed expert's capture in a reservoir buffer. _layer_input_features materializes it per module via _materialize_reservoir_provenance (gptqmodel/looper/awq_processor.py ~L1505), which stores a fresh temporary view buffer[:used].unsqueeze(0) in entry["inputs"].
The token-row branch of _layer_input_features (~L2950) then dedupes sibling captures with
cache_key = tuple(id(tensor) for tensor in tensors)
cat_tensor = cat_cache.get(cache_key) # and token_row_kwargs_cache.get(cache_key)and immediately replaces entry["inputs"] = [features[name]]. The view from the previous module is now unreferenced and freed, so CPython hands the same id() to the next module's freshly created view. The cache key matches, and that module receives the previous module's rows (cat_cache) and replay kwargs (token_row_kwargs_cache: packed mask, positions, provenance). The id() key was safe before #5236, because the captured tensors were long-lived objects held by entry["inputs"]. A reservoir view lives only for one loop iteration.
Consequences:
- Silent (the common case): the expert's AWQ scale search runs on another expert's activations, with that expert's row count and mask. Every check passes because the widths match: all
gate_proj/up_projsharehidden, and alldown_projsharemoe_intermediate. - Visible (only when widths differ): a
down_projthat receives anup_projcapture fails validation, so theup_proj -> down_projgroup is dropped and the module falls back to plain quantization:AWQ: target 'mlp.experts.1.down_proj' does not accept the 32-channel source input.This is how the problem showed up. A 99-family AWQ sweep (main vse75181df5) lost this group on MiniMax, GraniteMoE-SWA and Cohere2-MoE.
Repro 1 (deterministic, CPU, no model)
_processor is copied verbatim from tests/test_awq_reservoir_incremental_5233.py.
p = _processor(max_tokens=64, hidden=4)
names = [f"mlp.experts.{e}.{proj}" for e in range(8) for proj in ("gate_proj", "up_proj")]
for b in range(3):
p._set_current_batch_index(b)
for i, n in enumerate(names): # each module's rows are filled with its own index i
p._record_input_feature(n, torch.full((1, 2 + (i + b) % 5, 4), float(i)))
out = p._layer_input_features(_AWQLayerState(modules={n: torch.nn.Linear(4, 4) for n in names}))
bad = [(n, sorted(set(out[n][0, :, 0].tolist()))) for i, n in enumerate(names) if set(out[n][0, :, 0].tolist()) != {float(i)}]
print(f"{len(bad)}/{len(names)} modules got another module's rows:", bad)| tree | output |
|---|---|
| main c1807f8 | 1/16 modules got another module's rows: [('mlp.experts.1.up_proj', [1.0])] (should be 3.0) |
| 0cf4d8e (#5236) | 2/16 ... [('mlp.experts.1.up_proj', [1.0]), ('mlp.experts.4.gate_proj', [6.0])] |
| 0cf4d8e^ | 0/16 |
| e75181d | 0/16 |
Repro 2 (real checkpoints, 1-layer config copies, CPU)
Setup: AWQConfig(bits=4, group_size=128), 32 random-token rows, batch_size=4. A hook compares each reservoir module's own materialized rows with what _layer_input_features returned for it:
OLMoE-1B-7B-0924 (64 experts): 10 of 180 reservoir modules got another module's rows, e.g. mlp.experts.28.up_proj got (1,102,2048), own (1,97,2048)
Qwen1.5-MoE-A2.7B (60 experts): 15 of 192, e.g. mlp.experts.13.gate_proj got (1,288,2048), own (1,80,2048);
mlp.experts.13.up_proj got (1,278,2048) -> gate and up of the same expert disagree
On the tiny MiniMax used in the family sweep, mlp.experts.1.down_proj fell back to plain quant in 4 of 4 runs at 0cf4d8e, in 4 of 9 runs on main, and in 0 of 12 runs at 0cf4d8e^, f58fcfc^ or e75181d. Which module collides depends on allocation order.
Suggested fix
Do not key caches on id() of objects the loop itself drops. Options:
- Keep the keyed tensors alive for the lifetime of the cache, e.g. store
(tensors, cat_tensor)and verifycached_tensors[i] is tensors[i]. - Or skip
cat_cache/token_row_kwargs_cachefor entries that came from a reservoir: each has its own buffer, so there is nothing to share. - Or key on
(untyped_storage().data_ptr(), storage_offset, shape, stride)while still holding a reference.
Test that should have caught it
tests/test_awq_reservoir_incremental_5233.py only materializes one module. A test that records reservoir captures for several modules with distinct values and checks that each module's _layer_input_features output is its own would catch it, as Repro 1 does.
Severity
High for AWQ on MoE models since #5236. Routed experts silently get AWQ scales computed from another expert's activations and replay kwargs, about 5-8% of reservoir modules per layer in the real-model measurement. Some groups also fall back to plain quantization when the widths differ.
🤖 Generated with Claude Code
Activity
Qubitium commentedon Nov 18, 2026
More data from an independent repro (ROCm, bf16,
main@ c1807f8). The same root cause also crashes dense models:CalibrationConfig(exclude_attention_sinks=True)atbatch_size=1, every dense module and MoE root falls out of the token-row plan into the reservoir. The plan lengths come out as 0 in that configuration; I filed that root cause separately. All seven Llama projections are then reservoir entries, anddown_proj(8192 wide) can alias a 2048-wide sibling. The clip search does not catch the width mismatch, so the run aborts:exclude_attention_sinks=True) failed with the sameRuntimeErrorin_compute_best_clip, at layer 5 in one run and at a different layer in the next.AWQConfig: 31 of 192 reservoir modules in layer 0 and 30 of 192 in layer 1 got another expert's rows (about 16%). Examples:experts.6.gate_proj<-experts.4.gate_proj,experts.7.up_proj<-experts.4.gate_proj.🤖 Generated with Claude Code
Qubitium commentedon Nov 18, 2026
Agent claim:
agent-4e3a0639ecafis working on this issue now.Started 2026-11-18T16:25:46Z. The claim expires 4.0h after this comment is last edited (heartbeat). Other agents: do not start this issue while the claim is live.
Scope: fix the #5236 regression: AWQ _layer_input_features must key its sibling-shared captures correctly so a shared-expert projection is not fed another sibling's rows; add a routed+shared regression test
Qubitium commentedon Nov 18, 2026
Agent claim released:
agent-4e3a0639ecaffinished this issue.PR: #5293 — base
main, head3bd17a048(branchfix/5267-awq-sibling-key), 2 files.Root cause
AWQProcessor._layer_input_featuresdedupes sibling captures (q/k/v, gate/up) withcat_cache/token_row_kwargs_cache, keyed ontuple(id(t) for t in tensors). Before #5236 the keyed tensors stayed alive inentry["inputs"]for the whole run; #5236 replaced a routed expert's replay input with a fresh temporary view (buffer[:used].unsqueeze(0)), which the loop drops when it rebindstensors. CPython reuses that address for the next module's view, so theid()key matched and one module received another's concatenated rows and packed mask/positions. When the widths match (all gate/up sharehidden) it was silent; adown_projreceiving anup_projcapture failed validation and the group fell back to plain quantization — the visible symptom.Fix
Keep the
id()fast path but store(weakrefs, payload)per key: a hit requires every weak reference to still resolve to the same live object. A dead reference proves the id was reusable, so it is a miss and the payload is recomputed. Only weak references are retained, so reservoir buffers are not pinned for the rest of the layer, and #5236's in-place merge (capture copies only surviving rows; replay materializes one view per module) is unchanged.Evidence
tests/test_awq_reservoir_sibling_rows_5267.py: 1 failed, 3 passed on pristinemain(the reservoir case), 4 passed with the fix (re-verified by the parent agent); withtest_awq_reservoir_incremental_5233.py+test_awq_hash_moe_kept_rows_5015.py: 11 passed.test_real_checkpoint_awq_cpu_roundtrip[moe],test_inference_quantized_by_llm_awq,test_inference_mistral_awq, and the two wikitext-dependent ones), identical on pristinemain.uvx [email protected] check gptqmodel docs/eora tests setup.pyclean.Not verified: ROCm; the model-level repro uses the unit fixtures rather than a full MoE checkpoint.
Qubitium commentedon Nov 18, 2026
More data: on a real model, this id() reuse makes MoE AWQ quantization non-deterministic from run to run, and the PR should pin determinism.
Setup:
main@ c1807f8, RTX 4090. OLMoE-1B-7B-0924 truncated to 4 layers (config copy),AWQConfig(bits=4, group_size=128), fp16, 128 C4 docs. The same script was run twice per tree, and the result is the hash of the saved safetensors._materialize_reservoir_provenance(no id() reuse)Between two identical main runs, 1425-1487 of 2375 tensors differ. The differences start at layer 0, in the
up_proj/down_proj/gate_projqweight and scales of 53-62 of the 64 experts. Sorting the reservoir alone did not help (main + sort: cec38fde vs da47aedf). Only removing the id() reuse made the runs reproducible. Which modules collide depends on allocator state, so the wrong-rows effect from this issue lands on different experts in every run.The quality effect on this small model is within noise: KL to the fp16 model over 20 wikitext windows is 0.0708 (main) vs 0.0699 (#5212) vs 0.0704 (396b5f0). Still, a quantize that is not reproducible breaks checkpoint-hash regression testing for every MoE AWQ run.
Suggested addition to the fix: a regression test that quantizes the same tiny routed-expert stub twice in one process, with garbage collection between the runs, and asserts equal outputs. If the reservoir slot order is not restored to capture order, also say in the PR that #5236 output differs bitwise from #5212 (8de652bf vs 107c5dbc) even after the id() fix.
🤖 Generated with Claude Code
fix(awq): key the sibling capture caches on live tensors, not bare ids (
Merge origin/main into transformers5-local-models
fix(awq): validate the plan path's sampled-row cache against the live…