Repository navigation
fix(moe): scale AWQ norm consumers, split MLA fold groups, guard ERNIE patch, drop padding rows (#4017) - #4035
Merged
Merged
Conversation
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.
This was referenced Nov 14, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #4017
TL;DR
Five MoE/AWQ defects, one of them a dependency contract:
sbut only scaled the quantized consumers, so the MoErouter and
shared_expert_gatekept readingx / sand routing changed.and crashed inside the scale search.
transformersforward with remote codethat calls the removed
_update_causal_mask.whenever the calibration batch was padded.
defuser>=0.0.30was only pinned inrequirements.txt, so an older releasesilently left fused 3-D experts unquantized.
Net diff: 7 files, +422/-14 before the
#4005merge; this branch was merged withorigin/mainafter#4005landed and preserves both fixes.1. The problem
1a. Unscaled norm consumers (item 1)
awq_get_modules_for_scaling(gptqmodel/models/base.py:4773onmain@e088f0d23)builds the norm -> expert gate/up group.
apply_scale/scale_ln_fcs(
gptqmodel/quantization/awq/quantize/scale.py:139,:192) divide the norm bysand multiply each expert's gate/up bys. The router (mlp.gate) andQwen2's
shared_expert_gateread 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 bad1b. MLA groups (item 2)
The DeepSeek tree keeps
q_a_proj,q_b_proj,q_proj,kv_a_proj_with_mqaand
kv_b_projin one block.awq_get_modules_for_scalingdropped the wholeblock when a declared variant was missing (
q_projonly exists whenq_lora_rankis unset), then folded the survivingo_projblock intoinput_layernormbecause_select_prev_opfell back tolast_moduleregardless of its width.
_search_best_scalere-ranself_attnon theo_projinput:
With
q_lora_rank=Nonethe same fallback produced a two-layer group with ann.Linearprev_op, hittingassert len(layers) == 1inapply_scale.1c. ERNIE patch (item 3)
gptqmodel/models/definitions/ernie4_5_moe.py:180installedernie4_5_moe_model_forwardontype(self.model.model)unconditionally. Thatforward calls
self._update_causal_mask, removed in transformers 5. Theofficial
baidu/ERNIE-4.5-*checkpoints ship noauto_map, so the native classis 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() >= 3activations, althoughpreserve_batch_keep_mask(:218) exists to drop padding. Routed expertsreached 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 paddingreached
add_batch.1e. defuser floor (minor)
requirements.txt:27pinsdefuser>=0.0.30; the loader(
gptqmodel/models/loader.py:631) never checked it. With 0.0.28 the routedexperts 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_select_prev_opnow refuses a fold when the fallback module is a norm whosewidth 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
expertsbeforeshared_experts).apply_scaleaccumulates the product of every scale divided into the same normand 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 badThe 2-D branch keeps one
add_batchper sample so a batched run accumulates thesame rows in the same order as
batch_size=1. Natively routed experts cannot befiltered (their row count is unrelated to
B*S), so the MoE block pre-hookzeroes the padded rows; zero rows contribute nothing to
X^T X. The hookreturns a new tensor and does not mutate the caller's residual input.
4. Failure and ambiguity contract
nn.Linearlayer_modules_strict=False+ missing moduleassert len(layers) == 1module2inspect(common parent or root)defuser< 0.0.30AttributeError5. Change inventory
gptqmodel/models/base.pygptqmodel/quantization/awq/quantize/scale.pyscale_input_columns, accumulated consumer scale inapply_scalegptqmodel/looper/awq_processor.pyconsumer_map, candidate-scale consumer weightinggptqmodel/looper/gptq_processor.pygptqmodel/models/definitions/ernie4_5_moe.pygptqmodel/models/loader.pydocs/moe-awq-calibration.md,README.md6. Tests
tests/test_awq_moe_router_scaling.pyshared_expert_gate, and the float64 pre-fold block output, router logits and top-k are preservedtests/test_awq_mla_scaling.pytests/test_ernie4_5_moe_monkeypatch.pytests/test_moe_padding_rows.pytests/test_moe_batch_equivalence.pybatch_size=1vs2produce identical expert and dense weightstests/test_defuser_version_check.py7. Validation
Hardware: RTX 4090
GPU-d458708b-c760-bbf1-08fb-8b8803a2157d(CUDA venv) andROCm device 2 (
HIP_VISIBLE_DEVICES=2). The RTX 5090 was not used.Fail-before (same tests on
main@e088f0d23, clean worktree):Pass-after, CUDA:
Pass-after, ROCm (
HIP_VISIBLE_DEVICES=2):The single failure is
test_awq_weight_mean_matches_legacy_impl_0_cpu_gs32, afast_time <= legacy_time * 1.05timing assertion that ran while two otherpytest processes were active; it passes on an idle machine (re-run: 1 passed).
Numerical assertions in that test pass (
max_abs_diff1.2e-7 vs 2e-7).Measured effect:
RuntimeError: mm: ...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
#4005landed while this branch was open and rewrote the same function(
skip_block,nosrc,_filter_awq_scaling_sources). This branch was mergedwith
origin/main(8f2efe552) and keeps both behaviours:#4005'ssource validation and this PR's consumer scaling / width partition.
members share an input width but read different tensors is still only
protected by the declared
:in=tags (documented indocs/moe-awq-calibration.md).defusercheck logs an error rather than raising: the symptom onlyaffects families whose experts stay fused, and a hard failure at conversion
would block every MoE load on an older but otherwise working release.
docs/moe-awq-calibration.md,linked from
README.md.