Skip to content

fix(moe): scale AWQ norm consumers, split MLA fold groups, guard ERNIE patch, drop padding rows (#4017) - #4035

Merged
Qubitium merged 3 commits into
mainfrom
fix/issue-4017
Nov 14, 2026
Merged

Qubitium merged 3 commits into
mainfrom
fix/issue-4017

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4017

TL;DR

Five MoE/AWQ defects, one of them a dependency contract:

  1. AWQ folded a norm by s but only scaled the quantized consumers, so the MoE
    router and shared_expert_gate kept reading x / s and routing changed.
  2. DeepSeek-V2/V3 MLA blocks folded layers with different inputs into one norm
    and crashed inside the scale search.
  3. ERNIE 4.5 MoE replaced the native transformers forward with remote code
    that calls the removed _update_causal_mask.
  4. Calibration padding reached routed-expert and 2-D shared-expert Hessians
    whenever the calibration batch was padded.
  5. defuser>=0.0.30 was only pinned in requirements.txt, so an older release
    silently left fused 3-D experts unquantized.

Net diff: 7 files, +422/-14 before the #4005 merge; this branch was merged with
origin/main after #4005 landed and preserves both fixes.

1. The problem

1a. Unscaled norm consumers (item 1)

awq_get_modules_for_scaling (gptqmodel/models/base.py:4773 on main@e088f0d23)
builds the norm -> expert gate/up group. apply_scale / scale_ln_fcs
(gptqmodel/quantization/awq/quantize/scale.py:139, :192) divide the norm by
s and multiply each expert's gate/up by s. The router (mlp.gate) and
Qwen2's shared_expert_gate read the same normed tensor and were not rescaled.

flowchart TD
    N["post_attention_layernorm weight /= s"] --> X["x / s"]
    X --> E["expert gate/up weight *= s"]
    X --> R["router weight unchanged"]
    X --> G["shared_expert_gate unchanged"]
    E --> OK["experts see x"]
    R --> BAD["router sees x / s"]
    G --> BAD2["shared gate sees x / s"]
    classDef bad fill:#ffd6d6,stroke:#c00,color:#900
    class R,G,BAD,BAD2 bad
Loading

1b. MLA groups (item 2)

The DeepSeek tree keeps q_a_proj, q_b_proj, q_proj, kv_a_proj_with_mqa
and kv_b_proj in one block. awq_get_modules_for_scaling dropped the whole
block when a declared variant was missing (q_proj only exists when
q_lora_rank is unset), then folded the surviving o_proj block into
input_layernorm because _select_prev_op fell back to last_module
regardless of its width. _search_best_scale re-ran self_attn on the o_proj
input:

RuntimeError: mm: mat1 and mat2 shapes cannot be multiplied (8x32 and 64x32)

With q_lora_rank=None the same fallback produced a two-layer group with a
nn.Linear prev_op, hitting assert len(layers) == 1 in apply_scale.

1c. ERNIE patch (item 3)

gptqmodel/models/definitions/ernie4_5_moe.py:180 installed
ernie4_5_moe_model_forward on type(self.model.model) unconditionally. That
forward calls self._update_causal_mask, removed in transformers 5. The
official baidu/ERNIE-4.5-* checkpoints ship no auto_map, so the native class
is loaded and the first calibration forward raised
AttributeError: 'Ernie4_5_MoeModel' object has no attribute '_update_causal_mask'.

1d. Padding rows (item 4)

GPTQProcessor.pre_process_fwd_hook (gptqmodel/looper/gptq_processor.py:594-598)
applied the keep mask only to dim() >= 3 activations, although
preserve_batch_keep_mask (:218) exists to drop padding. Routed experts
reached through the MoE bypass and HF qwen2_moe's shared expert are called on
[B*S, H] rows, and natively routed experts get [routed_rows, H], so padding
reached add_batch.

1e. defuser floor (minor)

requirements.txt:27 pins defuser>=0.0.30; the loader
(gptqmodel/models/loader.py:631) never checked it. With 0.0.28 the routed
experts of afmoe / flint / granitemoe_swa stay fused 3-D and are silently left
unquantized.

2. The new flow

flowchart TD
    A["full_layer_modules block"] --> B{"all names carry ! or ?"}
    B -- yes --> C["pending_nonquant.append"]
    C --> D{"_is_gain_norm"}
    D -- yes --> E["last_gain_norm = module"]
    B -- no --> F["subset = resolvable quantized modules"]
    F --> G{"missing module"}
    G -- "layer_modules_strict" --> H["skip_block = True"]
    G -- "not strict" --> I["skip that module only"]
    F --> J["input_width = inp.shape[-1]"]
    J --> K["_select_prev_op(input_width, allow_block_norm)"]
    K --> L["_norm_scale_consumers + _moe_block_consumers"]
    L --> M["keep only layers with in_features == input_width"]
    M --> N{"any layer left"}
    N -- no --> H
    N -- yes --> O["node: prev_op, layers, _scale_consumers"]
    O --> P["_search_best_scale(scale_consumers=...)"]
    P --> Q["apply_scale(consumer_map=...)"]
    classDef bad fill:#ffd6d6,stroke:#c00,color:#900
    class H bad
Loading

_select_prev_op now refuses a fold when the fallback module is a norm whose
width differs from the consumer input, and falls back to the last gain norm of
the layer for MoE gate/up groups whose run was already consumed by a sibling
routed-expert block (DeepSeek orders experts before shared_experts).

apply_scale accumulates the product of every scale divided into the same norm
and multiplies the consumers' input columns by that product
(scale_input_columns), because each group divides the norm again.

3. Calibration row ownership

flowchart TD
    A["forward hook: inp, keep_mask"] --> B{"Embedding and shapes match"}
    B -- yes --> B1["select rows"]
    B -- no --> C{"inp.dim() >= 3 and inp.shape[:2] == keep_mask.shape"}
    C -- yes --> C1["per-sample add_batch"]
    C -- no --> D{"inp.dim() == 2 and inp.shape[0] == keep_mask.numel()"}
    D -- yes --> D1["per-sample row filter"]
    D -- no --> E["add_batch unchanged"]
    F["MoE block pre-hook"] --> G{"keep_mask 2-D and hidden.shape[:2] match"}
    G -- yes --> G1["hidden_states = hidden_states * keep_mask"]
    G -- no --> G2["no-op"]
    G1 --> H["routed experts see zero pad rows"]
    classDef bad fill:#ffd6d6,stroke:#c00,color:#900
    class E bad
Loading

The 2-D branch keeps one add_batch per sample so a batched run accumulates the
same rows in the same order as batch_size=1. Natively routed experts cannot be
filtered (their row count is unrelated to B*S), so the MoE block pre-hook
zeroes the padded rows; zero rows contribute nothing to X^T X. The hook
returns a new tensor and does not mutate the caller's residual input.

4. Failure and ambiguity contract

Situation Before After
Fallback norm width != consumer input folded a wrong-width scale (raise or corruption) fold refused, group left unscaled
Block mixes input widths one group, shape error matching consumers fold, others quantized but unscaled (debug log)
MoE gate/up group with empty non-quantized run fell back to an unrelated nn.Linear falls back to the layer's last gain norm
layer_modules_strict=False + missing module whole block dropped only that name skipped
Multi-module group with no root change assert len(layers) == 1 block module2inspect (common parent or root)
No keep mask bound to the thread - every hook is a no-op
defuser < 0.0.30 silent "0 layer matches" loader logs an error naming the version, once
Native ERNIE class patched, AttributeError not patched; remote class still patched

5. Change inventory

Area File +/- Purpose
AWQ fold gptqmodel/models/base.py +170/-14 consumer discovery, width partition, prev_op guards, block inspect
AWQ fold gptqmodel/quantization/awq/quantize/scale.py +58 scale_input_columns, accumulated consumer scale in apply_scale
AWQ search gptqmodel/looper/awq_processor.py +71/-6 consumer_map, candidate-scale consumer weighting
GPTQ capture gptqmodel/looper/gptq_processor.py +63 2-D keep-mask rows, MoE block pad zeroing
ERNIE gptqmodel/models/definitions/ernie4_5_moe.py +19 patch only the remote class
defuser gptqmodel/models/loader.py +43 runtime version floor
Docs docs/moe-awq-calibration.md, README.md +1 page mechanism reference

6. Tests

Test Invariant
tests/test_awq_moe_router_scaling.py the fold declares the router / shared_expert_gate, and the float64 pre-fold block output, router logits and top-k are preserved
tests/test_awq_mla_scaling.py every norm-fed group only contains consumers of the fold width; DeepSeek AWQ quantization completes
tests/test_ernie4_5_moe_monkeypatch.py native class not patched and its forward runs; remote class still patched
tests/test_moe_padding_rows.py 2-D rows filtered per sample; MoE pre-hook zeroes only padded rows
tests/test_moe_batch_equivalence.py batch_size=1 vs 2 produce identical expert and dense weights
tests/test_defuser_version_check.py version floor reported once, supported versions silent

7. Validation

Hardware: RTX 4090 GPU-d458708b-c760-bbf1-08fb-8b8803a2157d (CUDA venv) and
ROCm device 2 (HIP_VISIBLE_DEVICES=2). The RTX 5090 was not used.

Fail-before (same tests on main@e088f0d23, clean worktree):

tests/test_awq_moe_router_scaling.py .......... 4 failed (consumer_map empty)
tests/test_moe_padding_rows.py ............... 3 failed (no 2-D filter, no hook)
tests/test_defuser_version_check.py .......... 6 failed (helpers absent)
tests/test_ernie4_5_moe_monkeypatch.py ....... 2 failed (native class patched)
tests/test_moe_batch_equivalence.py .......... 1 failed (0.1536 rel > 1e-6)

Pass-after, CUDA:

$ PYTHONPATH=$PWD CUDA_VISIBLE_DEVICES=GPU-d458708b-... \
  /opt/venvs/cu130t/bin/python -m pytest tests/test_awq_moe_router_scaling.py \
  tests/test_awq_mla_scaling.py tests/test_moe_padding_rows.py \
  tests/test_defuser_version_check.py tests/test_ernie4_5_moe_monkeypatch.py \
  tests/test_moe_batch_equivalence.py tests/test_awq_scale_folding.py \
  tests/test_awq_scaling_groups.py -q
66 passed

$ ... pytest tests/test_tiny_moe_quant_smoke.py tests/test_moe_bypass_batch_size.py -q
22 passed

$ ruff check gptqmodel docs/eora tests setup.py
All checks passed!

Pass-after, ROCm (HIP_VISIBLE_DEVICES=2):

$ /opt/venvs/rocm101t/bin/python -m pytest <new tests + test_awq_scale_folding.py> -q
39 passed

$ ... pytest tests/test_awq_weight_mean.py tests/test_awq_per_module_bits.py -q
191 passed, 1 skipped, 1 failed

The single failure is test_awq_weight_mean_matches_legacy_impl_0_cpu_gs32, a
fast_time <= legacy_time * 1.05 timing assertion that ran while two other
pytest processes were active; it passes on an idle machine (re-run: 1 passed).
Numerical assertions in that test pass (max_abs_diff 1.2e-7 vs 2e-7).

Measured effect:

Measurement Before After
qwen2_moe block output rel. error after fold 2.14e-2 1.95e-7
qwen2_moe router logits rel. error 2.1e-2 9.4e-8
qwen2_moe top-k expert set changed identical
DeepSeek-V2 AWQ quantization RuntimeError: mm: ... completes
qwen3_moe expert weights, bs=1 vs bs=2 (FP32 calibration) 15.4% - 18.7% bit-identical
qwen3_moe dense weights, bs=1 vs bs=2 bit-identical bit-identical

The block-output numbers come from an independent float64 forward of a deep copy
of the pre-fold layer, not from the fold code.

8. Reviewer notes

  • #4005 landed while this branch was open and rewrote the same function
    (skip_block, nosrc, _filter_awq_scaling_sources). This branch was merged
    with origin/main (8f2efe552) and keeps both behaviours: #4005's
    source validation and this PR's consumer scaling / width partition.
  • The width partition separates MLA consumers by input width. A group whose
    members share an input width but read different tensors is still only
    protected by the declared :in= tags (documented in
    docs/moe-awq-calibration.md).
  • The defuser check logs an error rather than raising: the symptom only
    affects families whose experts stay fused, and a hard failure at conversion
    would block every MoE load on an older but otherwise working release.
  • Reference page: docs/moe-awq-calibration.md,
    linked from README.md.

GPT-QModel Bot added 3 commits November 14, 2026 17:00
…E patch, drop padding rows (#4017)

AWQ MoE folds divided a norm by `s` and multiplied only the quantized
consumers, so the router and `shared_expert_gate` kept reading `x / s`
and routing changed. DeepSeek MLA blocks also folded layers with
different inputs into one norm and crashed in the scale search. ERNIE
4.5 MoE patched the native transformers forward with remote code that
calls the removed `_update_causal_mask`. Calibration padding reached
routed/shared expert Hessians whenever the calibration batch was padded.

- base.py: `_norm_scale_consumers`/`_moe_block_consumers` collect the
  non-quantized consumers of a fold source; `apply_scale` and the scale
  search now scale them by the same accumulated scale.
- base.py: only consumers whose input width matches the fold source join
  a group; a fallback norm of the wrong width refuses the fold; missing
  modules under `layer_modules_strict=False` no longer drop the block;
  a multi-module group gets a block `module2inspect`.
- gptq_processor.py: 2-D `[B*S, H]` activations filter rows with the
  keep mask per sample, and the MoE block pre-hook zeroes padded rows
  for natively routed experts.
- ernie4_5_moe.py: install the remote forward patch only when the loaded
  class owns `_update_causal_mask`.
- loader.py: report an installed `defuser` older than 0.0.30 before it
  silently leaves fused 3-D experts unquantized.

Fixes #4017
Resolve the overlap with #4005 (awq scaling groups) in
`BaseQModel.awq_get_modules_for_scaling`:

- keep #4005's `skip_block` control flow, `nosrc` source validation and
  `_filter_awq_scaling_sources` return;
- keep this branch's consumer discovery (`_norm_scale_consumers`,
  `_moe_block_consumers`), width partition of a fold group, the
  wrong-width norm guard, `allow_block_norm` fallback and block
  `module2inspect` fallback.

README keeps both the #4005 scaling-groups link and the MoE calibration
reference page link.
@Qubitium
Qubitium merged commit ff8443d into main Nov 14, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4017 branch November 14, 2026 17:05
This was referenced Nov 14, 2026
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