Skip to content

refactor(models): declare non-canonical AWQ folds as data - #6470

Merged
Qubitium merged 1 commit into
mainfrom
refactor/awq-declared-fold-data
Nov 30, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/awq-declared-fold-data

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

This is step 4a of the AWQ lifecycle cleanup. Eight definitions fold a projection that the role-derived default (canonical_awq_folds, #6446) cannot name. This PR declares those folds as plain class data, awq_folds = (AWQFoldDeclaration(...),), placed next to each definition's module_tree:

  • output projections with no o role: out_proj, dense;
  • MLPs whose linear branch has no up role: OPT fc1 -> fc2, ExaOne c_fc_1 -> c_proj, Qwen-1 w1 -> c_proj;
  • the Granite-4 hybrid Mamba gated norm -> out_proj, where the norm is declared after its consumer.

There are no per-model functions, no new types and no registry. The data reuses the existing AWQFoldDeclaration.

Data only. No production path reads awq_folds yet:

The inventory test now compares what each definition declares against the effective plan. Ten AWQ_FOLD_DIFFERENCES entries are removed.

Net diff: 12 files changed, 144 insertions(+), 51 deletions(-) (+93). This step adds data, so the "net lines go down" rule does not apply.

What Changed

  • BaseQModel.awq_folds: Tuple[AWQFoldDeclaration, ...] = () (models/base.py:1709). It sits next to the other AWQ class attributes, away from the planner and from the calibration_device_modules block.

  • Data in 8 definitions:

    Definition awq_folds
    exaone.py:38 attn.attention.v_proj -> attn.attention.out_proj, mlp.c_fc_1 -> mlp.c_proj
    gpt_neo.py:37 attn.attention.v_proj -> attn.attention.out_proj
    gptj.py:37 attn.v_proj -> attn.out_proj
    opt.py:63 self_attn.v_proj -> self_attn.out_proj, fc1 -> fc2
    phi.py:37 self_attn.v_proj -> self_attn.dense
    lfm2_moe.py:115 self_attn.v_proj -> self_attn.out_proj (an o role would also hit the conv out_proj)
    qwen.py:123 mlp.w1 -> mlp.c_proj
    granitemoehybrid.py:76 mamba.norm -> mamba.out_proj
  • gptqmodel/models/awq_folds.py (not a production path):

    • canonical_awq_folds(..., declared=()) adds declared folds to the derived ones:
      • a declared fold applies only to layers that own its source (LFM2 conv layers and Granite attention layers have none);
      • it is emitted after the block holding its first target, then merged by source;
      • an unresolved target or consumer raises ValueError, and so does a fold whose first target is in no quantized block.
    • The replay-boundary rule moves from inline code into _default_boundary. merge_by_source applies it to every fold that has no boundary, so declared data does not need to repeat boundaries.
  • tests/module_tree/test_awq_fold_inventory.py:

    • test_canonical_folds_match_inventory compares awq_fold_declarations(layer) when a definition overrides it (PanGu, Inkling2-Loop), otherwise canonical_awq_folds(..., declared=awq_folds). This is the chain a declaration-driven planner (step 4b) would consume.
    • The same test asserts that every awq_folds source resolves on some decoder layer, so a misspelled source cannot silently apply nowhere.
    • New test_awq_folds_resolve_strictly covers the apply/skip/raise rules on the real LFM2-MoE parity model (attention layer plus conv layer).
    • Removed entries: exaone, gpt_neo, gptj, gpt_pangu, opt, phi, lfm2_moe/parity, qwen, granitemoehybrid and inkling2_loop.
    • phi4mm stays listed, with a precise reason (see Notes).
  • docs/awq-scaling-groups.md: one short paragraph on awq_folds.

  • Out of scope:

    • Consuming the data (4b) and deleting the qwen.py override (PR 5).
    • Config- and layer-variant overrides (chatglm/hymba boundary re-anchors, post-LN, llama alias families, rw, nanbeige, ricursive, lfm3, nemotron_h, k2_horizon, gemma4, raon1_mini, decilm order): these are PR 6/7 variant methods.
    • tracker-gap and canonical-unsafe entries: declaring them would freeze today's gaps as data, or they need nosrc first.

Why "canonical plus data" rather than "data replaces canonical"

The map sketched awq_folds or canonical, where data replaces the whole derivation. I implemented canonical + awq_folds for three reasons:

  • Hybrid definitions would need folds for unverified layouts. With full replacement, lfm2_moe would have to restate every derived fold of its attention, conv, dense and MoE layers. granitemoehybrid would have to restate its attention layers, which the inventory does not build (its default config is all-Mamba), so that data would be unverified.
  • Each gap costs one line. With additions, the gap is the only thing declared.
  • The PR 6 pattern still works. Variants that need to remove a fold stay awq_fold_declarations(layer) methods filtering super(), and PanGu and Inkling2-Loop already use that hook.

The data shape is the same tuple of AWQFoldDeclaration in both designs, so 4b can choose either.

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.

Environment: Python 3.14, torch 2.15.0+cu132, transformers 5.23.0, CPU only (CUDA_VISIBLE_DEVICES=, HF_HUB_OFFLINE=1). gptqmodel.__file__ was printed from the clone under test. Head is rebased on origin/main 2863a6b, which already contains #6460 and #6464.

# E1 inventory pin: the production planner's effective plan is unchanged
HF_HUB_OFFLINE=1 python -P tests/module_tree/awq_fold_inventory.py --check
# changed: none   (210 types)

# inventory + declared-data tests
python -P -m pytest -q -n 32 tests/module_tree/test_awq_fold_inventory.py
# 502 passed
# red check: with the 8 definition files reverted, test_canonical_folds_match_inventory fails for exactly
# exaone, gpt_neo, gptj, granitemoehybrid, lfm2_moe/parity, opt, phi, qwen (8 failed, 242 passed)

# AWQ onboarding baseline + fold/group tests
python -P -m pytest -q -n 32 tests/module_tree/test_awq_fold_inventory.py tests/test_awq_scale_search_safety.py \
  tests/test_awq_moe_router_scaling.py tests/test_awq_empty_groups.py tests/test_awq_position_kwargs.py \
  tests/test_awq_scale_search_memory.py tests/test_bloom_awq_replay.py tests/module_tree/test_awq_relationships.py \
  tests/module_tree/test_bloom_awq_relationships.py tests/module_tree/test_registered_module_plans.py \
  tests/module_tree/test_definition_subset_ordering.py tests/module_tree/test_awq_fold_declarations.py \
  tests/test_awq_scaling_groups.py tests/module_tree/test_awq_fold_safety_4175.py
# 1294 passed, 2 skipped (test_awq_scaling_groups.py:571 opt350 / muse_glimmer "not exercised as a buildable CausalLM family")

# touched-definition tests
python -P -m pytest -q -n 16 tests/test_lfm2_moe_expert_key_names_6283.py tests/test_granitemoehybrid_monkeypatch.py \
  tests/test_granitemoe_support.py tests/test_exaone_local_port.py tests/module_tree/test_exaone_local_port.py \
  tests/test_qwen_local_port.py tests/module_tree/test_qwen_local_port.py tests/test_awq_gpt_neo_packed_replay_5085.py \
  tests/module_tree/test_granitemoehybrid_model_tree.py tests/test_definition_module_paths.py \
  tests/module_tree/test_moe_tags.py tests/test_awq_replay_packed_batch_kwargs.py \
  tests/test_positional_mask_capture_4660.py tests/test_model_port_policy.py
# 285 passed, 1 skipped (test_lfm2_moe_expert_key_names_6283.py:299: vLLM not installed)

# tests/run_awq_cpu.sh unit selection (run via python -P -m pytest -n 32; the script's --timeout flag needs pytest-timeout)
# 1377 passed, 104 skipped (CUDA/accelerator-only or uncached tokenizer), 2 failed; both fail identically on origin/main:
#   tests/test_docs_contract_refs.py::test_doc_python_example_runs[docs/measurement.md::3]  NameError: name 'texts' is not defined
#   tests/test_awq_weight_mean.py::test_awq_pseudo_quantize_nan_guard_uses_one_host_read   assert 4 == 1

bash format/check.sh   # ruff 0.14.2: All checks passed!

Structural A/B of the derivation (CPU, meta). For every inventory case and layer variant, the script dumps canonical_awq_folds(plan, layer, blocks, gqa_shape_gate=...) with no data, as (source, targets, consumers, boundary, span_roots). It ran once on an origin/main worktree and once on this branch:

run_dump.sh <origin/main worktree> canonical_base.json    # 345 layer variants
run_dump.sh <branch>               canonical_branch.json  # 345 layer variants
cmp canonical_base.json canonical_branch.json             # identical

This shows that moving the boundary rule into _default_boundary/merge_by_source changes no derived fold.

GPU A/B: not applicable. No quantize, pack, save or load path is touched, and the production planner's effective plan is pinned unchanged by E1.

Measured Impact

Not applicable: no runtime path changes.

Model Support / Module Plan

Not applicable to the registry: no MODEL_MAP entry, tree, tag, alias or fusion change. The 8 touched definitions gain one class attribute. test_registered_module_plans.py and test_definition_subset_ordering.py pass (above).

AWQ onboarding safety

Per-variant policy is unchanged. Every declared fold is one the current planner already searches and folds (inventory status ok). The data restates it; nothing new is admitted. Forward evidence for each relationship, from the vendored ports:

  • v -> out_proj/dense: softmax attention output is linear in V (gpt_neo modeling_gpt_neo.py:151/163, gptj modeling_gptj.py:191/229, phi modeling_phi.py:236, lfm2_moe modeling_lfm2_moe.py:321/344).
  • ExaOne c_proj(act(c_fc_0(x)) * c_fc_1(x)), modeling_exaone.py:214.
  • Qwen-1 c_proj(w1(x) * silu(w2(x))), modeling_qwen.py:165.
  • OPT fc2(act(fc1(x))), where act is ReLU in every released OPT config (configuration_opt.py:67), so the fold is exact for positive scales.
  • Granite out_proj(norm(scan_output, gate)) with a gated RMSNorm gain, modeling_granitemoehybrid.py:719-722.

Unverified layouts are the same as on origin/main, because the inventory does not build them:

  • the OPT-350m post-norm tree;
  • Granite-4 attention layers.

Both are left to the derivation unchanged: the declared fold's source is absent there, or the data is identical across layouts.

Logic Flow Documentation

  • This change does not alter a major logic flow. No production decision path changes. The comparison chain the test pins (and step 4b will consume) is:
flowchart TD
    A["awq_fold_declarations(layer)"] --> B{"overridden<br/>(not None)?"}
    B -- "yes (PanGu, Inkling2-Loop)" --> M["merge_by_source<br/>default boundary"]
    B -- "no" --> C["canonical_awq_folds(plan, layer, blocks,<br/>declared=awq_folds)"]
    C --> D{"declared source<br/>on this layer?"}
    D -- "no" --> S["skip that fold"]
    D -- "yes" --> E{"targets resolve and first<br/>target in a quantized block?"}
    E -- "no" --> X["ValueError"]
    E -- "yes" --> F["emit after that block"]
    F --> M
    S --> M
    M --> T["test: equals inventory 'ok' groups<br/>unless listed in AWQ_FOLD_DIFFERENCES"]
    style X fill:#fdd,stroke:#c00
Loading

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, dispatch or packing change.

Notes

  • phi4mm stays in AWQ_FOLD_DIFFERENCES. Its lora_A adapter consumers could be declared as data. But phi4.py:67 also sets _awq_allow_partial_replay (the adapters never run in replay), and AWQFoldDeclaration has no field for it. The inventory does not record that flag either, so step 4b's E1 gate would not notice if it were lost. Recording it in the inventory belongs in a later step.
  • qwen.py's awq_get_modules_for_scaling override still produces the production w1 -> c_proj group. The data now states the same fold and pins it; PR 5 deletes the override.
  • The two run_awq_cpu.sh unit failures above reproduce on origin/main and are unrelated to this change.

🤖 Generated with Claude Code

Eight definitions fold a projection the role-derived default
(`canonical_awq_folds`) cannot name: an output projection without an o role
(`out_proj`, `dense`), an MLP whose linear branch has no up role (OPT
`fc1 -> fc2`, ExaOne `c_fc_1 -> c_proj`, Qwen-1 `w1 -> c_proj`), and the
Granite-4 hybrid Mamba gated `norm -> out_proj`, declared after its consumer.
Declare each one as `awq_folds = (AWQFoldDeclaration(...),)` class data next
to the module tree. `BaseQModel.awq_folds` defaults to `()`.

`canonical_awq_folds(..., declared=awq_folds)` adds the declared folds to the
derived ones. A fold applies to the layers that own its source (the LFM2 conv
layers and Granite attention layers have none), it is emitted after the block
that holds its first target, and it is merged by source. Unresolved targets
and unplaceable folds raise. The boundary rule moves into
`_default_boundary`, which `merge_by_source` applies to any fold without a
boundary. The canonical output is unchanged for all 345 inventoried layer
variants.

The inventory test now compares what a definition declares:
`awq_fold_declarations(layer)` when overridden (PanGu, Inkling2-Loop),
otherwise canonical plus `awq_folds`. Ten AWQ_FOLD_DIFFERENCES entries are
removed: exaone, gpt_neo, gptj, gpt_pangu, opt, phi, lfm2_moe, qwen,
granitemoehybrid and inkling2_loop. phi4mm stays listed with a precise
reason: its override also sets `_awq_allow_partial_replay`, which a
declaration cannot express.

Nothing in production reads `awq_folds` yet. The AWQ planner and the
inventory fixture are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium marked this pull request as ready for review November 30, 2026 02:59
@Qubitium
Qubitium merged commit 5b98d55 into main Nov 30, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/awq-declared-fold-data branch November 30, 2026 02:59
Qubitium added a commit that referenced this pull request Nov 30, 2026
…d teardown

Rebased fix/6148-issue onto origin/main 94ceaf7 (after #6464, #6465,
#6467, #6469, #6470). Three conflicts:
- gptqmodel/looper/forward_executor.py: import block. Main dropped the
  unused resolve_calibration_keep_mask import; kept only the PR's
  replay_records import.
- gptqmodel/looper/module_looper.py: #6465 moved the failed-run teardown
  into InflightLayerTracker (inflight_layer.py). Kept main's structure and
  re-applied the PR's release_looped_capture() as a ModuleLooper override
  of _release_failed_run_processors that calls super() first.
- gptqmodel/models/definitions/inkling2_loop.py: #6464 reduced
  pre_quantize_generate_hook_start to the batch-index/bank reset plus
  super(); the PR removes that reset, so the override is deleted.

Earlier rebase (onto 81ac176):
Rebased fix/6148-issue onto origin/main 81ac176. Two conflicts:
- gptqmodel/models/definitions/inkling2_loop.py: import block. Kept the
  PR's replay_records imports; dropped the PR's get_op_name import
  because main removed its last use and the rebased file does not use it.
- tests/module_tree/test_inkling2_loop_plan.py: main added the AWQ
  declaration block where the PR deletes _capture_inkling2_forward.
  Kept all of main's AWQ tests, removed only the helper the PR replaced
  with record-owned head banks.

Tests: 135 passed, 1 skipped on CPU (main baseline for the pre-existing
files: 124 passed).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Qubitium added a commit that referenced this pull request Dec 1, 2026
…d teardown

Rebased fix/6148-issue onto origin/main 94ceaf7 (after #6464, #6465,
#6467, #6469, #6470). Three conflicts:
- gptqmodel/looper/forward_executor.py: import block. Main dropped the
  unused resolve_calibration_keep_mask import; kept only the PR's
  replay_records import.
- gptqmodel/looper/module_looper.py: #6465 moved the failed-run teardown
  into InflightLayerTracker (inflight_layer.py). Kept main's structure and
  re-applied the PR's release_looped_capture() as a ModuleLooper override
  of _release_failed_run_processors that calls super() first.
- gptqmodel/models/definitions/inkling2_loop.py: #6464 reduced
  pre_quantize_generate_hook_start to the batch-index/bank reset plus
  super(); the PR removes that reset, so the override is deleted.

Earlier rebase (onto 81ac176):
Rebased fix/6148-issue onto origin/main 81ac176. Two conflicts:
- gptqmodel/models/definitions/inkling2_loop.py: import block. Kept the
  PR's replay_records imports; dropped the PR's get_op_name import
  because main removed its last use and the rebased file does not use it.
- tests/module_tree/test_inkling2_loop_plan.py: main added the AWQ
  declaration block where the PR deletes _capture_inkling2_forward.
  Kept all of main's AWQ tests, removed only the helper the PR replaced
  with record-owned head banks.

Tests: 135 passed, 1 skipped on CPU (main baseline for the pre-existing
files: 124 passed).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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