Skip to content

refactor(models): replace config-conditional AWQ group overrides with fold-declaration variants (batch B) - #6636

Merged
Qubitium merged 1 commit into
mainfrom
refactor/awq-config-conditional-folds-b
Dec 1, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/awq-config-conditional-folds-b

Conversation

@Qubitium

@Qubitium Qubitium commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

AWQ PR 6 of the lifecycle cleanup (batch B). Since #6480, a definition without
awq_groups_from_tree_order plans its AWQ groups from
awq_fold_declarations(layer). This PR turns the config-conditional
awq_get_modules_for_scaling node filters on that path into small variants of
the derived folds. It also replaces the class-identity check that blocked those
variants with one declared flag.

Diff: 15 files changed, 135 insertions(+), 148 deletions(-) (net −13) (production code under gptqmodel/: 11 files changed, 75 insertions(+), 118 deletions(-), net −43).
No numerics, checkpoint-format or public-API change: the fold inventory, a
stress and data-dependent A/B over every MODEL_MAP type, and GPU AWQ A/B runs
are identical (see Tests).

What Changed

One mechanism fix that enables the variants. _awq_nodes_from_declarations
picked the empty-capture contract with
type(self).awq_fold_declarations is BaseQModel.awq_fold_declarations
(base.py:7687 on main). With that check, any variant would have changed a
routed expert's empty down capture from the processor's starved-member
fallback (#4675) to a skipped group (#5995). This is why #6493 kept the node
filters on k2_horizon and gemma4. The contract is now the declared class flag
awq_hand_declared_folds (default False). Only the two definitions that write
their own folds set it: PanGu and Inkling. A filter of super()'s folds keeps
the derived contract.

Overrides replaced by fold-declaration variants (each filters
super().awq_fold_declarations(layer)):

Definition Before (main) After
llama.py (all LlamaQModel subclasses) awq_get_modules_for_scaling returns [] for longllama / stablelm_epoch / yi / q/k-norm cohere and stablelm (llama.py:65) awq_fold_declarations returns [] under the same condition
telechat2.py node filter drops the key_value source and, in post-LN residual mode, both norm sources (telechat2.py:40) variant drops both norm folds in post-LN mode. key_value becomes key_value:0:nosrc in the tree; it has no v role, so the derived folds never use it
hymba.py node filter drops a gateless (relu2) expert's up_proj source and rewrites module2inspect from mamba to mamba.in_proj (hymba.py:60) variant drops the same folds and declares boundary="mamba.in_proj"
k2_horizon.py node filter drops input_layernorm on MoVA layers (k2_horizon.py:138) same filter on folds
gemma4.py x2, gemma4_unified.py x2 retarget_kv_shared_attention_groups(nodes) re-anchors the KV-shared self_attn group on q_proj (_kv_shared_replay.py:262, gemma4.py:310/399, gemma4_unified.py:125/174) kv_shared_attention_folds(layer, folds): the same rule applied to the folds (about 15 lines instead of 45)
ovis2_6_moe.py awq_get_modules_for_scaling calls BaseQModel.awq_get_modules_for_scaling past Ovis2_5QModel (ovis2_6_moe.py:96) deleted: Ovis2_5QModel no longer overrides it

AWQ_FOLD_DIFFERENCES loses the 13 entries that these variants close: llama x7,
telechat post_ln, hymba x2, gemma4_text kv_shared/parity_moe, and k2 MoVA.

Kept, with reasons:

Override Why it stays
bloom, chatglm, dbrx_converted, rw, ricursive, nemotron_h awq_groups_from_tree_order = True, and every type has drop:width tracker groups. Moving it to declarations drops them, which is the "66 junk-group-only" set that needs a maintainer decision. The tracker path never calls awq_fold_declarations.
nanbeige It stays on the tracker for TRACKER_PLANNED qk_layernorm. Declarations would add the v_proj -> o_proj fold that the tracker misses, which changes numerics.
kimi_k3 raise NotImplementedError is a fail-closed guard for an unsupported method, not a group filter. Moving it would make every awq_fold_declarations caller raise and would save no lines.
cohere_compass It re-prepares kwargs; the map keeps it until PR 10.
raon1_mini, deepseek_v4 MTP Already done: raon1_mini was converted in #6493, and the deepseek_v4 MTP override was deleted with #6435.

Out of scope / follow-ups:

  • The tracker-planned overrides above wait on the maintainer's drop:width
    decision.
  • AWQ PR 7 (batch C) can use awq_hand_declared_folds for its MoE definitions
    in the same way.

Tests

Interpreter: /root/venv/bin/python (torch 2.15.0+cu132, transformers 5.23.0).
Each side ran with its own checkout first on PYTHONPATH (python -P, printed
gptqmodel.__file__). main = origin/main cc0c705b7.

E1, fold inventory (all 210 types).

HF_HUB_OFFLINE=1 python -P tests/module_tree/awq_fold_inventory.py --check

Result: changed: none (210 types).

Stress and data-dependent A/B, main vs branch (extends #6493's ab_stress.py
and perturb.py). The script covers every MODEL_MAP type and every inventory
config variant. It adds a +mha variant of each (every attention config
num_key_value_heads == num_attention_heads) and extra stress variants:

  • TeleChat kv_half, where key_value out == dense in, with and without post-LN;
  • Hymba relu2 (default and released);
  • Cohere / StableLM q/k-norm combinations;
  • Gemma 4 / Gemma 4-Unified KV-shared tails on the composite and unified trees,
    plus the composite parity MoE config;
  • Gemma 4 text KV-shared + k_eq_v.

For each distinct decoder layer it plans five input-feature cases: full, half
of the routed experts unrouted (empty captures), 20% absent features (dynamic
exclusions), 20% empty features, and an empty MoE root. Each case records every
node field that the processor reads.

python -P ab_perturb.py all --seeds 2

Result: compared 7248 layer plans over 530 config variants (210 types); build errors identical on both sides: 36; types with differences: []. The new Gemma 4 stress variants exercise the KV-shared rule: there are q_proj-boundary groups on gemma4 kv_shared/parity_moe, gemma4_unified kv_shared and gemma4_unified_text kv_shared. The 36 build errors are config variants that fail to build identically on both sides; they match the build errors already recorded in the fixture.

Negative control: on the branch, with the old identity check put back (not
awq_hand_declared_folds), the same A/B reports differences on hymba and
gemma4_text/parity_moe in the unrouted and empty20 cases. The flag is what
keeps those identical.

E2, CPU suites, main vs branch. 189 test files: the onboarding-skill
baseline, every file in the map's E2 list, every test calling
awq_get_modules_for_scaling / awq_fold_declarations, and every test naming
a touched definition (llama family, telechat, hymba, ovis2_6, pangu, inkling2,
lfm3, raon1, gemma4, k2_horizon, kv-shared). tests/models/ (GPU checkpoints)
is excluded.

HF_HUB_OFFLINE=1 CUDA_VISIBLE_DEVICES= python -P -m pytest -n 40 -q -rs <189 files>

Result on the final branch (rebased) vs main cc0c705b7:

  • main: 2 failed, 6732 passed, 786 skipped, 2 xfailed
  • branch: 1 failed, 6734 passed, 786 skipped, 2 xfailed, plus the 1 new test

All passing node ids are the same. The only differences are three load-sensitive tests whose outcome flips between runs on both sides, so they are flaky rather than caused by this change:

  • tests/test_awq_hybrid_recurrent_mask_4671.py::test_awq_batch_size_one_quantizes_a_mamba_hybrid: the tiny tokenizer fixture is "unusable" under -n 40. It failed on main in run 1 and on the branch in run 2, and passes on both sides in isolation.
  • tests/test_awq_weight_mean.py::test_awq_pseudo_quantize_nan_guard_uses_one_host_read: fails on both sides in run 1 and on main only in run 2.
  • tests/test_awq_weight_mean.py::test_awq_weight_mean_matches_legacy_impl (cpu, group size 64): a wall-clock speed assertion that failed on main only in run 2.

Skips, the same on both sides, and what they leave unverified:

  • 460 Marlin and other CUDA-qualification tests, plus about 90 CUDA/accelerator-only tests: kernels and GPU paths. No kernel is touched, and the GPU AWQ path is covered by E3 below.
  • 139 opt-in -m meta_coverage sweeps in test_moe_expert_coverage.py: module-tree expert coverage. The only tree change is a TeleChat nosrc flag, which is not a coverage change.
  • 6 TeleChat2-115B release-asset tests that need network access: the pinned release layout. The tiny native TeleChat tests run.
  • LFM3 /monster/data checkpoint tests: real LFM3 checkpoints. E3 covers LFM3-1.7B.

After the rebase onto e24a4dd2c, these re-ran and passed (1133 tests): test_awq_fold_inventory.py, test_hymba_awq_4891.py, test_ovis2_6_moe_local_port.py, test_awq_shared_kv_states_replay.py, test_k2_horizon_support.py, test_telechat2_local_port.py, test_llama_local_port.py, test_awq_fold_declarations.py and test_awq_moe_starved_expert_group_4675.py. The commits pulled in by the rebase do not touch any changed file or the AWQ group planner.

New and changed tests:

  • tests/test_hymba_awq_4891.py::test_hymba_fold_variant_keeps_the_derived_unrouted_expert_contract
    (new). A Hymba layer with one unrouted expert keeps that expert's
    up_proj -> down_proj group with its empty capture, exactly as the derived
    default does. With awq_hand_declared_folds the group is skipped. It fails on
    the branch with the old identity check.
  • tests/test_hymba_awq_4891.py::test_owned_hymba_drops_only_the_gateless_expert_up_to_down_fold
    (changed). Its "generic" oracle is now the derived declarations
    (BaseQModel.awq_fold_declarations), because BaseQModel.awq_get_modules_for_scaling
    now dispatches to Hymba's variant.
  • tests/module_tree/test_ovis2_6_moe_local_port.py (changed). It asserted that
    the removed pass-through override exists. It now asserts that Ovis2.6 uses the
    base planner and declarations.

E3, GPU AWQ A/B (GPU 2): AWQConfig(bits=4, group_size=128), bf16, 64
wikitext-2 rows, batch 4, seed 0, the same on both sides. Every saved
safetensors tensor is compared bytewise, and every json and quant_log.csv
(time column excluded) is compared.

Model Touched path Result
Llama-3.2-1B-Instruct (unsloth mirror) LlamaQModel.awq_fold_declarations bit-identical: 370 tensors plus config/quantize_config/quant_log/tokenizer files
Qwen2.5-0.5B-Instruct Llama subclass (Qwen2QModel) bit-identical
LFM3-1.7B a filtering variant that is now derived under the flag bit-identical
gemma-4-E2B-it (20 KV-shared layers) kv_shared_attention_folds, Gemma 4 composite bit-identical: 2501 tensors plus all jsons and quant_log

The Llama branch run used the branch revision from before the Gemma 4 / K2 conversion. Those later edits do not touch the LlamaQModel path. Peak CUDA memory: 0.4 to 1.2 GiB.

Lint: bash format/check.sh passes: All checks passed! (ruff 0.14.2).

Re-verified after rebase onto 9d7c6f403 (head 44ee68326)

Rebased over #6624 (AWQ batch C), #6630 (tree-order dynamic-excluded reader), #6633/#6634 (scale limit, stateless rotary) and #6637. The only conflicts were in docs/awq-scaling-groups.md and AWQ_FOLD_DIFFERENCES, against #6624's entries; both sides were kept.

  • python -P tests/module_tree/awq_fold_inventory.py --check: changed: none (210 types).
  • Plan A/B main vs branch with capture perturbations (3 seeds): 10042 layer plans over 530 config variants, no differences; build errors identical on both sides (36).
  • E2 (189 files, CPU, -n 40): branch 6743 passed / 786 skipped / 2 xfailed; main 6742 passed / 786 skipped / 2 xfailed. No failures on either side.
  • GPU AWQ A/B (seeded, same calibration): Llama-3.2-1B-Instruct 370 tensors and gemma-4-E2B-it 2501 tensors, plus config/quant_log files: bit-identical.
  • bash format/check.sh: all checks passed.

Measured Impact

Not applicable: behaviour-preserving refactor. The E3 checkpoints are
bit-identical.

Model Support / Module Plan

No new MODEL_MAP entry. The only module-tree change is
telechat2.py: key_value:0 -> key_value:0:nosrc. That flag affects AWQ
sources only, and key_value was never one. Registry and module-plan tests
(test_registered_module_plans.py, test_definition_subset_ordering.py,
test_telechat2_local_port.py) pass. Model test node IDs are in the E2 run
above.

AWQ onboarding safety

No variant changes which groups are searched or folded. Every variant
reproduces the node filter it replaces on every config, layer variant and
capture perturbation above. The existing per-model neutrality tests still pass:
tests/module_tree/test_telechat2_local_port.py::test_awq_scale_folds_preserve_every_decoder_layer_output,
tests/test_hymba_awq_4891.py::test_owned_hymba_awq_folds_preserve_layer_output,
tests/test_awq_shared_kv_states_replay.py, tests/test_k2_horizon_support.py
and tests/test_llama_local_port.py. Per-variant policy is unchanged: the
Llama alias layouts are plain-quantization-only, TeleChat post-LN is up -> down
only, Hymba relu2 experts have no up -> down, K2 MoVA layers have no
input-norm fold, and a Gemma 4 KV-shared tail scores q_proj alone.

Logic Flow Documentation

This replaces a decision mechanism (per-model node filters, plus a
class-identity contract) with declared folds and a declared flag.
docs/awq-scaling-groups.md (already linked from README) has the updated flow
diagram and text.

flowchart TD
    A["awq_get_modules_for_scaling"] --> B{"awq_groups_from_tree_order?"}
    B -- "yes" --> T["_awq_generic_get_modules_for_scaling<br/>tracker, plus kept node overrides"]
    B -- "no" --> C["awq_fold_declarations(layer)"]
    C --> C1["BaseQModel: canonical_awq_folds + awq_folds"]
    C1 --> C2["definition variant filters super():<br/>llama, telechat2, hymba, k2_horizon,<br/>gemma4 kv_shared_attention_folds"]
    C2 --> D["_resolve_awq_fold_declarations"]
    D -- "malformed" --> E["raise AWQFoldDeclarationError"]
    D --> F["merge_by_source"]
    F --> G{"search input captured?"}
    G -- "no" --> H["skip group<br/>targets quantize plainly"]
    G -- "empty" --> X{"routed expert down and<br/>not awq_hand_declared_folds?"}
    X -- "no" --> H
    X -- "yes" --> I["node for the processor's<br/>starved-member fallback"]
    G -- "yes" --> I2["generate_node_for_awq_scaling"]
    style E fill:#f8d7da,stroke:#842029,stroke-width:2px
    style H fill:#fff3cd,stroke:#997404,stroke-width:2px
Loading
Situation Before (main) After
Empty-capture contract type(self).awq_fold_declarations is BaseQModel.awq_fold_declarations (base.py:7687) not self.awq_hand_declared_folds (base.py:7717); True only on pangu_alpha.py:45, inkling2_loop.py:146
Llama unqualified aliases node override llama.py:65 returns [] awq_fold_declarations returns [] (llama.py:65)
TeleChat2 post-LN / key_value node override telechat2.py:40 variant telechat2.py:42, key_value:0:nosrc
Hymba relu2 / mamba boundary node override rewrites module2inspect (hymba.py:60) variant declares boundary="mamba.in_proj" (hymba.py:60)
K2-Horizon MoVA node override k2_horizon.py:138 variant k2_horizon.py:138
Gemma 4 KV-shared tail retarget_kv_shared_attention_groups(nodes) (_kv_shared_replay.py:262) kv_shared_attention_folds(layer, folds)
Ovis2.6 pass-through ovis2_6_moe.py:96 removed

Review Requirements

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

Not applicable: no kernel change.

Notes

  • Known behaviour preserved, not fixed here: AWQ with dynamic excluding a
    block that reads a shared norm still folds the norm into the remaining blocks
    on the tracker path.
  • awq_hand_declared_folds is new class data. Any out-of-tree definition that
    writes its own expert down folds in awq_fold_declarations must set it to
    keep the skip contract.

🤖 Generated with Claude Code

@Qubitium
Qubitium marked this pull request as ready for review December 1, 2026 09:50
… fold-declaration variants (batch B)

Since #6480 a definition without `awq_groups_from_tree_order` plans its AWQ
groups from `awq_fold_declarations(layer)`. Its config-conditional
`awq_get_modules_for_scaling` post-filters become small variants of the
derived folds:

* llama: `awq_fold_declarations` returns `[]` for LongLLaMA, StableLM-Epoch,
  Yi and q/k-norm Cohere/StableLM, else `super()`.
* telechat2: drops the two norm folds in post-layernorm residual mode. The
  `key_value` filter is moved into the tree as `key_value:0:nosrc` (the
  derived folds never use it: it has no `v` role).
* hymba: drops a gateless (relu2) expert's `up_proj -> down_proj` and declares
  the input-norm fold's replay boundary as `mamba.in_proj` instead of
  rewriting `module2inspect`.
* k2_horizon: drops the input-norm fold on MoVA layers.
* gemma4, gemma4_unified (text and composite):
  `retarget_kv_shared_attention_groups(nodes)` becomes
  `kv_shared_attention_folds(layer, folds)`, which replays a KV-shared
  layer's input-norm fold on `self_attn.q_proj` alone.
* ovis2_6_moe: deleted. It only called `BaseQModel.awq_get_modules_for_scaling`
  past Ovis2_5QModel, which no longer overrides it.

`_awq_nodes_from_declarations` chose the empty-capture contract by class
identity (`type(self).awq_fold_declarations is BaseQModel...`), so any
variant would have moved a routed expert's empty `down` capture from the
processor's starved-member fallback (#4675) to a skip (#5995). That would
have changed Hymba's and Gemma 4's MoE layers, and it is why #6493 kept the
K2-Horizon and Gemma 4 node filters. The contract is now the
declared `awq_hand_declared_folds` flag, set by the two definitions that write
their own folds (PanGu, Inkling); a filter of the derived folds keeps the
derived contract.

Kept, because removing them changes behaviour or needs a maintainer decision:
bloom, chatglm, dbrx_converted, rw, ricursive and nemotron_h still plan from
the tree tracker and have drop:width groups (leaving the tracker drops them);
nanbeige stays on the tracker for its qk_layernorm tracker gap; kimi_k3's
NotImplementedError is a fail-closed guard, not a group filter; cohere_compass
re-prepares kwargs until PR 10. raon1_mini was converted in #6493 and the
deepseek_v4 MTP override was removed with #6435.

`tests/module_tree/awq_fold_inventory.py --check` reports no change for all 210
types; a stress and data-dependent A/B (MHA and coincident-width variants,
unrouted experts, absent and empty captures) is equal on all 210 types, and a
GPU AWQ A/B is bit-identical.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium force-pushed the refactor/awq-config-conditional-folds-b branch from 2da970a to 44ee683 Compare December 1, 2026 10:04
@Qubitium
Qubitium merged commit 64c1b98 into main Dec 1, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/awq-config-conditional-folds-b branch December 1, 2026 10:09
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