Skip to content

refactor(awq): share the planner's width predicates and feature-kwargs merge - #6476

Merged
Qubitium merged 1 commit into
mainfrom
refactor/awq-shared-planner-predicates
Nov 30, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/awq-shared-planner-predicates

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

The generic AWQ planner (BaseQModel._awq_generic_get_modules_for_scaling) carried private copies of checks that exist once elsewhere or are repeated inside it:

  • The 1-D nn.Parameter gain width appeared 3 times: the _norm_width closure, inline in _is_gain_norm, and in awq_folds._norm_width.
  • The "reads a width-wide input" consumer test appeared 3 times: twice in _norm_scale_consumers and once, weight-only, in _moe_block_consumers.
  • The per-feature kwargs merge appeared twice: the _module_kwargs_for_feature closure, next to the _awq_module_kwargs_for_feature static method that the declared-fold path already used.

The width checks now live once in gptqmodel/quantization/awq/fold_rules.py, next to source_width. The planner uses the static kwargs merge. Behavior is unchanged: the fold inventory, a structural A/B of every MODEL_MAP type and GPU AWQ checkpoints all match origin/main exactly.

There is no linked issue.

What Changed

  • fold_rules.py gains three small pure functions:
    • gain_width(module): the length of a 1-D nn.Parameter weight, else None.
    • weight_reads(module, width): true when the module has a 2-D nn.Parameter weight with width input columns. This covers a router's [experts, hidden] weight.
    • reads_width(module, width): the same as weight_reads, except that an nn.Linear is judged by in_features.
  • Each call site keeps its exact old check:
    • The planner keeps accepting only nn.Parameter weights. source_width (fold legality) keeps accepting any tensor and Linear rows; it is untouched.
    • The consumers of a norm run use reads_width, because they judged nn.Linear by in_features.
    • The children of a MoE root use weight_reads, because they were judged by weight columns only, even for an nn.Linear.
  • base.py:
    • Deleted: the _norm_width closure, the 2-line inline gain check in _is_gain_norm, the 3 inline consumer-width blocks, and the _module_kwargs_for_feature closure together with its base_module_kwargs/per_feature_kwargs setup.
    • The two generate_node_for_awq_scaling calls in the generic planner now use self._awq_module_kwargs_for_feature(module_kwargs, feature_name). That method was compacted with the same semantics.
  • awq_folds._norm_width is now gain_width(module) if norm_type_of(module) is not None else None. The semantics are identical.
  • No API, numerics or checkpoint change. No definition is touched.
  • Out of scope, left alone:
    • The optional trim of the Mapping spelling of fold declarations.
    • The per-definition kwargs merges in definitions/{qwen,lfm3_vl,solar_open2,minicpmv_4_6}.py.

git diff --shortstat origin/main: 4 files changed, 99 insertions(+), 70 deletions(-). Production code (gptqmodel/) is 53 insertions and 69 deletions (net -16). The new tests are 46 insertions and 1 deletion.

kwargs merge: why the closure and the method are interchangeable here

The two merges differ only for inputs that are not a dict:

  • The closure stripped _awq_feature_kwargs only when isinstance(module_kwargs, dict); otherwise it ran dict(module_kwargs), which raises on None.
  • The method returns None for None and {} for a non-Mapping.

Every in-tree producer passes a dict whose _awq_feature_kwargs is a dict of dicts:

  • AWQProcessor builds module_kwargs_global = dict(self._module_forward_kwargs) plus ["_awq_feature_kwargs"] = dict(...) (gptqmodel/looper/awq_processor.py:4633-4636). The per-feature values come from _feature_kwargs_from_batch_indices, which builds a Dict[str, Any] with dict(...).
  • cohere_compass rebuilds the kwargs through _prepare_layer_forward_kwargs, which also returns dict(...).
  • Every other awq_get_modules_for_scaling override passes the kwargs through unchanged.
  • No test passes None or a non-dict Mapping to the planner.
