Repository navigation
fix(models): correct remote-code AWQ trees, coverage, position replay, and looped calibration (#4093) - #4109
Merged
Merged
Conversation
…, 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.
This was referenced Nov 15, 2026
Merged
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.
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_valueandcrashed in AWQ replay, AWQ replayed one sample's
position_idswith anothersample'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 reusableLoopedLayerCaptureMixin(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:2pxfile:line(before)InstellaQModel(LlamaQModel)inherited the Llama norm names, so q/k/v had no source andmlp.gate/upfolded intoself_attn.o_projgptqmodel/models/definitions/instella.py:9gptqmodel/models/definitions/k2_horizon.py:140-157densedeclared; coverage counted declared specs onlygptqmodel/models/definitions/telechat2.py:25position_idsadded only when the key was absent; mismatchedposition_embeddingskeptgptqmodel/looper/awq_processor.py:2939gptqmodel/models/definitions/pangu_alpha.py(no override)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:2px3. Per-subsystem detail
3.1 Instella owns its norm names (item 1)
gptqmodel/models/definitions/instella.py:19-30now declarespre_attention_layernorm/pre_feedforward_layernorm(the real names atmodeling_instella.py:663-664) instead of inheriting the Llama tree.instellais 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):
3.2 K2-Horizon attention is one flat group (item 2)
gptqmodel/models/definitions/k2_horizon.py:151-157replaces the per-projectiondict entries with one flat
""tuple:q_proj:0,k_proj:0,v_proj:0,gate_proj:0:nosrc,o_proj:1. Theattention gate is not positively homogeneous, so it is a declared non-source.
3.3 TeleChat2 quantizes its input projections and can replay its attention (item 3)
gptqmodel/models/definitions/telechat2.py:31declares("query:0", "key_value:0", "dense:1"). AWQ replay neededTelechatAttention.forward(hidden_states, residual, attention_mask, ...); thenew
awq_module_replay_inputshook promotes the 2-D capture to 3-D, passes theblock 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 fedby
ModuleLooper.create_named_modules(module_looper.py:2161-2175).TypeError: TelechatAttention.forward() missing 1 required positional argument: 'residual'self_attention.query/key_valuenn.Linear(fp16)undeclared_snapshot() == {}3.4 AWQ replay rebuilds stale position scaffolding (item 4)
AWQProcessor._prepare_module_forward(awq_processor.py:2847) now:position_idswhenevershape[-1] != seq_len, not only when absent;module.rotary_emb/module.rotarywhen the model root has norotary (Nanbeige/DeciLM), and keeps it instead of re-resolving the root;
position_embeddingswhose sequence length does not match when norotary can rebuild it (
_position_embeddings_match,awq_processor.py:3003);exaone.py:19declaresrotary_embedding = "transformer.rotary".Variable-length AWQ (48- and 20-token calibration, sorted descending):
RuntimeError: size of tensor a (48) must match tensor b (20)3.5 PanGu's top-query layer replays the input HF gives it (item 5)
PanguAlphaQModel.prepare_layer_replay_kwargs(pangu_alpha.py:32) appliestransformer.ln_fto the last block's input and setscustom_query = transformer.wqe(position_ids)(arange when absent). Otherlayers are untouched.
Tiny PanGu, last-layer
q_projrelative error on query embeddings:3.6 Looped decoders calibrate on every loop (item 6)
gptqmodel/models/looped_capture.pyaddsLoopedLayerCaptureMixin(extractedfrom the HRM-Text implementation): one full forward per calibration sample with
a pre-hook on every physical layer, then
pre_quantizeserves the currentlayer's own invocations.
ModuleLooper.cache_inputspublishescache.captured_batch_countasprocessor.num_batches(module_looper.py:1767)so replay is not truncated to loop 0.
add_batchper moduletotal_ut_steps=4)num_loops=2)4. Failure and ambiguity contract
record_undeclared+ a "NOT declared" warningposition_idslength != replay lengthapply_rotary_pos_embarange(seq_len)position_embeddingslength != replay lengthTypeErrornum_batchessized from the capturecustom_querymodelln_f+wqe(position_ids)for the last block5. Change inventory
definitions/instella.py,k2_horizon.py,telechat2.py,exaone.pylooper/module_coverage.py,looper/module_looper.pylooper/awq_processor.py,models/base.pydefinitions/pangu_alpha.pyln_f+custom_querymodels/looped_capture.py(new),definitions/{hrm_text,ouro,nanbeige}.py,looper/module_looper.pytests/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.jsondocs/awq-scaling-groups.md,README.md6. Tests / guarantees
test_awq_scaling_groups.py(instella,k2_horizon)1e-5relativetest_instella_support.pytest_k2_horizon_support.py::test_k2_horizon_attention_projections_share_one_awq_groupo_projseparatetest_telechat2_coverage.pytest_awq_position_kwargs.pytest_pangu_alpha_replay.pyln_f+custom_query; GPTQ beats RTNtest_looped_decoder_capture.pycaptured_batch_countsettest_layer_module_coverage.py7. Validation
Environment:
/opt/venvs/cu130t/bin/python(Python 3.14t, torch2.16.0.dev+cu130, transformers 5.22.2),
PYTHONPATH=$PWD.Hardware: RTX 4090
GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7efor 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):
Pre-existing failures observed on
origin/main(not caused by this branch; verifiedon a clean
origin/mainworktree and on718256fd7):tests/test_hf_config_compat.py::test_normalize_hf_config_compat_restores_legacy_cache_length_helpers(
DummyCachehas noget_max_lengthin this environment)tests/test_hf_config_compat.py::test_resolve_trust_remote_code_overrides_when_native_support_existstests/test_awq_gptq_lifecycle.py::test_awq_capture_is_pre_forward_and_gptq_does_not_receive_the_hooktests/test_awq_per_module_bits.py::test_clip_search_uses_module_width[*](needs the absentparameterized)Before (
/tmp/defsA-before,718256fd7), same tests:8. Reviewer notes
protocol. These runs use 64 C4 docs and 40x512 wikitext-2 tokens; the defect
and the direction are identical (catastrophic -> sane, and AWQ now beats RTN).
num_loops=1is used in the item-4 Nanbeige fixture so that test exercisesposition-kwargs replay, not loop capture; loop capture has its own test.
config.jsonandremote code; every fixture-gated test skips with a precise reason when the
local path is absent.