Repository navigation
refactor(awq): build scaling groups from fold declarations; the tree tracker stays only as the test oracle - #6480
Merged
Conversation
…the fold inventory The meta inventory pinned source, targets, consumers, boundary, feature, search members and span_roots, but not the other node fields AWQProcessor._quantize_layer reads: `_awq_allow_partial_replay` (set by phi4mm's override), which input tensor `inp` is, which feature's kwargs a group replays with, and any extra key that reaches _search_best_scale. layer_plan now hands the planner one kwargs marker per feature and records `partial_replay`, `inp` and `kwargs` (when they are not the group's own feature) and `keys` (unknown node keys). Four config variants the AWQ unit tests exercise but the inventory did not are added (nanbeige qk_layernorm, minimax MHA, exaone GQA, solar_open2 tiny MHA). The fixture is regenerated on unchanged production code; the new fields appear for phi4mm (partial replay), cohere_compass (re-prepared position_embeddings), deci, nemotron-nas and qwen (override-built nodes without per-feature kwargs) and nemotron_omni (feature renamed to the MoE block). No previously recorded group changed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tracker stays only as the test oracle BaseQModel.awq_get_modules_for_scaling now builds the processor's scaling nodes from awq_fold_declarations(layer), whose default is the module plan's role-derived folds plus the definition's awq_folds data (canonical_awq_folds). The tree-order backward tracker (_awq_generic_get_modules_for_scaling) no longer runs for those definitions, and the declared path no longer re-runs it to borrow a feature, kwargs and replay module: * every fold is validated by fold_rules.declared_fold before mutation; a target may be any quantized module applying an [out, in] weight (Qwen3-Next's AWQ tree quantizes its router), and a fold that spans sibling branches of its declared boundary is legal; * merge_by_source supplies the replay boundary; a span_roots fold scores the targets inside it and folds the rest (#4741), as _merge_shared_source_nodes did; * the search input is the first captured target of the fold's first branch, or the MoE root capture for gate/up groups (#4697/#4760/#4903); the derived default keeps a routed expert's empty down capture for the processor's starved-member fallback (#4675), declared overrides skip it (#5995), as on main. A definition whose declarations do not yet reproduce its effective groups sets awq_groups_from_tree_order = True and keeps the tracker (92 of 210 types): 24 whose declarations change an effective group (tracker-gap v -> o and DeltaNet folds, canonical-unsafe v -> o on gated attention, exaone's GQA data fold, openvla's phi-2 backbone, qwen.py's kwargs, decilm.py's duplicates), 66 whose only difference is the tracker's width-mismatched drop:width groups, which the processor drops but which can still route a starved member to fallback, plus bailing_moe and nemotron_h_puzzle through their class. test_tracker_planned_cases_still_need_the_tracker re-plans them from declarations, so the list can only shrink. The per-model awq_get_modules_for_scaling overrides still call super() and post-filter. The fold inventory (now recording every node field the processor reads) is unchanged for all 210 types: inventory --check reports no change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Qubitium
marked this pull request as ready for review
November 30, 2026 05:49
Merged
12 tasks done
Qubitium
added a commit
that referenced
this pull request
Nov 30, 2026
… redundant (batch A) (#6493) Since #6480 these definitions plan AWQ groups from their fold declarations (canonical_awq_folds plus awq_folds), and their awq_get_modules_for_scaling post-filters mostly guarded against the old tree tracker's stale fallbacks. Deleted (no replacement; the role-derived folds never emit what they strip): * baichuan, llada2, spark2_5: o_proj/dense/out_proj never joins a norm group, and the packed QKV projection never matches o_proj's width. * gemma3n (text and composite): input_layernorm and v_proj are `nosrc`, so no attention group exists for the KV-shared retarget to act on. * gemma4/gemma4_unified: _retarget_attention_output_folds. v_proj is `nosrc`, so no group targets o_proj. The four overrides keep only retarget_kv_shared_attention_groups (KV-shared q_proj boundary). Replaced by data or a fold-declaration variant: * deepseek_v2: `nosrc` on kv_a_proj_with_mqa and kv_b_proj instead of dropping o_proj groups. Without it a config with kv_lora_rank + qk_rope_head_dim == heads * v_head_dim (tests/test_awq_mla_scaling.py's tiny config) would fold kv_a_proj_with_mqa into o_proj. * k2_horizon: `nosrc` on the attention v_proj instead of stripping o_proj (MHA widths would add v_proj -> o_proj) and `postnorm` on q_norm/k_norm instead of re-pinning the attention group to input_layernorm (with heads * head_dim == hidden_size the norm walk would pick q_norm). The override keeps only the MoVA rule (no input_layernorm group when v_router is present). * lfm3, raon1_mini: awq_fold_declarations keeps the input-norm folds only (lfm3 also drops operator_norm on attention layers). lfm3_vl keeps the base declarations it reached before. Kept, because removing them changes the pinned plan: decilm (fold order and per-feature kwargs), qwen (per-feature kwargs), solar_open2 (tiny_mha would gain v_proj -> o_proj), deepseek_vl_v2 and xing4_0 (leaving the tracker drops their drop:width groups; that opt-out needs a maintainer decision). k2_horizon and gemma4 keep node-level overrides: a declaration override would switch their routed experts to the declared-path empty-capture contract. tests/module_tree/awq_fold_inventory.py --check reports no change for all 210 types. New regressions pin the coincident-width MLA config and K2 MHA, q/k-norm and MoVA layouts; Raon's negative control now builds the default folds. Co-authored-by: Claude Opus 5.5 <[email protected]>
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
… 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
added a commit
that referenced
this pull request
Dec 1, 2026
… fold-declaration variants (batch B) (#6636) 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]>
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.
Summary
AWQ lifecycle step 4b (map
awq_lifecycle.md, PR 4b).BaseQModel.awq_get_modules_for_scalingnow builds the processor's scaling nodes fromawq_fold_declarations(layer). That method's default is the module plan's role-derived folds plus the definition'sawq_foldsdata (canonical_awq_folds, merged in #6446/#6470). For 118 of 210MODEL_MAPtypes, production no longer runs the backward prev-op tracker (_awq_generic_get_modules_for_scaling). The declared path (PanGu, Inkling2-Loop) also stops re-running it to borrow a feature, kwargs and replay module.The tracker stays for two uses: as the test oracle, and for the 92 types that keep it through the declared opt-out
awq_groups_from_tree_order = True. Their declarations cannot yet reproduce today's groups byte-for-byte (below). No per-model function was added.Behavior-preserving on the measured surface:
--check:changed: none).dynamicexclusion. There main has a fold bug that this PR does not fix (see Notes).What Changed
Prerequisite guard (commit 1, fixture regenerated on unchanged
main).tests/module_tree/awq_fold_inventory.py::layer_plannow records the node fields the old fixture missed:partial_replay(_awq_allow_partial_replay, which phi4mm's override sets);inp(whichinput_feattensor, by identity);kwargs(which feature's per-feature kwargs, through one marker entry per feature, plus any added key);keys(any other node key).They are written only when they differ from the group's
feature. The regenerated fixture shows them for phi4mm, cohere_compass, deci, nemotron-nas, qwen and nemotron_omni; nothing else changed.gptqmodel/models/base.py:awq_fold_declarationsdefaults tocanonical_awq_folds(plan, layer, full_layer_modules(...), gqa_shape_gate=awq_scale_optimize_shape_dependent_modules, declared=awq_folds).Noneis gone._awq_nodes_from_declarationsis rewritten: validate (declared_fold), thenmerge_by_source(boundary,span_roots), then select the feature, then build the node.span_rootsbecomes_awq_search_layers/_awq_allow_outside_fold, exactly as_merge_shared_source_nodesdoes.downcapture for the starved-member fallback ([QUALITY] AWQ MoE: one starved, unrouted or dynamic-excluded expert sends ALL experts' gate/up to RTN (one all-or-nothing scale group); default AWQ on Qwen3-30B-A3B RTNs all 256 expert gate/up per layer #4675), while folds from a definition's own override skip it (Declare AWQ fold sources and consumers per layer variant #5995). Both are main's behavior.awq_get_modules_for_scalingroutesawq_groups_from_tree_orderdefinitions to the tracker and everything else to the declarations. The per-modelawq_get_modules_for_scalingoverrides still callsuper()and post-filter (deleted in PRs 5-7).gptqmodel/quantization/awq/fold_rules.py::declared_fold, now run for every fold:[out, in]weight, not onlynn.Linear. Qwen3-Next's AWQ tree quantizes itsQwen3NextTopKRouter, which main already folds. Conv1D is still rejected.span_rootswith aboundary.Data:
awq_groups_from_tree_order = Trueon the definitions listed below (74 classes in 70 files), and an explicitFalseonDeepSeekV4QModel, which inherits from opted-out V3 but is byte-equal.Docs:
docs/awq-scaling-groups.md(declarations, legality table, new flow diagram; the tracker diagram is kept as the opt-out path). Docstrings inawq_folds.py.Out of scope / follow-ups: deleting the overrides (PRs 5-7) and the tracker (PR 8); a behavior PR to unify the two empty-capture contracts; width-gating
awq_foldsdata (exaone GQA); the 66 junk-only opt-outs (Notes).Who keeps the tracker, and why (each is a
TRACKER_PLANNEDentry or the width-drop rule intests/module_tree/test_awq_fold_inventory.py)self_attn.v_proj -> o_proj: the tracker loses it behind a:!leaf. Adopting it changes numerics.pre_mlp_layernorm -> mlp), apertus, apertus1p5, apertus1p5_text, bailing_hybrid, exaone4_5, glm5_next, hrm_text, mage_vl, mimo_v2, qwen3_vl, qwen3_vl_moeself_attn.v_proj -> o_projon a variant the AWQ unit tests build (now in the inventory)qk_layernorm), minimax (MHA), solar_open2 (tiny MHA; canonical-unsafe:o_projreads a gated output)input_layernorm -> in_proj_qkv, in_proj_zfoldawq_foldsdata foldattn.attention.v_proj -> out_projraises on a GQA layout: data folds are not width-gated yetgqa)self_attn.v_proj -> dense, which no role names andawq_foldscannot declare for one backbone only (found bytests/module_tree/test_openvla_local_port.py)v -> oand dense MLP foldsqwen.py's override appendsw1 -> c_projwith layer kwargs; theawq_foldsfold carriesc_proj's per-feature kwargsdecilm.py's override re-appendsv -> oandup -> down: duplicate source raisesdrop:widthgroups (width-mismatched Linear->Linear guesses such as fused QKV -> dense, GQA v -> o, MLA latents) disappearBailingMoeQModel), nemotron_h_puzzle (inheritsNemotronHQModel; its expert-0-unrouted split also differs, below)Tests
New or changed tests:
tests/module_tree/test_awq_fold_inventory.py::test_tracker_planned_cases_still_need_the_tracker[*]: re-plans every opted-out case from declarations. A listed case must still change an effective group. Any other case of an opted-out definition may differ only by itsdrop:widthgroups. So the opt-out list can only shrink.test_current_planner_matches_inventory[*]now also pinspartial_replay,inp,kwargsandkeys.tests/module_tree/test_awq_fold_declarations.py::test_default_declaration_is_the_role_derived_fold_setreplaces theNone-keeps-generic test. On a layer computingout(left(norm(x))) + right(norm(x)), the tracker emitsleft -> rightandright -> out, neither of which reads that output. The default emitsnorm -> leftonly, and the opt-out restores the tracker.Measured Impact
Not applicable (no claimed issue). E3 is bit-identical; wall-clock and peak memory are in the A/B logs below.
Model Support / Module Plan
Not applicable: no
MODEL_MAPentry, path, tag or fusion change. Definitions only gain the opt-out attribute.tests/module_tree/test_registered_module_plans.pyandtest_definition_subset_ordering.pypass (in E2).AWQ onboarding safety
No new grouping: every type's effective plan is unchanged (E1). This includes every node field the processor reads, and the scaling-group/neutrality suites pass unchanged (E2). Per-variant AWQ policy is unchanged from main.
Data-dependent oracle.
perturb2.pyruns origin/main and the branch, each in its own interpreter, over 210 types, every config variant and each distinct layer, with 3 seeds per perturbation: 4714 plans.dynamicexclusion)dynamicin_proj_zcaptureLogic Flow Documentation
file:lineevidence.docs/repeats the diagrams, titled for the mechanism, and is linked fromREADME.md(docs/awq-scaling-groups.md).flowchart TD A["awq_get_modules_for_scaling"] --> B{"awq_groups_from_tree_order?"} B -- "no" --> C["awq_fold_declarations(layer)<br/>default: canonical_awq_folds + awq_folds"] C --> D["_resolve_awq_fold_declarations<br/>declared_fold per fold"] D -- "malformed" --> E["raise AWQFoldDeclarationError"] D --> F["merge_by_source<br/>boundary and span_roots"] F --> G{"search input captured?<br/>MoE root or first branch"} G -- "no" --> H["skip group<br/>targets quantize plainly"] G -- "yes" --> I["generate_node_for_awq_scaling<br/>feature, kwargs, boundary"] B -- "yes" --> T["_awq_generic_get_modules_for_scaling<br/>tree-order tracker"] T --> M["_merge_shared_source_nodes"] I --> O["_filter_awq_scaling_sources"] M --> O O --> S["AWQProcessor._quantize_layer"] style E fill:#f8d7da,stroke:#842029,stroke-width:2px style H fill:#fff3cd,stroke:#997404,stroke-width:2px888959022)awq_fold_declarationsreturnsNone(base.py:7141), so the tracker runs (awq_get_modules_for_scaling, base.py:7375 ->_awq_generic_get_modules_for_scaling, base.py:7385)awq_fold_declarationsreturnscanonical_awq_folds(...)(base.py:7145); the tracker runs only forawq_groups_from_tree_order(base.py:1722, 7336)merge_by_sourceboundary, first-branch or MoE-root feature (base.py:7263)declared_foldfor overrides only;nn.Lineartargets; no cross-branch folddeclared_foldfor every fold;[out, in]targets;span_rootswith aboundary(fold_rules.py:171, 187)_merge_shared_source_nodessets_awq_search_layers/_awq_allow_outside_fold(base.py:8068)span_rootsfrommerge_by_sourcesets the same node keysReview Requirements
Kernel Accuracy Requirements
Not applicable: no kernel, pack or dispatch change (E3 shows identical packed tensors).
Notes
Equivalence evidence.
HF_HUB_OFFLINE=1 python -P tests/module_tree/awq_fold_inventory.py --checkgiveschanged: none(210 types).AWQConfig(bits=4, group_size=128), 64 wikitext rows, seed 0, origin/main vs branch on the same GPU, every safetensors tensor compared bytewise plus the json andquant_log.csvfiles:All runs are on the rebased head against
c37c3f12e. A first round against888959022was also bit-identical for all seven. Peak memory on the two MoE models varies between runs on both sides (Qwen1.5-MoE main 2017 then 1984 MiB; branch 2105 then 2143). No measurable VRAM claim is made. Not run: Qwen3-30B-A3B (cached but too large for a modest-memory lane), Qwen2.5-VL-3B and Granite-4.0-H-350m (cached, but qwen2_5_vl and granitemoehybrid stay on the tracker, so the A/B would only exercise main's code), and Qwen3.5 (qwen3_5 is opted out).Real bug on main, left alone. Suppose
dynamicexcludes a module that reads a norm shared with a quantized block of another tree block: cohere/stablelm's parallel MLP, qwen3.5-familylinear_attn.in_proj_z, or intern_s2_preview's shared expert. The tracker skips the excluded block and folds the norm into the remaining members with statusok. The excluded module still reads the norm and is not compensated, so the layer output changes. For example, with cohere andmlp.*excluded, main foldsinput_layernorm -> q/k/vonly. The branch keeps the excluded targets in the group, so the processor's coverage check falls back instead of folding. Preserving main here would mean re-implementing the tracker's per-block state (block features, block-local consumers, block boundaries) inside the new builder, so this is the one reachable divergence. It should get its own issue and fix; the safe fix compensates excluded readers as consumers.Junk-only opt-outs. For 66 types the declarations already reproduce every group the processor folds. They differ only by the tracker's
drop:widthgroups, whichcheck_layerdrops. Those groups matter only before the drop, where the fallback policy can send a starved member to the configured fallback. With the default0.5%threshold that cannot happen for these always-executed dense projections. Moving these types is a one-line removal each plus a fixture regeneration that deletes exactly those rows, once the maintainer accepts that, or after a processor change that checks the width DROP before the fallback policy.Two empty-capture contracts. The derived default keeps a routed expert's empty
downcapture (the tracker's MoE-down branch). A definition's ownawq_fold_declarationsskips it (main's declared path, Declare AWQ fold sources and consumers per layer variant #5995). Both are preserved here (base.py:7281); unifying them is a behavior PR.Net lines. Planner code shrinks by 40 lines (
base.py,awq_folds.py,fold_rules.py: +92/-132). The PR as a whole grows (80 files changed, 598 insertions(+), 238 deletions(-), fixture included) because the tracker must stay as the oracle and opt-out, and the 92 opt-outs are data lines (157 in 71 definition files). PRs 5-8 remove them together with the tracker.refactor(awq): share the planner's width predicates and feature-kwargs merge #6476 (shared planner predicates) merged while this was in progress. The branch is rebased onto it (no conflicts), and E1/E2/E3 were rerun against
c37c3f12e. The head is then rebased onto522e4c0c9. fix(awq): validate the plan path's sampled-row cache against the live host copy #6479 touches onlyawq_processor.py's sampled-row cache, not this PR's files; the onboarding baseline, the declaration tests and fix(awq): validate the plan path's sampled-row cache against the live host copy #6479'stest_awq_reservoir_sibling_rows_5267.pypass on the final head (787 passed, 2 skipped).🤖 Generated with Claude Code