Skip to content

refactor(models): move the remaining structural AWQ overrides to fold data (batch C) - #6624

Merged
Qubitium merged 1 commit into
mainfrom
refactor/awq-structural-folds-c
Dec 1, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/awq-structural-folds-c

Conversation

@Qubitium

@Qubitium Qubitium commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Summary

AWQ lifecycle step 7, batch C (map awq_lifecycle.md, PR 7). The structural awq_get_modules_for_scaling overrides that built or patched scaling nodes by hand now come from the fold declarations (canonical_awq_folds plus awq_folds data), where that reproduces the current plan exactly. Four of the seven targets move (phi4mm, intern_s2_preview, minicpmv_4_6, solar_open2). Three stay (ernie4_5_vl_moe, nemotron_omni, nemotron_h_puzzle), because moving them changes a reachable plan; the reasons are below.

Behavior-preserving:

  • E1: awq_fold_inventory.py --check reports changed: none for all 210 types.
  • Structural stress A/B: 52 cases are equal to main: the inventory variants plus the MHA variant of every config of the touched and kept types (intern_s2_preview, minicpmv4_6, phi4mm, solar_open2, nemotron_h_puzzle, ernie4_5_vl_moe/ernie4_5_moe_vl, nemotron_omni, nemotron_h, qwen3_5); solar_open2 dense-prefix (first_k_dense_replace=1) and MHA+dense variants; the unit-test tiny configs (MiniCPM-V 4.6 DeltaNet text layout, Puzzle tiny/MHA/no-latent/bias); and coincident widths (Puzzle moe_latent_size equal to the hidden size or the expert width).
  • Data-dependent A/B: 523 perturbed plans (full; half the routed experts unrouted; 20% of features absent, i.e. a dynamic exclusion; 20% empty; MoE root empty; 3 seeds; every distinct layer of every variant above). The only differences are unreachable. Intern-S2 and MiniCPM-V 4.6 differ when the dense in_proj_qkv capture is empty (a dense projection sees every token of its layer). Solar Open 2 differs only when the MoE root mlp capture is empty while experts hold rows ([QUALITY] AWQ silently drops the routed-expert gate/up scaling group for 15 MoE definitions without moe_lifecycle_hooks (gpt-oss, Granite-MoE, ERNIE-4.5-MoE, Gemma-4, Nemotron-H...): MoE-root capture is never registered #4697: the root sees every routed token). Before the in_proj_qkv-capture filter, the perturbation also found the reachable dynamic-exclusion difference that the filter now preserves.
  • E3: bit-identical checkpoints (every tensor plus config jsons and quant_log.csv) on seeded tiny MiniCPM-V 4.6, Intern-S2-Preview and Solar Open 2 fixtures (GPU), a tiny phi4mm fixture (CPU, see Notes) and Qwen2.5-0.5B-Instruct (GPU control).

AWQ_FOLD_DIFFERENCES is not empty after this PR. The map's goal assumed all of batch C could move; the entries left belong to PR 6 (config-conditional overrides), the tracker-gap/canonical-unsafe cases that need a quality-evidenced PR, and the three kept definitions here.

What Changed

Definition origin/main This PR
phi4mm awq_get_modules_for_scaling (phi4.py:67) keeps norm groups, replaces their consumers with each target's lora_A.{vision,speech} and sets _awq_allow_partial_replay (phi4.py:95) two awq_folds entries with those consumers and partial_replay=True
intern_s2_preview 35-line DeltaNet builder (intern_s2_preview.py:89): drops every group touching linear_attn, hand-builds input_layernorm -> in_proj_qkv, in_proj_z (consumers in_proj_b/a, boundary linear_attn) when in_proj_qkv was captured, renames past_key_values to cache_params the :in=x tags already derive that group. A 2-line filter keeps one corner: no group without an in_proj_qkv capture
minicpmv_4_6 the same builder on top of the tree tracker (minicpmv_4_6.py:18, :72) DeltaNet layers plan from the declarations with the same filter. Full-attention layers keep the tracker
solar_open2 tracker (solar_open2.py:17) plus an override (solar_open2.py:85) that strips o_proj from norm groups and restores the dense-prefix mlp.up_proj -> down_proj declarations: v_proj:0:nosrc (o_proj reads the gated output; tiny MHA would otherwise gain v_proj -> o_proj), and up -> down is a role-derived fold

Shared code:

  • AWQFoldDeclaration.partial_replay (awq_folds.py): the boundary replay may not execute every member; _awq_nodes_from_declarations (base.py) turns it into _awq_allow_partial_replay.
  • merge_by_source: a merged fold that adds only consumers keeps the group's boundary. Without this, phi4mm's data fold for the same single target re-anchored the group from self_attn to the target. No other type merges such a fold (E1).
  • tests/module_tree/test_awq_fold_inventory.py: phi4mm leaves AWQ_FOLD_DIFFERENCES; solar_open2 tiny_mha leaves AWQ_FOLD_DIFFERENCES and TRACKER_PLANNED.
  • docs/awq-scaling-groups.md: the new field, the consumer-only merge, and the DeltaNet note.

The past_key_values -> cache_params rename is dropped on purpose. In the old flow _search_best_scale re-adds the layer's past_key_values through setdefault from the global kwargs, and both definitions' awq_module_replay_inputs reject a non-None cache under either name. The only difference in the DeltaNet replay is an explicit cache_params=None (its default). This was recorded on GPU by wrapping the DeltaNet forward:

main  : replay kwargs {attention_mask, cache_params, past_key_values, position_embeddings, position_ids, use_cache}; non-None {attention_mask, position_embeddings, position_ids, use_cache}
branch: replay kwargs {attention_mask, past_key_values, position_embeddings, position_ids, use_cache};               non-None {attention_mask, position_embeddings, position_ids, use_cache}

Kept, with the reason:

Override Why it stays
ernie4_5_vl_moe.py:400 (+ tracker :26) The declarations already equal the override's MoE group (routers and every shared/text/vision gate/up). But leaving the tracker drops its width-dropped self_attn.v_proj -> o_proj group on every layer. That is one of the 66 drop:width-only opt-outs, and the group can still route a starved member to fallback.
nemotron_omni.py:181 (tracker via NemotronHQModel) It has the same drop:width group on attention layers. Also, the MoE group's _input_feature_name="mixer" (which lets the processor split a starved routed expert, #4675) has no declaration form: the nested mixer.experts root is not captured, so the declared feature would be mixer.shared_experts.up_proj.
nemotron_h_puzzle.py:47 (tracker via NemotronHQModel) The declarations (with v_proj:nosrc) equal the inventory and the unit-test tiny configs, but the perturbation A/B finds three reachable differences. (1) Unrouted routed experts on a non-latent layout: the tracker plans a shared-expert-only group that falls back, while the declarations skip the group, because puzzle does not capture its MoE root. (2) A dynamic exclusion of shared_experts.up_proj on latent layouts: the tracker still folds the norm into fc1_latent_proj, while the declarations drop the group. This is the known shared-norm exclusion bug, preserved here. (3) moe_latent_size == hidden_size would add the routed experts to the norm group.

Out of scope: PR 6 (config-conditional overrides; nemotron_h belongs there), and releasing the 66 drop:width-only opt-outs (needs a maintainer decision).

Tests

  • Unit tests have been executed and passed, or the reason they are not applicable is documented.
  • I added a new simple/fast unit test for this change, or documented why that is not applicable.

New tests (all pass on origin/main's code and on this branch):

  • tests/module_tree/test_awq_fold_declarations.py::test_merge_keeps_the_group_boundary_when_a_fold_adds_only_consumers
  • tests/module_tree/test_intern_s2_preview_local_port.py::test_deltanet_input_group_searches_on_in_proj_qkv_capture[None|linear_attn.in_proj_qkv|linear_attn.in_proj_z]
  • tests/test_minicpmv46_awq_port.py::test_input_group_searches_on_in_proj_qkv_capture[linear_attn.in_proj_qkv|linear_attn.in_proj_z]
# CPU, PYTHONPATH=<clone>, HF_HUB_OFFLINE=1, CUDA_VISIBLE_DEVICES=, torch 2.15, transformers 5.23, python 3.14
# E2 (162 files): the onboarding baseline, tests/run_awq_cpu.sh unit, the map's fold/group/replay list, every test that
# calls awq_get_modules_for_scaling / awq_fold_declarations / AWQFoldDeclaration / merge_by_source, and every test file
# of a touched or kept type (phi4, intern_s2_preview, minicpmv46, solar_open2, ernie4_5_vl_moe, nemotron_h*, nemotron_omni),
# minus tests/models/test_cohere_compass.py (GPU model test)
python -P -m pytest $(cat e2_files.txt) -q -p no:cacheprovider -n 32 --timeout=1800 -rs
# origin/main cc0c705b7: 5774 passed, 107 skipped
# branch:                5778 passed, 2 failed, 107 skipped (+6 new tests)
#   FAILED tests/test_awq_weight_mean.py::test_awq_pseudo_quantize_nan_guard_uses_one_host_read  (scalar_reads 4 == 1)
#   FAILED tests/test_awq_hybrid_recurrent_mask_4671.py::test_awq_batch_size_one_quantizes_a_mamba_hybrid  (tokenizer "cannot encode")
#   Both are flaky on origin/main too: rerun alone, the pair gave "2 failed" three times on the main worktree, and
#   "1 failed, 1 passed" on the branch. Neither touches the planner.
# Skips (107, both sides): CUDA/accelerator/Triton/Marlin kernels with CUDA hidden, network release assets, optional
#   extras (minicpm-o), 2 non-buildable alias rows, 1 transformers sliding_window==1 case. No planner path is skipped.

# E1
python -P tests/module_tree/awq_fold_inventory.py --check        # 210 types, changed: none

# Structural / data-dependent A/B (scripts outside the repo; each side in its own interpreter)
python -P ab_stress.py --repo <branch> --out ab_{base,branch}.json; python -P ab_stress.py --compare ab_base.json ab_branch.json
#   cases=52 equal=52 differ=0
python -P perturb.py intern_s2_preview,minicpmv4_6,phi4mm,solar_open2,nemotron_h_puzzle,ernie4_5_vl_moe,ernie4_5_moe_vl,nemotronh_nano_omni_reasoning_v3 --seeds 3
#   compared 523 plans; non-junk differences: intern_s2_preview/minicpmv4_6 "empty" (in_proj_qkv capture empty),
#   solar_open2 "empty"/"root_empty" (MoE root capture empty): all unreachable, see Summary

# E3: AWQConfig(bits=4, group_size=16 tiny / 128 Qwen), seed 0, fixed calibration, BACKEND.TORCH, bf16; every saved
# tensor byte-compared plus config jsons and quant_log.csv (time columns excluded)
#   MiniCPM-V 4.6 tiny (DeltaNet + full attention, GPU)        97 tensors  bit-identical
#   Intern-S2-Preview tiny (DeltaNet/full attention + MoE, GPU) 289 tensors bit-identical
#   Solar Open 2 tiny (dense prefix + GQA/KDA + MoE, GPU)       165 tensors bit-identical
#   phi4mm tiny (text/image/audio calibration rows, CPU)        211 tensors bit-identical
#   Qwen2.5-0.5B-Instruct (wikitext, GPU control)               626 tensors bit-identical

# Lint
bash format/check.sh                                              # All checks passed!

Measured Impact

Not applicable: no numerics change. The GPU A/B above is bit-identical.

Model Support / Module Plan

No MODEL_MAP entries were added. Tree changes: one :nosrc flag on solar_open2 self_attn.v_proj (AWQ-only; GPTQ ignores it). Registry and per-model tests are in the E2 run above.

AWQ onboarding safety

No new groups. Every touched variant keeps its exact plan: E1 (210 types), the structural stress A/B (MHA / equal-width / dense-prefix / unit-test tiny configs) and the perturbation A/B (unrouted experts, dynamic exclusions, empty captures). The existing per-model neutral-fold, candidate-search and replay tests (test_minicpmv46_awq_port.py, test_intern_s2_preview_local_port.py, test_phi4_local_port.py, test_solar_open2_local_port.py) pass unchanged.

Logic Flow Documentation

  • This change does not alter a major logic flow, or the required diagrams and docs page are included below.

The generic flow in docs/awq-scaling-groups.md ("Flow") is unchanged. Per-definition hand-built nodes are replaced by declared data:

flowchart TD
    A["awq_get_modules_for_scaling(layer)"] --> B{"awq_groups_from_tree_order?<br/>(minicpmv_4_6: full-attention layers only)"}
    B -- "no" --> C["canonical_awq_folds + awq_folds<br/>phi4mm: lora_A consumers, partial_replay"]
    C --> D["merge_by_source<br/>consumer-only fold keeps the boundary"]
    D --> E["_awq_nodes_from_declarations<br/>partial_replay -> _awq_allow_partial_replay"]
    E --> F{"intern_s2 / minicpmv_4_6:<br/>feature == linear_attn.in_proj_z?"}
    F -- "yes (no in_proj_qkv capture)" --> G["drop the DeltaNet input group<br/>in_proj_z quantizes plainly"]
    F -- "no" --> H["scaling nodes"]
    B -- "yes" --> T["tree tracker (ernie, nemotron_omni, puzzle, minicpmv full attention)"]
Loading
Old mechanism (origin/main) New
phi4.py:67-98 node rewrite phi4.py awq_folds + AWQFoldDeclaration.partial_replay
intern_s2_preview.py:89-125 DeltaNet builder :in=x derivation + 2-line filter
minicpmv_4_6.py:72-106 builder on tracker output declarations on DeltaNet layers + same filter
solar_open2.py:85-141 strip/restore + tracker (:17) v_proj:nosrc + role-derived up -> down

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 is touched.

Notes

  • Found, not fixed (main and branch alike): phi4mm AWQ on CUDA crashes in the scale-search replay: apply_rotary_pos_emb gets CPU cos/sin (Expected all tensors to be on the same device, modeling_phi4_multimodal.py:1216). _prepare_module_forward rebuilds position_embeddings with the root rotary, which stays on CPU for phi4mm (no rotary_embedding declaration). So the phi4mm A/B above ran on CPU.
  • Two tests are flaky on origin/main, independent of this PR: test_awq_hybrid_recurrent_mask_4671.py::test_awq_batch_size_one_quantizes_a_mamba_hybrid (the tiny tokenizer sometimes "cannot encode ordinary text") and test_awq_weight_mean.py::test_awq_pseudo_quantize_nan_guard_uses_one_host_read (scalar_reads 4 instead of 1). Both fail and pass intermittently on the main worktree too.
  • A/B scripts: ab_stress.py, perturb.py (extended from PR 5's) and gpu_ab.py are kept outside the repo.

🤖 Generated with Claude Code

… data (batch C)

Batch C of the AWQ lifecycle cleanup: the structural awq_get_modules_for_scaling
overrides that rebuilt or patched scaling nodes by hand now come from the fold
declarations (canonical_awq_folds plus awq_folds data), where that reproduces
the current plan exactly.

* phi4mm: the override's lora_A consumers and `_awq_allow_partial_replay` are
  `awq_folds` data. AWQFoldDeclaration gains `partial_replay` (the boundary
  replay may not execute every member; the adapters never run there), which
  _awq_nodes_from_declarations turns into the node flag. merge_by_source keeps
  a group's boundary when a merged fold adds only consumers, so the data fold
  of the same target keeps the derived `self_attn`/`mlp` replay boundary.
* intern_s2_preview: the hand-built DeltaNet node is deleted; the `:in=x` tags
  already derive input_layernorm -> in_proj_qkv, in_proj_z with in_proj_b/a
  compensated. A two-line filter keeps one corner: without an in_proj_qkv
  capture (a `dynamic` exclusion) the group is not planned, so in_proj_z
  quantizes plainly instead of joining a starved group (fallback routing).
  The override's past_key_values -> cache_params rename is dropped: the
  scale search re-adds the layer's past_key_values with setdefault, and
  awq_module_replay_inputs rejects any non-None cache under either name, so
  the DeltaNet replay only loses an explicit cache_params=None, its default
  (recorded on GPU; the checkpoints are bit-identical).
* minicpmv_4_6: the same DeltaNet builder becomes "DeltaNet layers plan from
  the declarations" with the same filter. Full-attention layers keep the tree
  tracker: their width-dropped v_proj -> o_proj group is one of the 66
  drop:width-only differences that can still route a starved member to
  fallback.
* solar_open2: leaves the tracker. `v_proj:nosrc` replaces the override's
  o_proj stripping (o_proj reads the gated output; tiny_mha would otherwise
  gain v_proj -> o_proj), and the dense-prefix mlp.up_proj -> down_proj group
  the override restored is a role-derived fold.

Kept, because the declarations change a reachable plan:
* ernie4_5_vl_moe: its declarations already equal the override's MoE group,
  but leaving the tracker drops the width-dropped v_proj -> o_proj group on
  every layer (one of the 66).
* nemotron_omni: the same drop:width group on attention layers, and the MoE
  group's `mixer` search-feature name (which lets the processor split a
  starved routed expert, #4675) has no declaration form.
* nemotron_h_puzzle: with routed experts unrouted on a non-latent layout the
  tracker plans a shared-expert group that falls back while the declarations
  skip the group (the MoE root is not captured); a `dynamic` exclusion of
  shared_experts.up_proj on latent layouts drops the fold the tracker still
  makes (the known shared-norm exclusion bug, preserved); and
  moe_latent_size == hidden_size would add the routed experts to the norm
  group.

The phi4mm and solar_open2 tiny_mha entries leave AWQ_FOLD_DIFFERENCES and
TRACKER_PLANNED. tests/module_tree/awq_fold_inventory.py --check reports no
change for all 210 types.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium marked this pull request as ready for review December 1, 2026 09:45
@Qubitium
Qubitium merged commit 29188ea into main Dec 1, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/awq-structural-folds-c branch December 1, 2026 09:46
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