Repository navigation
fix(awq): fold scales into the correct norm and resolve offset gains (#3973) - #3989
Merged
Merged
Conversation
…3973) AWQ scale folding used a fixed GemmaRMSNorm/Gemma2RMSNorm class list to detect (1 + weight) gains, so Gemma3, Qwen3.5 and Qwen3-Next norms silently stored 1 + w/s instead of (1 + w)/s. Resolve the gain parameterization from the module's live forward (the existing gain probe) and fold in float32. awq_get_modules_for_scaling also kept the first block of a run of non-quantized modules as prev_op. For Gemma2/3 that is post_attention_layernorm, not the pre_feedforward_layernorm that feeds the MLP. Track the whole run and select the last gain norm whose width matches the consumer's input, keeping the historical fallback when none matches so MoE routers and capture-only roots are not selected.
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 #3973
TL;DR
AWQ scale folding decided two things from the wrong signal: the
(1 + w)gain offset from a two-entry class list, andprev_opfrom the first block of a run of non-quantized modules. Both now come from the thing that actually determines the result — the live module's forward and the norm whose width matches the consumer's input. Net diff: 6 files, +475/−20, with a new reference pagedocs/awq-scale-folding.md.1. The problem
1a. Offset gain detected by class list
scale_ln_fcschose the(1 + w)fold fromisinstance(ln, GemmaRMSNorm) or isinstance(ln, Gemma2RMSNorm)atgptqmodel/quantization/awq/quantize/scale.py:145(origin/main).Gemma3RMSNorm,Qwen3_5RMSNorm,Qwen3_5MoeRMSNormandQwen3NextRMSNormcomputex * (1 + weight)but subclass neither, so they tookweight /= sand stored1 + w/sinstead of(1 + w)/s.flowchart TD A["scale_ln_fcs(ln, fcs, scales)"] --> B{"isinstance(ln, GemmaRMSNorm)<br/>or isinstance(ln, Gemma2RMSNorm)"} B -- "yes" --> C["w += 1; w /= s; w -= 1"] B -- "no" --> D["w /= s"] D -. "Gemma3 / Qwen3.5 / Qwen3-Next:<br/>gain becomes 1 + w/s" .-> E["silent numerical corruption"] style D fill:#f8d7da,stroke:#b02a37,stroke-width:2px style E fill:#f8d7da,stroke:#b02a37,stroke-width:2px1b.
prev_opis the first module of a non-quantized runawq_get_modules_for_scalingskipped every non-quantized block after the first atgptqmodel/models/base.py:4413-4419(origin/main), then used it asprev_opatgptqmodel/models/base.py:4490. Gemma 2/3 order ispost_attention_layernorm:!→pre_feedforward_layernorm:!→mlp.gate/up, so the MLP scale was folded into the post-attention norm, which feeds the residual and is re-normalized — not equivalent to scaling the MLP input.scale.py:145scale.py:87scale.py:146-148add_/div_/sub_,scale.py:205prev_opselectionbase.py:4413-4419+base.py:4490base.py:4407/base.py:4555base.py:44422. The new flow
flowchart TD A["awq_get_modules_for_scaling<br/>iterate full_layer_modules"] --> B{"block quantized?"} B -- "no" --> C["resolve block[-1]<br/>append to pending_nonquant"] C --> D{"first of run?"} D -- "yes" --> E["_try_update_last_module<br/>fallback last_module"] D -- "no" --> F["keep fallback"] B -- "yes" --> G["resolve feature_name and inp"] G --> H["_select_prev_op(inp.shape[-1])"] H --> I{"reverse pending_nonquant:<br/>gain norm with<br/>weight.numel == input width?"} I -- "yes" --> J["prev_op = that norm"] I -- "no" --> K["prev_op = last_module"] J --> L["generate_node_for_awq_scaling"] K --> L L --> M["apply_scale -> scale_ln_fcs"] M --> N{"_norm_gain_offset(ln)"} N -- "1.0" --> O["float32<br/>w.add_(1).div_(s).sub_(1)"] N -- "0.0" --> P["w.div_(s)"] N -. "probe and source both inconclusive" .-> Q["warn + assume plain gain"] style Q fill:#f8d7da,stroke:#b02a37,stroke-width:2px_norm_gain_offsetcallsresolve_gain_offset(gptqmodel/quantization/norm_tuning.py:159), which reuses the existing norm-tuning gain probe: it evaluatesweightand1 + weighthypotheses on a private copy at two small gains and picks the one that matches. If the module's forward cannot be probed (extra inputs, non-tensor output),_source_gain_offset(scale.py:62) inspects the forward source for an additive offset. If that is inconclusive too, the fold logs a warning and falls back to the pre-fix plain gain — visible, not silent.3. Failure and ambiguity contract
prev_op = post_attention_layernormprev_op = pre_feedforward_layernormprev_oplast_modulefallback retained4. Change inventory
gptqmodel/quantization/awq/quantize/scale.pygptqmodel/quantization/norm_tuning.pyresolve_gain_offsetwrapper over_probe_gain_offsetgptqmodel/models/base.pyprev_optests/test_awq_scale_folding.pydocs/awq-scale-folding.mdREADME.md5. Before / after (measured)
Issue snippet:
apply_scale(norm, [linear])on a random gain, relative L2 oflinear(norm(x))before vs after folding. Same script, same seed,origin/mainworktree vs this branch.LlamaRMSNormGemma2RMSNormGemma3RMSNormQwen3NextRMSNormQwen3_5MoeRMSNorm(synthetic subclass-free)On-device (Gemma3RMSNorm, same script):
GPU-1892aea4-…(RTX 4090)HIP_VISIBLE_DEVICES=0(R9700)Gemma 2 MLP (real
Gemma2ForCausalLMlayer,Gemma2QModel.awq_get_modules_for_scaling):The issue reported 0.38 for this case; the value depends on the random layer weights.
6. Tests
tests/test_awq_scale_folding.py— the oracle is plain PyTorch (nn.Linear/nn.RMSNormforward before the fold, plus the closed-form(1 + w)/s - 1andfc_w * s), never the code under test:test_scale_ln_fcs_resolves_gain_offset_from_semantics[*](8 norms)norm -> linearoutput preserved to 1e-6 for plain and offset gainstest_scale_ln_fcs_offset_gain_folds_in_float32[fp16/bf16](1 + w)/s - 1rounded oncetest_gemma2_mlp_prev_op_is_pre_feedforward_layernormprev_optest_gemma2_mlp_scale_fold_is_output_neutralprev_oppreserves MLP outputtest_moe_router_is_not_selected_as_prev_opprev_opFail before / pass after
Failing on origin/main: the four offset-gain norm cases (Gemma3, Qwen3-Next, synthetic Qwen3.5-MoE, Qwen3.5), both fp16/bf16 float32-fold cases, and both Gemma2
prev_op/output-neutrality cases.Related existing tests
ROCm venv (
HIP_VISIBLE_DEVICES=0):tests/test_awq_scale_folding.py=> 13 passed.Hardware: NVIDIA RTX 4090 (
GPU-1892aea4-cc09-827c-b9a5-93d4eef7f5ae, CUDA 13.0 torch 2.16.0.dev) and AMD Radeon AI PRO R9700 (HIP_VISIBLE_DEVICES=0, ROCm 10.1 torch 2.16.0.dev). The RTX 5090 was not used.7. Reviewer notes
deepcopy, negligible next to the AWQ scale search, and it is the same mechanism norm tuning already relies on.prev_opselection requires a 1-D gain-norm weight whose length equals the consumer's input width. That rejects MoE routers (mlp.gate:!, 2-D output) and capture-only roots while keeping the historical fallback for anything unmatched.docs/awq-scale-folding.mdcarries the same diagrams and is linked fromREADME.md.