Skip to content

[BUG] Regression from #5236 (fix of #5233): AWQ _layer_input_features keys its sibling-share caches on id() of reservoir views that are freed each iteration - routed experts silently get another expert's rows and replay kwargs #5267

Closed

Description

@Qubitium

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_proj share hidden, and all down_proj share moe_intermediate.
  • Visible (only when widths differ): a down_proj that receives an up_proj capture fails validation, so the up_proj -> down_proj group 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 vs e75181df5) 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 verify cached_tensors[i] is tensors[i].
  • Or skip cat_cache/token_row_kwargs_cache for 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

  1. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    More data from an independent repro (ROCm, bf16, main @ c1807f8). The same root cause also crashes dense models:

    • Dense models reach this path as well. With CalibrationConfig(exclude_attention_sinks=True) at batch_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, and down_proj (8192 wide) can alias a 2048-wide sibling. The clip search does not catch the width mismatch, so the run aborts:
      Llama-3.2-1B-Instruct (2-layer copy), AWQConfig(bits=4, group_size=128), 64 C4 rows, bs=1, exclude_attention_sinks=True
      LAYER 0 reservoir modules checked=7 got-foreign-rows=1
          ('mlp.down_proj', (1, 906, 2048), (906, 8192), 'self_attn.q_proj')
        File "gptqmodel/looper/awq_processor.py", line 4451, in _compute_best_clip
      RuntimeError: The size of tensor a (16) must match the size of tensor b (64) at non-singleton dimension 2
      
      An uninstrumented quantize of the full Llama-3.2-1B-Instruct (512 short C4 rows, bs=1, exclude_attention_sinks=True) failed with the same RuntimeError in _compute_best_clip, at layer 5 in one run and at a different layer in the next.
    • Rate at bs=1 on OLMoE. OLMoE-1B-7B-0924 2-layer copy, 128 C4 rows (300-600 chars), bs=1, default 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

  2. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim: agent-4e3a0639ecaf is 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

  3. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-4e3a0639ecaf finished this issue.

    PR: #5293 — base main, head 3bd17a048 (branch fix/5267-awq-sibling-key), 2 files.

    Root cause

    AWQProcessor._layer_input_features dedupes sibling captures (q/k/v, gate/up) with cat_cache / token_row_kwargs_cache, keyed on tuple(id(t) for t in tensors). Before #5236 the keyed tensors stayed alive in entry["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 rebinds tensors. CPython reuses that address for the next module's view, so the id() key matched and one module received another's concatenated rows and packed mask/positions. When the widths match (all gate/up share hidden) it was silent; a down_proj receiving an up_proj capture 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

    • New tests/test_awq_reservoir_sibling_rows_5267.py: 1 failed, 3 passed on pristine main (the reservoir case), 4 passed with the fix (re-verified by the parent agent); with test_awq_reservoir_incremental_5233.py + test_awq_hash_moe_kept_rows_5015.py: 11 passed.
    • Full AWQ family suite (GPU 1, 1108 tests): 1032 passed, 71 skipped, 5 failed — all five are the known offline-cache misses (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 pristine main.
    • uvx [email protected] check gptqmodel docs/eora tests setup.py clean.

    Not verified: ROCm; the model-level repro uses the unit fixtures rather than a full MoE checkpoint.

  4. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    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.

    tree run 1 run 2
    396b5f0 fb1c7ff0 fb1c7ff0
    f58fcfc (#5212) 107c5dbc 107c5dbc
    c32411c (parent of #5236) 107c5dbc 107c5dbc
    0cf4d8e (#5236) b6dbf4c4 9bbb5508
    main e0d07ce6 3f6495fc
    main + views kept alive in _materialize_reservoir_provenance (no id() reuse) 8de652bf 8de652bf
    main + views kept alive + survivors re-sorted by (source,row) before replay 107c5dbc 107c5dbc (bitwise equal to #5212)

    Between two identical main runs, 1425-1487 of 2375 tensors differ. The differences start at layer 0, in the up_proj/down_proj/gate_proj qweight 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions