Skip to content

fix(awq): fold scales into the correct norm and resolve offset gains (#3973) - #3989

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

Qubitium merged 3 commits into
mainfrom
fix/issue-3973

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

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, and prev_op from 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 page docs/awq-scale-folding.md.

1. The problem

1a. Offset gain detected by class list

scale_ln_fcs chose the (1 + w) fold from isinstance(ln, GemmaRMSNorm) or isinstance(ln, Gemma2RMSNorm) at gptqmodel/quantization/awq/quantize/scale.py:145 (origin/main). Gemma3RMSNorm, Qwen3_5RMSNorm, Qwen3_5MoeRMSNorm and Qwen3NextRMSNorm compute x * (1 + weight) but subclass neither, so they took weight /= s and stored 1 + w/s instead 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:2px
Loading

1b. prev_op is the first module of a non-quantized run

awq_get_modules_for_scaling skipped every non-quantized block after the first at gptqmodel/models/base.py:4413-4419 (origin/main), then used it as prev_op at gptqmodel/models/base.py:4490. Gemma 2/3 order is post_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.

Mechanism origin/main This PR
Offset-gain detection class list, scale.py:145 live gain probe, scale.py:87
Offset fold arithmetic in-place in stored dtype, scale.py:146-148 float32 add_/div_/sub_, scale.py:205
prev_op selection first block of run, base.py:4413-4419 + base.py:4490 last matching gain norm, base.py:4407 / base.py:4555
Empty block inside a run implicitly skipped by the first-of-run rule skipped explicitly, base.py:4442

2. 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
Loading

_norm_gain_offset calls resolve_gain_offset (gptqmodel/quantization/norm_tuning.py:159), which reuses the existing norm-tuning gain probe: it evaluates weight and 1 + weight hypotheses 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

Situation Before After
Unknown offset-gain norm class silently folded as plain gain measured from forward; correct fold
Norm forward not probe-able silently folded as plain gain source inspection; if inconclusive, warning + plain gain
Run of non-quantized blocks (Gemma 2/3) prev_op = post_attention_layernorm prev_op = pre_feedforward_layernorm
Run contains a MoE router / capture-only root router could be prev_op router rejected: not a 1-D gain norm of the consumer width
No candidate norm matches the input width n/a historical last_module fallback retained

4. Change inventory

Area File ± Purpose
AWQ fold gptqmodel/quantization/awq/quantize/scale.py +72/−6 semantics-based gain offset, float32 fold, source fallback
Norm probe gptqmodel/quantization/norm_tuning.py +13 public resolve_gain_offset wrapper over _probe_gain_offset
Module resolution gptqmodel/models/base.py +64/−14 collect non-quantized run, select matching gain norm as prev_op
Tests tests/test_awq_scale_folding.py +261 13 regression tests, independent oracles
Docs docs/awq-scale-folding.md +84 flow, before/after, contracts
Docs index README.md +1 link to the new page

5. Before / after (measured)

Issue snippet: apply_scale(norm, [linear]) on a random gain, relative L2 of linear(norm(x)) before vs after folding. Same script, same seed, origin/main worktree vs this branch.

Norm origin/main This PR
LlamaRMSNorm 9.71e-8 9.71e-8
Gemma2RMSNorm 1.01e-7 1.01e-7
Gemma3RMSNorm 0.2661 1.16e-7
Qwen3NextRMSNorm 0.2634 1.01e-7
Qwen3_5MoeRMSNorm (synthetic subclass-free) 0.2688 1.22e-7

On-device (Gemma3RMSNorm, same script):

Device origin/main This PR
CUDA GPU-1892aea4-… (RTX 4090) 0.2903 1.02e-7
ROCm HIP_VISIBLE_DEVICES=0 (R9700) 0.2903 9.29e-8

Gemma 2 MLP (real Gemma2ForCausalLM layer, Gemma2QModel.awq_get_modules_for_scaling):

origin/main: prev_op: ['post_attention_layernorm'] -> layer-output rel change 0.5608
this PR:     prev_op: ['pre_feedforward_layernorm'] -> layer-output rel change < 1e-5

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.RMSNorm forward before the fold, plus the closed-form (1 + w)/s - 1 and fc_w * s), never the code under test:

Test Pins
test_scale_ln_fcs_resolves_gain_offset_from_semantics[*] (8 norms) pre-fold norm -> linear output preserved to 1e-6 for plain and offset gains
test_scale_ln_fcs_offset_gain_folds_in_float32[fp16/bf16] stored gain equals float32 (1 + w)/s - 1 rounded once
test_gemma2_mlp_prev_op_is_pre_feedforward_layernorm real Gemma2 layer resolves the MLP prev_op
test_gemma2_mlp_scale_fold_is_output_neutral folding through the selected prev_op preserves MLP output
test_moe_router_is_not_selected_as_prev_op a router in the same non-quantized run is never prev_op

Fail before / pass after

# origin/main worktree (00163850), same test file
PYTHONPATH=/tmp/wt3973 /opt/venvs/cu130t/bin/python -m pytest tests/test_awq_scale_folding.py -q
=> 8 failed, 5 passed

# fix/issue-3973
PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest tests/test_awq_scale_folding.py -q
=> 13 passed

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

PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest tests/test_norm_config.py tests/module_tree/test_gemma_olmo_family_plan_coverage.py -q
=> 35 passed
# tests/test_awq_weight_mean.py needs the third-party `parameterized` package,
# which is not installed in either venv (pre-existing collection error).
# The two scaling-node tests were run with a local stub module:
PYTHONPATH=/tmp/stub:$PWD /opt/venvs/cu130t/bin/python -m pytest tests/test_awq_weight_mean.py -q -k "qwen3_moe_awq_scaling_node or public_moe_model_policies"
=> 2 passed

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

  • The probe runs once per norm per scaling node. It is two tiny forwards on a private deepcopy, negligible next to the AWQ scale search, and it is the same mechanism norm tuning already relies on.
  • Semantics, not names: a norm class can be configured either way, and the probe resolves per instance. This also covers VaultGemma/T5Gemma/Gemma4-style definitions without a registry to maintain.
  • prev_op selection 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.md carries the same diagrams and is linked from README.md.
  • Out of scope here: issue [BUG] AWQ packed-format readers: 8-bit Marlin/Machete wrong un-interleave; dequantize_model scrambles AWQ channels #3974 (AWQ packed readers) is handled separately.

…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] AWQ scale folding corrupts Gemma2/Gemma3/Qwen3.5/Qwen3-Next: wrong (1+w) RMSNorm detection and wrong prev_op norm

1 participant