Skip to content

fix(awq,adapter): honor norm data flow and PEFT pattern rules (#4002) - #4023

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4002
Nov 14, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4002

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4002

This PR covers items 1-4 of #4002 only. Item 5 (utils/model_dequant.py AWQ GEMV/GEMV_FAST layouts) is intentionally out of scope and is owned by a separate Fixes #4002 PR.

TL;DR

  • AWQ now selects fold sources from declared data flow: LFM3's sandwich post_operator_norm / post_ffn_norm are tagged :postnorm and never used as prev_op.
  • An unresolvable gain probe is fail-closed: scale_ln_fcs raises UnresolvableGainOffset, and apply_scale skips the group without mutating weights or captured features.
  • rank_pattern / alpha_pattern use PEFT 0.21.2's exact re.match(r"(.*\.)?(pattern)$", name) rule.
  • alpha_pattern accepts positive real values, including JSON 4.0.

1. AWQ folded LFM3 scales into sandwich post-norms (item 1)

Root cause

gptqmodel/models/base.py:4407 on origin/main (_select_prev_op) chose the last width-matching gain norm in a non-quantized run. LFM3's tree lists operator_norm, post_operator_norm before conv and ffn_norm, post_ffn_norm before feed_forward, but post_*_norm runs on the block output after the residual add (use_sandwich_norm: true). Tree position is not forward data flow.

Before (measured with the real LFM3QModel.awq_get_modules_for_scaling on a layer mirroring Lfm3DecoderLayer, seed 0):

conv prev: post_operator_norm
ffn prev:  post_ffn_norm
relative layer-output change after fold: 0.5689731240272522

Old flow

flowchart TD
    A["_select_prev_op(input_width)"] --> B["reverse pending_nonquant"]
    B --> C{"norm type, 1-D weight,<br/>weight.numel == input width?"}
    C -- "yes" --> D["prev_op = last matching norm"]
    C -- "no" --> E["prev_op = last_module"]
    D --> F["scale_ln_fcs folds into that norm"]
    style D fill:#f8d7da,stroke:#b02a37,stroke-width:2px
Loading

New flow

flowchart TD
    A["awq_get_modules_for_scaling"] --> B["post_norm_modules = set(get_post_norm_modules())"]
    B --> C["iterate full_layer_modules"]
    C --> D{"block quantized?"}
    D -- "no" --> E["append block[-1] to pending_nonquant"]
    E --> C
    D -- "yes" --> F["_select_prev_op(input_width)"]
    F --> G["reverse scan pending_nonquant"]
    G --> H{"_is_gain_norm:<br/>norm type, 1-D weight, width match,<br/>name not in post_norm_modules"}
    H -- "yes" --> I["prev_op = candidate norm"]
    H -- "no candidate" --> J{"last_module_name in post_norm_modules?"}
    J -- "yes" --> K["prev_op = None; skip block"]
    J -- "no" --> L["prev_op = last_module fallback"]
    I --> M["generate_node_for_awq_scaling"]
    L --> M
    K --> N["continue without folding"]
    style K fill:#f8d7da,stroke:#b02a37,stroke-width:2px
Loading

Fix

  • New definition-level flag POST_NORM_FLAG = ":postnorm" at gptqmodel/models/base.py:420, collected by get_post_norm_modules at :1202 (also registered in _MODULE_TREE_RUNTIME_METHODS).
  • _is_gain_norm rejects declared post-norms (gptqmodel/models/base.py:4432); _select_prev_op skips them and refuses the last_module fallback when that module is a post-norm (:4443).
  • LFM3, LFM3-VL and LFM3-Omni tag post_operator_norm and post_ffn_norm with :postnorm.

After:

conv prev: operator_norm
ffn prev:  ffn_norm
relative layer-output change after fold: 1.569886904917439e-07

The issue reports 0.688 on the real LFM3 weights; our fixture mirrors the same layer and reproduces the wrong prev_op and the 1e-7-class after state. No LFM3 checkpoint was cached locally.

2. Source-text fallback guessed a gain (item 2)

Root cause

gptqmodel/quantization/awq/quantize/scale.py:62-84,97 on origin/main fell back to grepping the forward source for 1.0+self.weight when the live probe was ambiguous, then folded as an offset gain. HF MuseSparkTextInputScaledRMSNorm scales before normalizing, so its gain is not foldable.

Before (real class from transformers 5.22.2):

offset: 1.0
relative error: 0.11317338794469833

New flow

flowchart TD
    A["apply_scale"] --> B["scale_ln_fcs"]
    B --> C["_norm_gain_offset"]
    C --> D{"resolve_gain_offset live probe"}
    D -- "0.0 or 1.0" --> E["fold gain in float32"]
    D -- "ambiguous or raises" --> F["raise UnresolvableGainOffset"]
    F --> G["apply_scale logs and skips the group"]
    G --> H["weights, features, output unchanged"]
    style F fill:#f8d7da,stroke:#b02a37,stroke-width:2px
    style G fill:#f8d7da,stroke:#b02a37,stroke-width:2px
Loading

Fix

  • Removed _source_gain_offset and the inspect import.
  • _norm_gain_offset (scale.py:65) raises UnresolvableGainOffset (scale.py:36) instead of guessing.
  • apply_scale (scale.py:150) logs and skips that group before touching weights or input_feat_dict.

After: scale_ln_fcs raises, apply_scale skips, and the norm weight, consumer weight, captured input feature, and block output are bit-identical.

3. LoRA patterns matched more broadly than PEFT (item 3)

Root cause

gptqmodel/adapter/adapter.py:26-49 on origin/main used endswith without a dot boundary and then an unanchored re.search. PEFT 0.21.2 get_pattern_key uses re.match(rf"(.*\.)?({key})$", name).

Measured before (base rank 8, base alpha 8, pattern alpha 64), against real PEFT 0.21.2:

Pattern Module Before PEFT After
1.self_attn.q_proj model.layers.1.self_attn.q_proj 8.0 8.0 8.0
1.self_attn.q_proj model.layers.10.self_attn.q_proj 1.0 1.0 1.0
1.self_attn.q_proj model.layers.11.self_attn.q_proj 8.0 1.0 1.0
model.layers.1 model.layers.1.self_attn.q_proj 8.0 1.0 1.0
model.layers.1 model.layers.10.self_attn.q_proj 8.0 1.0 1.0
model.layers.1 model.layers.11.self_attn.q_proj 8.0 1.0 1.0
up_proj model.layers.0.mlp.gate_up_proj 8.0 1.0 1.0
up_proj model.layers.0.mlp.up_proj 8.0 8.0 8.0
up_proj model.layers.0.mlp.down_proj 1.0 1.0 1.0

After the fix every per-module scale matches PEFT exactly (delta 0.0) on CUDA and ROCm.

New flow

flowchart TD
    A["dynamic_rank_override / dynamic_alpha_override"] --> B["iterate pattern keys in insertion order"]
    B --> C["_rank_pattern_matches(pattern, weight_key)"]
    C --> D["pcre.compile with optional dot-prefix group and end anchor"]
    D -- "match" --> E["first match wins"]
    D -- "no match" --> F{"legacy export:<br/>pattern or key has uppercase?"}
    F -- "yes" --> G["retry with pcre.IGNORECASE"]
    F -- "no" --> H["next pattern"]
    G -- "match" --> E
    G -- "no match" --> H
    H --> B
    E --> I["lora_scale = alpha / rank<br/>or alpha / sqrt(rank) for rsLoRA"]
Loading

Fix

_rank_pattern_matches (gptqmodel/adapter/adapter.py:27) now uses PEFT's exact rule. The case-insensitive retry keeps the pattern unchanged and only adds pcre.IGNORECASE, preserving \S, \D, \W semantics for legacy exports.

4. Float alpha crashed the loader (item 4)

Root cause

gptqmodel/adapter/adapter.py:392 on origin/main asserted isinstance(override, int). JSON has no integer type, so "alpha_pattern": {"...": 4.0} raised AssertionError in post_init (and was silently skipped under python -O).

Fix

dynamic_alpha_override (adapter.py:380) validates numbers.Real > 0, converts with float(), and raises ValueError for invalid values instead of relying on an assert. A 4.0 alpha now loads with scale 4.0 / 8 = 0.5, matching PEFT exactly.

Validation

Hardware:

  • CUDA: RTX 4090 GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7e (nvidia-smi index 1). nvidia-smi --query-compute-apps showed the 4090 free before runs; the RTX 5090 was never used.
  • ROCm: R9700 with HIP_VISIBLE_DEVICES=1 only.

Commands and results (run after merging current origin/main):

# CUDA
CUDA_VISIBLE_DEVICES=GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7e PYTHONPATH=$PWD \
  /opt/venvs/cu130t/bin/python -m pytest -q \
  tests/test_awq_scale_folding.py tests/test_adapter_config.py tests/test_adapter_scaling.py \
  tests/test_eora_merge.py tests/test_eora.py tests/test_eora_weight_lifecycle.py \
  tests/test_adapter_cache_lifecycle.py tests/test_adapter_case_sensitive.py tests/test_lfm3_support.py
# 67 passed, 7 skipped

# ROCm
HIP_VISIBLE_DEVICES=1 PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest -q \
  tests/test_awq_scale_folding.py tests/test_adapter_config.py tests/test_adapter_scaling.py \
  tests/test_eora_merge.py tests/test_eora.py tests/test_eora_weight_lifecycle.py \
  tests/test_adapter_cache_lifecycle.py tests/test_adapter_case_sensitive.py tests/test_lfm3_support.py
# 67 passed, 7 skipped

# Module plans after the tree-flag addition
PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest -q \
  tests/module_tree/test_registered_module_plans.py tests/module_tree/test_module_tree_variants.py
# 429 passed

# Norm config/guard regression (unchanged behavior)
CUDA_VISIBLE_DEVICES=GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7e PYTHONPATH=$PWD \
  /opt/venvs/cu130t/bin/python -m pytest -q tests/test_norm_config.py tests/test_norm_guards.py
# 29 passed

# Lint gate
ruff check gptqmodel docs/eora tests setup.py
# All checks passed!

Fail-before evidence (same tests run against a clean origin/main worktree):

  • test_lfm3_sandwich_post_norms_are_not_fold_sources sees post_operator_norm / post_ffn_norm and fails.
  • test_probe_failure_skips_scale_instead_of_guessing_from_source folds with error 0.113 and mutates weights on main.
  • test_alpha_pattern_matches_peft_dot_boundary fails with assert 7.0 <= 1e-07 for all three patterns.
  • test_float_alpha_pattern_loads_with_peft_scale fails at assert isinstance(override, int).
  • test_rank_pattern_requires_a_dot_boundary fails on the over-match.

Docs

  • New: docs/awq-norm-selection.md (linked from README.md).
  • New: docs/adapter-pattern-matching.md (linked from README.md).
  • Updated: docs/awq-scale-folding.md to match the new selection and fail-closed probe flow.

Reviewer notes / limitations

  • The post-norm fix is definition-level metadata, not a runtime tensor-identity check. A future model with a sandwich post-norm must tag it :postnorm; the LFM3 family is tagged here.
  • The LFM3 regression uses a synthetic layer that mirrors Lfm3DecoderLayer (use_sandwich_norm=True) because no LFM3 checkpoint is cached. The wrong prev_op and the 1e-7-class after state are reproduced; the 0.688 real-model number is quoted from the issue.
  • The up_proj row in the issue mentions down_proj; in this fixture the over-match is gate_up_proj (down_proj does not end in up_proj). The committed tests pin the PEFT-parity result for gate_up_proj, up_proj, and down_proj.
  • No GPTQMODEL_* switches, no dense inference weight caches, no device-family changes. CUDA and ROCm were both exercised.

AWQ:
- Tag LFM3 sandwich post-norms with a definition-level :postnorm flag and
  exclude them from prev_op selection, so scales fold into operator_norm /
  ffn_norm instead of post_operator_norm / post_ffn_norm.
- Drop the forward-source gain fallback. When the live probe cannot resolve
  weight vs 1+weight, scale_ln_fcs raises UnresolvableGainOffset and
  apply_scale skips the group without mutating weights or features.

Adapter:
- Match rank_pattern / alpha_pattern with PEFT's exact
  re.match(r'(.*\.)?(pattern)$', name) rule instead of endswith plus an
  unanchored search.
- Accept positive float alpha_pattern values from JSON exports.

Tests: LFM3 folding, probe-failure skip, PEFT dot-boundary parity, and float
alpha loading. Docs: docs/awq-norm-selection.md and
docs/adapter-pattern-matching.md, linked from README.
@Qubitium
Qubitium merged commit be85199 into main Nov 14, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4002 branch November 14, 2026 15:49
Qubitium added a commit that referenced this pull request Nov 14, 2026
…ule bits (#4002) (#4031)

* fix(awq): dispatch dequantization on the saved AWQ layout and per-module bits (#4002)

`dequantize_model` decoded every AWQ checkpoint with the GEMM reader. That is
exact for GEMM 4-bit and AwqTorch 8-bit, but GPTQModel can also write GEMV
(`[out, in/8]` natural order), GEMV_FAST/LLM_AWQ (`pack_intweight` INT16
interleave with fp16 scaled zeros) and per-module `dynamic` widths, so those
checkpoints either raised `IndexError`, `NotImplementedError: "rshift_cpu" not
implemented for 'Half'` or a size-mismatch `RuntimeError`.

Read `format`/`version` from the saved config, resolve `bits`/`group_size`
through `dynamic`, and decode each layout with its own inverse transform. The
per-module width is no longer taken from the checkpoint-wide `bits`.

Fixes item 5 of #4002; items 1-4 landed in #4023.

* docs(awq): point the dequantization scatter reference at the real line (#4002)

---------

Co-authored-by: GPTQModel Bot <[email protected]>
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