Old (origin/main 888959022) New (this branch)
base.py:7538 _norm_width closure fold_rules.py:48 gain_width
base.py:7442-7451 inline 1-D nn.Parameter check in _is_gain_norm base.py:7442 gain_width(...)
base.py:7575-7581 and 7591-7597: in_features or 2-D nn.Parameter columns base.py:7559, 7570 reads_width(...) (fold_rules.py:63)
base.py:7663-7664 2-D nn.Parameter columns (MoE root children) base.py:7637 weight_reads(...) (fold_rules.py:55)
base.py:7378-7387 and 7668-7674 _module_kwargs_for_feature closure base.py:7767, 7982 self._awq_module_kwargs_for_feature(module_kwargs, ...) (base.py:7228)
awq_folds.py:159-165 own 1-D nn.Parameter check awq_folds.py:160-163 gain_width

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 in tests/test_awq_scaling_groups.py:

  • test_planner_width_predicates_keep_their_weight_type_checks pins each type check:
    • a plain-tensor gain is None for gain_width but counted by source_width;
    • a Linear has no gain width;
    • a plain-tensor router weight is not a reader;
    • a Linear whose in_features disagrees with its weight is judged by in_features in reads_width and by its weight in weight_reads.
  • test_planner_node_kwargs_merge_their_feature_kwargs[llama|qwen2_moe]: every generic-planner node's kwargs are the layer kwargs updated with that node's feature kwargs, with _awq_feature_kwargs stripped.

Environment: Python /root/venv (torch 2.15.0+cu132, transformers 5.23.0, ruff 0.14.2). The clone is first on PYTHONPATH and runs with python -P; gptqmodel.__file__ was printed for each tree.

E1: fold inventory

HF_HUB_OFFLINE=1 PYTHONPATH=$PWD python -P tests/module_tree/awq_fold_inventory.py --check --workers 48
# 210 types, changed: none   (the 18 `default` variant build errors are recorded in the committed fixture, same as main)

E2: structural A/B of the planner, every MODEL_MAP type

A script builds every type on meta with the inventory's builders (build_wrapper, synthesize_features): every config variant and every decoder layer. It runs in one process per type and once per tree (origin/main worktree, then this branch). It calls awq_get_modules_for_scaling twice per layer:

  • with {};
  • with a dict carrying layer kwargs and a distinct _awq_feature_kwargs entry for every feature, so the merge is exercised.

For each node it records: every node key, the prev_op name and an identity check (layer.get_submodule(name) is prev_op), layers, module2inspect, the full kwargs (keys and values), _scale_consumers, _input_feature_name, the inp shape and the search/span keys.

