Skip to content

fix(models): correct remote-code AWQ trees, coverage, position replay, and looped calibration (#4093) - #4109

Merged
Qubitium merged 4 commits into
mainfrom
fix/issue-4093-awqtrees
Nov 15, 2026
Merged

Qubitium merged 4 commits into
mainfrom
fix/issue-4093-awqtrees

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #4093 (items 1-6)

TL;DR

Six model-definition and calibration-replay defects in remote-code families:
two trees folded AWQ scales across the residual (wikitext-2 PPL 27997 / 1745
where RTN is 26.6 / 21.2), TeleChat2 never quantized query/key_value and
crashed in AWQ replay, AWQ replayed one sample's position_ids with another
sample's activations, PanGu's top-query layer was calibrated on the wrong input,
and looped decoders (Ouro, Nanbeige 4.2) were calibrated on loop 0 only.

Net: 26 files, +1915/-204. Two new shared mechanisms: a definition hook for
AWQ replay inputs (BaseQModel.awq_module_replay_inputs) and a reusable
LoopedLayerCaptureMixin (generalized from the HRM-Text fix in #4055).

1. The problem

flowchart TD
    A["definition.module_tree"] --> B["ModulePlan.from_tree"]
    B --> C["awq_get_modules_for_scaling"]
    C --> D{"prev_op is the real<br/>consumer input?"}
    D -- "tree is wrong" --> E["fold across residual<br/>PPL 27997 / 1745"]
    D -- "leaf undeclared" --> F["query / key_value stay fp16<br/>coverage says all matched"]
    D -- "ok" --> G["apply_scale"]
    G --> H["AWQProcessor._prepare_module_forward"]
    H --> I{"captured position_ids<br/>length == seq_len?"}
    I -- "no" --> J["replay 430 ids with 522 activations<br/>RuntimeError"]
    I -- "yes" --> K["replay block"]
    K --> L["GPTQ / AWQ layer replay"]
    L --> M{"last block and<br/>custom_query model?"}
    M -- "no hook" --> N["PanGu last layer sees layer-0 kwargs<br/>GPTQ 0.131 worse than RTN 0.094"]
    M -- "hook" --> O["correct input"]
    L --> P{"looped decoder?"}
    P -- "single-chain capture" --> Q["Hessian from loop 0 only<br/>Ouro add_batch 8, not 32"]
    P -- "full-forward capture" --> R["every invocation"]
    style E fill:#f8d7da,stroke:#842029,stroke-width:2px
    style F fill:#f8d7da,stroke:#842029,stroke-width:2px
    style J fill:#f8d7da,stroke:#842029,stroke-width:2px
    style N fill:#f8d7da,stroke:#842029,stroke-width:2px
    style Q fill:#f8d7da,stroke:#842029,stroke-width:2px
Loading
# Old mechanism file:line (before)
1 InstellaQModel(LlamaQModel) inherited the Llama norm names, so q/k/v had no source and mlp.gate/up folded into self_attn.o_proj gptqmodel/models/definitions/instella.py:9
2 each attention projection was its own dict node, producing chained single-module groups gptqmodel/models/definitions/k2_horizon.py:140-157
3 only dense declared; coverage counted declared specs only gptqmodel/models/definitions/telechat2.py:25
4 position_ids added only when the key was absent; mismatched position_embeddings kept gptqmodel/looper/awq_processor.py:2939
5 no replay hook for the top-query block gptqmodel/models/definitions/pangu_alpha.py (no override)
6 HRM-only capture; Ouro/Nanbeige used the single-chain capture gptqmodel/models/definitions/hrm_text.py (before #4055 extraction)

2. The new flow

flowchart TD
    A["ModuleLooper.create_named_modules"] --> B["ModulePlan.find(name)"]
    B --> C{"quantizable leaf with no spec?"}
    C -- "yes" --> D["LayerModuleCoverageTracker.record_undeclared"]
    C -- "no" --> E["record_hit / record_miss"]
    D --> F["report(): NOT declared warning"]
    A --> G["AWQProcessor._prepare_module_forward"]
    G --> H["BaseQModel.awq_module_replay_inputs<br/>(TeleChat2: residual + causal mask)"]
    H --> I{"position_ids / position_embeddings<br/>match seq_len?"}
    I -- "no" --> J["rebuild position_ids with arange;<br/>use root or module-local rotary;<br/>drop foreign position_embeddings"]
    I -- "yes" --> K["keep captured kwargs"]
    J --> L["AWQ scale search"]
    K --> L
    M["ModuleLooper.cache_inputs"] --> N["LoopedLayerCaptureMixin.build_quantization_input_cache"]
    N --> O["cache.captured_batch_count"]
    O --> P["processor.num_batches = captured_batch_count"]
    P --> Q["replay every loop invocation"]
    R["BaseQModel.prepare_layer_replay_kwargs"] --> S["PanguAlphaQModel: ln_f + wqe(position_ids)<br/>for blocks[-1] only"]
    style D fill:#d1e7dd,stroke:#0f5132,stroke-width:2px
    style J fill:#d1e7dd,stroke:#0f5132,stroke-width:2px
    style Q fill:#d1e7dd,stroke:#0f5132,stroke-width:2px

Loading

3. Per-subsystem detail

3.1 Instella owns its norm names (item 1)

gptqmodel/models/definitions/instella.py:19-30 now declares
pre_attention_layernorm / pre_feedforward_layernorm (the real names at
modeling_instella.py:663-664) instead of inheriting the Llama tree. instella
is added to FAMILY_MODEL_TYPES, so the fold-preservation invariant covers it.

Real checkpoint (/monster/data/model/Instella-3B-Instruct, wikitext-2 40x512,
64 variable-length C4 docs, AWQ 4-bit g128 sym=False, fp16, RTX 4090):

Configuration PPL
RTN 26.64
AWQ, old Llama-inherited tree 27997.65
AWQ, fixed Instella tree 25.31

3.2 K2-Horizon attention is one flat group (item 2)

gptqmodel/models/definitions/k2_horizon.py:151-157 replaces the per-projection
dict entries with one flat "" tuple:
q_proj:0, k_proj:0, v_proj:0, gate_proj:0:nosrc, o_proj:1. The
attention gate is not positively homogeneous, so it is a declared non-source.

Configuration PPL
RTN 21.23
AWQ, old per-projection nodes 1744.94
AWQ, flat attention group 19.78

3.3 TeleChat2 quantizes its input projections and can replay its attention (item 3)

gptqmodel/models/definitions/telechat2.py:31 declares
("query:0", "key_value:0", "dense:1"). AWQ replay needed
TelechatAttention.forward(hidden_states, residual, attention_mask, ...); the
new awq_module_replay_inputs hook promotes the 2-D capture to 3-D, passes the
block input as residual, and builds a causal bool mask.

The coverage report was also blind to leaves with no spec at all:
LayerModuleCoverageTracker.record_undeclared (module_coverage.py:65) is fed
by ModuleLooper.create_named_modules (module_looper.py:2161-2175).

Check Before After
AWQ on tiny TeleChat2 TypeError: TelechatAttention.forward() missing 1 required positional argument: 'residual' quantize OK
self_attention.query / key_value nn.Linear (fp16) quantized modules
coverage "all 4 specs matched" while two Linears were undeclared "all 6 layer-module spec(s) matched", undeclared_snapshot() == {}

3.4 AWQ replay rebuilds stale position scaffolding (item 4)

AWQProcessor._prepare_module_forward (awq_processor.py:2847) now:

  • rebuilds position_ids whenever shape[-1] != seq_len, not only when absent;
  • falls back to module.rotary_emb / module.rotary when the model root has no
    rotary (Nanbeige/DeciLM), and keeps it instead of re-resolving the root;
  • drops a position_embeddings whose sequence length does not match when no
    rotary can rebuild it (_position_embeddings_match, awq_processor.py:3003);
  • exaone.py:19 declares rotary_embedding = "transformer.rotary".

Variable-length AWQ (48- and 20-token calibration, sorted descending):

Family Before After
EXAONE-3.0-7.8B RuntimeError: size of tensor a (48) must match tensor b (20) quantize OK
DeciLM-7B same 48 vs 20 quantize OK
Nanbeige 4.2 same 48 vs 20 quantize OK

3.5 PanGu's top-query layer replays the input HF gives it (item 5)

PanguAlphaQModel.prepare_layer_replay_kwargs (pangu_alpha.py:32) applies
transformer.ln_f to the last block's input and sets
custom_query = transformer.wqe(position_ids) (arange when absent). Other
layers are untouched.

Tiny PanGu, last-layer q_proj relative error on query embeddings:

Configuration Error
Before: GPTQ 0.1311
Before: RTN 0.0941
After: GPTQ 0.0544
After: RTN 0.0959

3.6 Looped decoders calibrate on every loop (item 6)

gptqmodel/models/looped_capture.py adds LoopedLayerCaptureMixin (extracted
from the HRM-Text implementation): one full forward per calibration sample with
a pre-hook on every physical layer, then pre_quantize serves the current
layer's own invocations. ModuleLooper.cache_inputs publishes
cache.captured_batch_count as processor.num_batches (module_looper.py:1767)
so replay is not truncated to loop 0.

Family Invocations / forward Per-loop cosine vs loop 0 GPTQ add_batch per module
Ouro (total_ut_steps=4) 4 -0.008, -0.016, -0.019 32 after (8 before)
Nanbeige 4.2 (num_loops=2) 2 0.748 16 after (8 before)

4. Failure and ambiguity contract

Situation Before After
A quantizable Linear has no tree spec silently stays in the source dtype; coverage says everything matched record_undeclared + a "NOT declared" warning
Captured position_ids length != replay length replayed as-is, crash in apply_rotary_pos_emb rebuilt with arange(seq_len)
Captured position_embeddings length != replay length replayed as-is, broadcast error rebuilt from a root/module-local rotary, else dropped
Attention module needs args the capture never records TypeError definition hook supplies them
Looped decoder capture one chain pass, loop 0 only every invocation, num_batches sized from the capture
Top-query layer in a custom_query model replayed with layer-0 kwargs ln_f + wqe(position_ids) for the last block

5. Change inventory

Area Files Purpose
Model trees definitions/instella.py, k2_horizon.py, telechat2.py, exaone.py real norm names, flat attention group, declared q/kv, declared rotary
Coverage looper/module_coverage.py, looper/module_looper.py undeclared quantizable leaves
AWQ replay looper/awq_processor.py, models/base.py stale position kwargs + definition replay hook
Layer replay definitions/pangu_alpha.py top-query ln_f + custom_query
Looped capture models/looped_capture.py (new), definitions/{hrm_text,ouro,nanbeige}.py, looper/module_looper.py every-invocation Hessian capture
Tests tests/test_{telechat2_coverage,awq_position_kwargs,pangu_alpha_replay,looped_decoder_capture,instella_support,k2_horizon_support,layer_module_coverage}.py, tests/test_awq_scaling_groups.py, tests/tiny_remote_models.py, tests/module_tree/fixtures/registered_module_plans.json regression coverage
Docs docs/awq-scaling-groups.md, README.md mechanisms + diagrams

6. Tests / guarantees

Test Invariant
test_awq_scaling_groups.py (instella, k2_horizon) folding a random scale preserves decoder-layer logits to 1e-5 relative
test_instella_support.py tree declares the real norm names; the plan resolves on the checkpoint's own layer
test_k2_horizon_support.py::test_k2_horizon_attention_projections_share_one_awq_group q/k/v/gate are one group, o_proj separate
test_telechat2_coverage.py q/kv/dense quantized; no undeclared leaf; replay supplies residual + mask
test_awq_position_kwargs.py stale ids rebuilt, mismatched embeddings dropped, module-local rotary used; EXAONE/DeciLM/Nanbeige AWQ runs on variable lengths
test_pangu_alpha_replay.py last layer gets ln_f + custom_query; GPTQ beats RTN
test_looped_decoder_capture.py Ouro 4 / Nanbeige 2 invocations, per-loop cosine < 0.99, captured_batch_count set
test_layer_module_coverage.py undeclared leaves are recorded and warned about

7. Validation

Environment: /opt/venvs/cu130t/bin/python (Python 3.14t, torch
2.16.0.dev+cu130, transformers 5.22.2), PYTHONPATH=$PWD.

Hardware: RTX 4090 GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7e for the PPL runs;
CPU (CUDA_VISIBLE_DEVICES="") for the tiny-model tests; ROCm
(/opt/venvs/rocm101t/bin/python, HIP_VISIBLE_DEVICES=1) for the unit tests.

After (this branch):

pytest tests/test_telechat2_coverage.py tests/test_awq_position_kwargs.py \
       tests/test_pangu_alpha_replay.py tests/test_looped_decoder_capture.py \
       tests/test_instella_support.py tests/test_k2_horizon_support.py \
       tests/test_layer_module_coverage.py tests/test_hrm_text_support.py \
       tests/module_tree/test_registered_module_plans.py \
       tests/test_awq_empty_groups.py tests/test_awq_rotary_device.py \
       "tests/test_awq_scaling_groups.py::test_scaling_groups_preserve_decoder_layer_output[instella]" \
       "tests/test_awq_scaling_groups.py::test_scaling_groups_preserve_decoder_layer_output[k2_horizon]"
-> 481 passed

pytest tests/test_awq_scaling_groups.py
-> 93 passed, 2 skipped

pytest "tests/test_awq_scaling_groups.py::test_scaling_groups_preserve_decoder_layer_output[instella]" \
       "tests/test_awq_scaling_groups.py::test_scaling_groups_preserve_decoder_layer_output[k2_horizon]"
-> 2 passed

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

Pre-existing failures observed on origin/main (not caused by this branch; verified
on a clean origin/main worktree and on 718256fd7):

  • tests/test_hf_config_compat.py::test_normalize_hf_config_compat_restores_legacy_cache_length_helpers
    (DummyCache has no get_max_length in this environment)
  • tests/test_hf_config_compat.py::test_resolve_trust_remote_code_overrides_when_native_support_exists
  • tests/test_awq_gptq_lifecycle.py::test_awq_capture_is_pre_forward_and_gptq_does_not_receive_the_hook
  • tests/test_awq_per_module_bits.py::test_clip_search_uses_module_width[*] (needs the absent parameterized)

Before (/tmp/defsA-before, 718256fd7), same tests:

12 failed, 1 passed, 1 error   (new unit tests; the looped module does not exist)
3 failed                       (item 4 variable-length AWQ: 48 vs 20 on all three)
1 failed                       (TeleChat2 AWQ: TypeError missing 'residual')
1 failed                       (PanGu: GPTQ 0.1311 vs RTN 0.0941)
ouro add_batch 8 / nanbeige add_batch 8   (loop 0 only)

8. Reviewer notes

…, and looped calibration (#4093)

Items 1-6 of #4093.

- instella: own module_tree with pre_attention_layernorm /
  pre_feedforward_layernorm instead of the inherited Llama norm names.
  AWQ folded mlp.gate/up into self_attn.o_proj across the residual
  (wikitext-2 PPL 27997 -> 25.31; RTN 26.64).
- k2_horizon: one flat attention group (q/k/v/gate + o_proj consumer)
  instead of per-projection nodes (PPL 1744.94 -> 19.78; RTN 21.23).
- telechat2: declare query/key_value/dense, add awq_module_replay_inputs
  to supply residual + causal mask, and report quantizable leaves that no
  tree spec declares (LayerModuleCoverageTracker.record_undeclared).
- awq_processor: rebuild stale position_ids whenever their length differs
  from the replayed sample, use a module-local rotary when the root has
  none, and drop mismatched position_embeddings. exaone declares
  rotary_embedding = "transformer.rotary". Fixes EXAONE/DeciLM/Nanbeige
  48-vs-20 AWQ crashes.
- pangu_alpha: prepare_layer_replay_kwargs applies ln_f and sets
  custom_query for the last (top-query) block; GPTQ last-layer q_proj
  error 0.1311 (worse than RTN 0.0941) -> 0.0544 (better than 0.0959).
- looped decoders: LoopedLayerCaptureMixin (extracted from HRM-Text)
  captures every invocation of Ouro/Nanbeige/HrmText layers and publishes
  captured_batch_count so replay is not truncated to loop 0
  (Ouro add_batch 8 -> 32, Nanbeige 8 -> 16).

Adds regression tests for each item, the two new families to
FAMILY_MODEL_TYPES, registry fixture updates, and docs/awq-scaling-groups.md.
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.

1 participant