Repository navigation
refactor(awq): share the planner's width predicates and feature-kwargs merge - #6476
Merged
Merged
Conversation
…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]>
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
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:nn.Parametergain width appeared 3 times: the_norm_widthclosure, inline in_is_gain_norm, and inawq_folds._norm_width.width-wide input" consumer test appeared 3 times: twice in_norm_scale_consumersand once, weight-only, in_moe_block_consumers._module_kwargs_for_featureclosure, next to the_awq_module_kwargs_for_featurestatic method that the declared-fold path already used.The width checks now live once in
gptqmodel/quantization/awq/fold_rules.py, next tosource_width. The planner uses the static kwargs merge. Behavior is unchanged: the fold inventory, a structural A/B of everyMODEL_MAPtype and GPU AWQ checkpoints all match origin/main exactly.There is no linked issue.
What Changed
fold_rules.pygains three small pure functions:gain_width(module): the length of a 1-Dnn.Parameterweight, elseNone.weight_reads(module, width): true when the module has a 2-Dnn.Parameterweight withwidthinput columns. This covers a router's[experts, hidden]weight.reads_width(module, width): the same asweight_reads, except that annn.Linearis judged byin_features.nn.Parameterweights.source_width(fold legality) keeps accepting any tensor and Linear rows; it is untouched.reads_width, because they judgednn.Linearbyin_features.weight_reads, because they were judged by weight columns only, even for annn.Linear.base.py:_norm_widthclosure, the 2-line inline gain check in_is_gain_norm, the 3 inline consumer-width blocks, and the_module_kwargs_for_featureclosure together with itsbase_module_kwargs/per_feature_kwargssetup.generate_node_for_awq_scalingcalls in the generic planner now useself._awq_module_kwargs_for_feature(module_kwargs, feature_name). That method was compacted with the same semantics.awq_folds._norm_widthis nowgain_width(module) if norm_type_of(module) is not None else None. The semantics are identical.Mappingspelling of fold declarations.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:_awq_feature_kwargsonly whenisinstance(module_kwargs, dict); otherwise it randict(module_kwargs), which raises onNone.NoneforNoneand{}for a non-Mapping.Every in-tree producer passes a dict whose
_awq_feature_kwargsis a dict of dicts:AWQProcessorbuildsmodule_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 aDict[str, Any]withdict(...).cohere_compassrebuilds the kwargs through_prepare_layer_forward_kwargs, which also returnsdict(...).awq_get_modules_for_scalingoverride passes the kwargs through unchanged.Noneor a non-dictMappingto the planner.888959022)base.py:7538_norm_widthclosurefold_rules.py:48gain_widthbase.py:7442-7451inline 1-Dnn.Parametercheck in_is_gain_normbase.py:7442gain_width(...)base.py:7575-7581and7591-7597:in_featuresor 2-Dnn.Parametercolumnsbase.py:7559,7570reads_width(...)(fold_rules.py:63)base.py:7663-76642-Dnn.Parametercolumns (MoE root children)base.py:7637weight_reads(...)(fold_rules.py:55)base.py:7378-7387and7668-7674_module_kwargs_for_featureclosurebase.py:7767,7982self._awq_module_kwargs_for_feature(module_kwargs, ...)(base.py:7228)awq_folds.py:159-165own 1-Dnn.Parametercheckawq_folds.py:160-163gain_widthTests
New tests in
tests/test_awq_scaling_groups.py:test_planner_width_predicates_keep_their_weight_type_checkspins each type check:Noneforgain_widthbut counted bysource_width;in_featuresdisagrees with its weight is judged byin_featuresinreads_widthand by its weight inweight_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_kwargsstripped.Environment: Python
/root/venv(torch 2.15.0+cu132, transformers 5.23.0, ruff 0.14.2). The clone is first onPYTHONPATHand runs withpython -P;gptqmodel.__file__was printed for each tree.E1: fold inventory
E2: structural A/B of the planner, every
MODEL_MAPtypeA 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 callsawq_get_modules_for_scalingtwice per layer:{};_awq_feature_kwargsentry for every feature, so the merge is exercised.For each node it records: every node key, the
prev_opname and an identity check (layer.get_submodule(name) is prev_op),layers,module2inspect, the full kwargs (keys and values),_scale_consumers,_input_feature_name, theinpshape and the search/span keys.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, andquant_log.csvrows (the wall-time column excluded).E4: CPU suites (
CUDA_VISIBLE_DEVICES="",-n 32), branch and origin/mainThe 80 test files are:
fold_rulesor the touched closures (found by grep);tests/module_tree/test_awq_fold_inventory.py;test_awq_fold_safety_4175,test_mimo_v2_local_port,test_awq_ling2_fold_4677,test_awq_glm5_next_neutrality,test_dots3_note_awq_relationships,test_dots3_note_fork_planandtest_deepseek_v4_local_port.Failures, all pre-existing on main:
tests/models/test_cohere_compass.py::test_cohere_compass_model_type_selects_definitionand::TestCohereCompass::test_cohere_compassfail on both trees.tests/test_awq_weight_mean.py::test_awq_pseudo_quantize_nan_guard_uses_one_host_readis 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 == 1scalar reads).E5: GPU-only AWQ nodes on GPU 3, both trees
These nodes are skipped on CPU.
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:1993needs a second visible GPU (cuda:1). This multi-GPU path is not re-run.test_awq_weight_mean.pyare 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_MAPentry, alias, definition, module tree or fusion declaration changes.tests/module_tree/test_registered_module_plans.pyandtest_definition_subset_ordering.pypass (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.pywithout 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:lineevidence. The existing_is_gain_normdiagrams indocs/awq-norm-selection.mdanddocs/moe-awq-calibration.mdstill describe the code.Review Requirements
I or an AI agent (such as Codex or Claude) have:
Kernel Accuracy Requirements
Notes
gain_widthis deliberately stricter thansource_width:nn.Parameteronly, 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.Mappingwould now get its per-feature kwargs applied, where it previously got them silently ignored.🤖 Generated with Claude Code