python -P planner_ab.py <origin/main worktree> ab_base.json; python -P planner_ab.py <branch> ab_new.json; cmp ab_base.json ab_new.json
types=210 variants=268 layers=8380 nodes=1042142 (all with kwargs, 6708 with consumers, prev_op identity checked on every node)
planner raises recorded: 240 layer calls (same on both); variants that do not build on meta: 18 (the inventory's `default` errors, same on both)
RESULT: 0 differences  (the two JSON outputs are byte-identical)

E3: GPU AWQ A/B, GPU 3 (NVIDIA RTX 4090, CUDA_DEVICE_ORDER=PCI_BUS_ID)

Setup: AWQConfig(bits=4, group_size=128), bf16, seed 0, the first 64 wikitext-2 rows longer than 200 characters, batch_size=4. Each tree quantized the same model, then the outputs were compared: every saved safetensors tensor bytewise, every JSON file, and quant_log.csv rows (the wall-time column excluded).

Model Tensors Result Peak CUDA MiB base / branch
Qwen/Qwen2.5-0.5B-Instruct 626 bit-identical 387 / 387
FlameF0X/TinyMoE-100m-2x8-retrained (Mixtral, 8 experts) 873 bit-identical 313 / 313

E4: CPU suites (CUDA_VISIBLE_DEVICES="", -n 32), branch and origin/main

The 80 test files are:

PYTHONPATH=$PWD python -P -m pytest -q -p no:cacheprovider -n 32 -rs $(cat test_files.txt)
# branch:      2 failed, 2809 passed, 31 skipped
# origin/main: 2 failed, 2806 passed, 31 skipped   (branch = main + the 3 new test nodes)

Failures, all pre-existing on main:

  • tests/models/test_cohere_compass.py::test_cohere_compass_model_type_selects_definition and ::TestCohereCompass::test_cohere_compass fail on both trees.
  • tests/test_awq_weight_mean.py::test_awq_pseudo_quantize_nan_guard_uses_one_host_read is flaky on CPU. It passed in the final runs of both trees, failed in an earlier branch run, and failed 3 out of 3 standalone runs on both trees (assert 4 == 1 scalar reads).

E5: GPU-only AWQ nodes on GPU 3, both trees

These nodes are skipped on CPU.

PYTHONPATH=$PWD python -P -m pytest -q -p no:cacheprovider -rs tests/test_awq_weight_mean.py tests/test_awq_variable_length_ppl.py tests/test_awq_per_module_bits.py tests/test_awq_hybrid_recurrent_mask_4671.py
# branch:      2 failed, 223 passed, 1 skipped
# origin/main: 2 failed, 223 passed, 1 skipped
# Both trees: test_awq_variable_length_ppl.py::test_awq_beats_rtn_with_variable_length_calibration (known on main)
#             test_awq_hybrid_recurrent_mask_4671.py::test_awq_batch_size_one_quantizes_a_mamba_hybrid
#               (its tmp tokenizer fixture is rejected as unusable before quantization; it failed on main in both runs
#                and passed once on the branch before the rebase, so it is a flaky fixture, not this change)

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

Skips and what they leave unverified:

  • test_awq_scaling_groups.py:578: opt350 and muse_glimmer are not buildable CausalLM families. Their definitions are covered by E1 and E2.
  • test_ricursive_local_port.py:170 (x2): a Transformers 5.23 sliding-window limitation, unrelated to the planner.
  • test_awq_weight_mean.py:1993 needs a second visible GPU (cuda:1). This multi-GPU path is not re-run.
  • The CPU-only CUDA skips in test_awq_weight_mean.py are covered by E5.

Measured Impact

Not applicable: there is no claimed issue and the refactor is behavior-preserving. E3 shows identical checkpoints and equal peak memory.

Model Support / Module Plan

Not applicable: no MODEL_MAP entry, alias, definition, module tree or fusion declaration changes. tests/module_tree/test_registered_module_plans.py and test_definition_subset_ordering.py pass (E4).

AWQ onboarding safety

AWQ evidence and per-variant policy: not applicable for qualification. No grouping, search, replay or fold rule changes; this moves existing predicates into fold_rules.py without changing any outcome. E1 (per-type effective fold plan with outcomes) and E2 (full planner node lists, kwargs and consumers for every config variant) prove that every variant keeps exactly its current groups. The onboarding CPU baseline is part of E4.

Logic Flow Documentation

Not applicable: control flow, selection order and outcomes are unchanged. Per-call-site predicates are replaced by the same predicates in one module; the old-vs-new table above gives file:line evidence. The existing _is_gain_norm diagrams in docs/awq-norm-selection.md and docs/moe-awq-calibration.md still describe the code.

Review Requirements

I or an AI agent (such as Codex or Claude) have:

  • 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, packing or dispatch code changes. E3 shows bit-identical AWQ checkpoints.

Notes

  • gain_width is deliberately stricter than source_width: nn.Parameter only, and no Linear rows. Unifying the two would change which plain-tensor or Linear sources the planner treats as norms, so they stay separate. The new unit test pins the difference.
  • Reviewers: the kwargs-merge equivalence rests on the dict-only producer contract described above. A future caller that passes a non-dict Mapping would now get its per-feature kwargs applied, where it previously got them silently ignored.

🤖 Generated with Claude Code

…s merge

The generic AWQ planner (`BaseQModel._awq_generic_get_modules_for_scaling`)
carried its own copies of three checks:

- the 1-D `nn.Parameter` gain width, written as the `_norm_width` closure and
  again inline in `_is_gain_norm`;
- the "reads a width-wide input" consumer test (`nn.Linear.in_features`, or a
  2-D `nn.Parameter`'s columns for a router), written twice in
  `_norm_scale_consumers` and once (weight-only) in `_moe_block_consumers`;
- the per-feature kwargs merge, written as the `_module_kwargs_for_feature`
  closure next to the existing `_awq_module_kwargs_for_feature` static method
  that the declared-fold path already uses.

The width checks now live once in `quantization/awq/fold_rules.py`, next to
`source_width`: `gain_width`, `weight_reads` and `reads_width`. Each call site
keeps its exact check: the planner accepts only `nn.Parameter` weights (while
`source_width` keeps accepting any tensor), the norm-run consumers judge an
`nn.Linear` by `in_features`, and the MoE-root children are judged by their
weight columns only. The role-derived `awq_folds._norm_width` reuses
`gain_width` too. The closure merge is replaced by the static method. They
agree for every dict input, and `AWQProcessor` always passes a dict whose
`_awq_feature_kwargs` is a dict of dicts (cohere_compass rebuilds it as one).

Behavior-preserving: the fold inventory, a structural A/B of every MODEL_MAP
config variant's planner nodes (prev_op identity, layers, module2inspect,
kwargs, consumers) and GPU AWQ checkpoints of Qwen2.5-0.5B-Instruct and a
Mixtral MoE are identical to origin/main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium marked this pull request as ready for review November 30, 2026 03:38
@Qubitium
Qubitium merged commit 59e921a into main Nov 30, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/awq-shared-planner-predicates branch November 30, 2026 03:38
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