Repository navigation
refactor(models): one module-tree parser; answer flag/role queries from ModulePlan - #6398
Merged
Merged
Conversation
Qubitium
added a commit
that referenced
this pull request
Nov 29, 2026
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Qubitium
marked this pull request as ready for review
November 29, 2026 13:55
…om ModulePlan The module_tree token grammar was implemented four times: module_plan.py (_split_spec/_join/_iter_variants), byte-identical copies in shared_input.py, BaseQModel._parse_module_flags/_parse_module_aliases/_iter_module_tree_variants, and LazyTurtle._parse_module_spec/_iter_module_tree_variants. On top of that, base.py walked the tree again in _collect_norm_modules_from_tree, _collect_flagged_layer_modules, _collect_moe_modules_from_tree and get_moe_module_name, re-deriving sets ModulePlan already compiles. module_plan.py now owns the grammar (split_aliases, split_spec, join_path, iter_variants) and every consumer imports it. ModulePlan gains flagged(flag), which answers get_norm_modules, get_post_norm_modules and get_awq_no_scale_consumer_modules; get_moe_module_name returns ModulePlan.moe_roots(). The uncalled get_moe_modules, has_norm_flag and the awq_no_scale_consumer_modules(layer) wrapper are removed; the AWQ _norm_scale_consumers call site reads get_awq_no_scale_consumer_modules() directly. LazyTurtle keeps its list-only guard, so frozen tuple trees are still rejected there. A structural A/B over all 210 MODEL_MAP entries (class tree, every module_tree_overrides variant, every effective tree, every tree-shaped class attribute; list and frozen forms) shows identical, ordered outputs for every production query. A new registry-wide unit test pins the flag and MoE-root queries against an independent reference walk, including Nemotron-H's dotted mixer.experts:moe root. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Qubitium
force-pushed
the
refactor/one-module-tree-parser
branch
from
November 29, 2026 13:57
2eec7ed to
8505e4b
Compare
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
Behavior-preserving debloat. There were four hand-written parsers for the
module_treetoken grammar, and on top of thembase.pywalked the tree again to answer flag and MoE-root queries. All of those now go throughmodule_plan.pyand the compiledModulePlan.module_plan.pyowns the grammar:split_aliases(),split_spec(),join_path()anditer_variants(). These are the old_split_spec,_joinand_iter_variants, now public.split_aliasesis the shared alias split.shared_input.py,BaseQModelandLazyTurtleimport the grammar. Their copies are deleted.ModulePlan.flagged(flag)answersget_norm_modules(),get_post_norm_modules()andget_awq_no_scale_consumer_modules().get_moe_module_name()returnsModulePlan.moe_roots().get_moe_modules+_collect_moe_modules_from_tree,has_norm_flag, and theawq_no_scale_consumer_modules(layer)wrapper.git diff --shortstat origin/main: 11 files changed, 240 insertions(+), 316 deletions(-) (net -76) (package code alone: 4 files, +68/-272, net -204; tests and docs: 7 files, +172/-44, mostly the new registry-wide reference test and the docs section).No
Fixesline: this PR resolves no issue.What Changed
gptqmodel/models/module_plan.pysplit_aliases,split_spec,join_path,iter_variants). NewModulePlan.flagged().gptqmodel/models/shared_input.py_split_spec/_join/_iter_variantscopies and imports frommodule_plan.collect_leaf_specskeeps its own walk, which raises on conflicts.gptqmodel/models/base.py_parse_module_aliases,_parse_module_flags,_collect_moe_modules_from_tree,get_moe_modules,_collect_norm_modules_from_tree,_collect_flagged_layer_modules,awq_no_scale_consumer_modulesandhas_norm_flag._iter_module_tree_variantskeeps its class-default-tree behavior and delegates toiter_variants. Flag and MoE-root getters readModulePlan. Parser call sites usesplit_spec.gptqmodel/utils/structure.pyLazyTurtle._parse_module_spec/_iter_module_tree_variantsand usessplit_aliases/iter_variants. The existingisinstance(module_tree, list)guard at the top of_build_moe_alias_specsstill rejects frozen tuple trees.tests/…split_spec/split_aliases. Theget_moe_modulesasserts now checkModulePlan.is_moe/moe_roots. New registry-wide reference test (see Tests).docs/model-tree-resolution.mdNo API or behavior change for any registered definition (see the A/B below). The removed public-looking names (
get_moe_modules,has_norm_flag,awq_no_scale_consumer_modules) are undocumented and have no caller ingptqmodel/,scripts/or the definitions. Only tests used them.Correction to the debloat map's suggested formula. The map proposed
get_moe_module_name = [s.template for s in plan.moe_roots() if "." not in s.template]. The structural A/B showed that formula breaks Nemotron-H and Nemotron Omni. They declare the dotted top-level key"mixer.experts:moe", so the old code returned["mixer.experts"]and the map's formula returns[].MoELifecycle.get_moe_blockwould then log "No :moe flag found" and returnNone. The shipped code returns allmoe_roots(). That matches the old output, in order, for every registered tree.test_dotted_moe_root_key_is_reportedpins it.Out of scope, left as is:
awq_input_feature_aggregation(base.py) has(generator) or cls.get_moe_module_name() or []. A generator is always truthy, so the fallback never runs. It is AWQ-adjacent, so I left it for the AWQ lifecycle refactor._build_layer_modules_for_tree,is_moe_module,awq_post_norm_modules(OLMo Hybrid overrides it) andcollect_leaf_specs's conflict-raising walk stay as they are, per the map.Tests
New tests in
tests/module_tree/test_moe_flag_parsing.py:test_plan_flag_and_moe_queries_match_reference_walk[<model_type>](210 nodes): for everyMODEL_MAPentry and every effective tree (gptq + each override method), asserts thatget_norm_modules,get_post_norm_modules,get_awq_no_scale_consumer_modulesandget_moe_module_nameequal, in order, an independent in-test reference walk with the pre-refactor semantics.test_dotted_moe_root_key_is_reported: Nemotron-H returns["mixer.experts"].test_flagged_skips_expert_placeholders_and_folds_parent_repeat_leaves: synthetic tree covering#expert subtrees, a parent-repeat leaf and a:normdict key.test_split_aliases_keeps_checkpoint_aliases_in_order.Red evidence. With the map's
"." not in templatefilter put back, thenemotron_handnemotronh_nano_omni_reasoning_v3nodes andtest_dotted_moe_root_key_is_reportedfail at the assertion. With thenot spec.is_expert_placeholderfilter removed fromflagged(), the synthetic test fails.The map's CPU list plus the touched families, on this branch:
origin/main1615acc with the same assertion:test_registered_module_plans.py::test_registered_model_plan_matches_quantization_consumers[gemma4]and[gemma4_text]. The checked-inregistered_module_plans.jsonblocks for Gemma 4 no longer match the definition (['pre_feedforward_layernorm_2:!'] != ['router.proj:!']at block 11). The definition last changed in 840a916 (test(awq): cover fold-graph config features and fix Gemma KV/MoE folds #6329); the fixture did not. This PR does not touch it, and the A/B showsbuild_layer_modulesis identical old vs new.test_awq_scaling_groups.py:571:opt350,muse_glimmerare not buildable CausalLM families). They are skipped on main too and leave those two definitions' AWQ grouping unverified by that test. The structural A/B still covers their trees.Wider sweep. Every non-GPU-model test file that references a touched function was run on
origin/mainand on this branch, and the per-node outcomes were compared:87 test files:
tests/minustests/models/(GPU model tests). The set is every file that references a touched function (get_moe_module_name,get_norm_modules,get_post_norm_modules,get_awq_no_scale_consumer_modules,collect_leaf_specs,build_shared_input_plan,has_moe_flag,_iter_module_tree_variants,LazyTurtle, MoE lifecycle, norm handling, ...), plus the AWQ files the map lists. Both sides ran the same pytest invocation with--junitxmlandCUDA_VISIBLE_DEVICES="".test_shared_input.py::TestFlagParsingtested the deletedLazyTurtle._parse_module_specandBaseQModel._parse_module_flags. They are replaced bytest_module_tree_grammar_keeps_in_tag_as_plain_flag.test_registered_module_plans.py::...[gemma4]and[gemma4_text]: fixture drift, see above.module_tree/test_inkling2_loop_plan.py::test_inkling2_loop_public_loader_uses_local_code_and_checkpoint_keysandtest_awq_falcon_h1_parallel_branch_4741.py::test_awq_scales_the_parallel_branch_instead_of_falling_back: these tests' tiny tokenizers are now rejected by the tokenizer check from e8e7327 (fix(loader): reject tokenizer-less checkpoints and repair pad token (#6361) #6386) withValueError: The tokenizer ... is unusable.test_norm_review_regressions(105),test_qwen2_5_omni_lm_head(4),test_auto_module_decoder:1549(2),test_offload_files:979,2258(3),test_offload_quantized_modules_restored_4450(4). Their GPU branches are not verified by this sweep; the GPU A/B below covers the quantize path.mamba_ssm(test_jamba_support:303).Measured Impact
Not applicable: no claimed issue. This is a behavior-preserving refactor with no runtime cost change. The flag getters compile a
ModulePlanper call, asis_moe_modulealready did.Model Support / Module Plan
Not applicable as new model support: no definition, alias, path, tag or override changed. The registry contract (
test_registered_module_plans.py) was run; see the pre-existing Gemma 4 fixture drift above.Model test node IDs and results:
test_plan_flag_and_moe_queries_match_reference_walk[*]210/210 passed.test_registered_module_plans.py: 425 passed, 2 failed (gemma4,gemma4_text, same failures on main).AWQ onboarding safety
Not applicable as onboarding: no AWQ grouping, search, replay or fold logic changed. The only AWQ-adjacent edit is one call site.
_norm_scale_consumersnow readsself.get_awq_no_scale_consumer_modules()directly instead of through the removed one-lineawq_no_scale_consumer_modules(layer)wrapper. Neither name is in_MODULE_TREE_RUNTIME_METHODS, so tree resolution is unchanged. The A/B checks that call site on an instance with a frozen effective tree. A GPU AWQ quantize A/B is bit-identical (below).Structural A/B (core proof)
The script imports
origin/mainand this branch in separate processes, dumps JSON, then diffs in order. Two baselines were used: the pristineorigin/mainworktree at 1615acc (this branch's base) and the read-only debloat base at 390a032. Their dumps are byte-identical.Coverage:
MODEL_MAPentries._freeze_module_treetuple: 844 tree queries. The trees are:module_tree;module_tree_overrides[method]applied viaapply_module_tree_override;_resolve_effective_module_treeresult for gptq plus each override method;module_tree_two_norm.Per tree, 24 outputs are compared in order:
has_moe_flag.iter_variantscopy and_iter_module_tree_variants(explicit and class-default).get_norm_modules,get_post_norm_modules,get_awq_no_scale_consumer_modulesandget_moe_module_name, both class-level under_module_tree_contextand instance-bound._norm_scale_consumersno-scale call site.extract_layers_node, andis_moe_moduleon every declared path.build_layer_modules(with and without capture-only),build_shared_input_plan,collect_leaf_specs,collect_module_specsandModulePlan.to_dict.LazyTurtle._build_moe_alias_specsandgenerate_layers_modules_tree_simple.flagged_any: the old generic_collect_flagged_layer_modules(f)againstModulePlan.flagged(f)for every flag that appears in the tree.Coverage is not vacuous. The non-empty results are:
Result:
The 658 informational differences come only from
flagged_any, for flags that no production code asks_collect_flagged_layer_modulesabout. The old walker joined an empty""dict key (llama4feed_forward:moe→"", and similar) asmlp..gate_proj, whileModulePlanjoins it asmlp.gate_proj. No:norm,:postnormornoconsumerflag sits under an empty key in any definition, so production output is identical.ab_module_tree.py
GPU A/B
Run on one GPU (CUDA_DEVICE_ORDER=PCI_BUS_ID),
origin/main1615acc vs this branch. Both sides used the sameQuantizeConfig(bits=4, group_size=128)(GPTQ) orquant_method=METHOD.AWQ, format=FORMAT.GEMM(AWQ), seed 0, and the same 64 deterministic calibration strings. Every saved safetensors tensor was compared byte-for-byte, and every*.jsonfile was compared.Logic Flow Documentation
file:lineevidence.docs/repeats the diagrams, titled for the mechanism, and is linked fromREADME.md.The decision source for the flag and MoE-root queries moves from per-query tree walkers to the compiled
ModulePlan. The section is added todocs/model-tree-resolution.md, whichREADME.mdalready links.flowchart LR T["_module_tree_for_class(cls)<br/>class or instance-bound tree"] --> P["ModulePlan.from_tree()"] P --> F["plan.flagged(flag)<br/>declaration order<br/>no '#' expert paths"] P --> R["plan.moe_roots()"] F --> N["get_norm_modules()<br/>:norm"] F --> PN["get_post_norm_modules()<br/>:postnorm"] F --> NC["get_awq_no_scale_consumer_modules()<br/>noconsumer"] R --> MN["get_moe_module_name()<br/>incl. dotted keys such as mixer.experts"] NONE["tree is None"] --> NN["get_moe_module_name() returns None<br/>flag getters return empty list"] style P fill:#d9f7be,stroke:#237804,stroke-width:2px style NONE fill:#ffa39e,stroke:#a8071amodule_plan.py:57_split_spec,shared_input.py:65_split_spec(copy),base.py:2219,2234_parse_module_aliases/_parse_module_flags,structure.py:2625_parse_module_specmodule_plan.py:59,70split_aliases/split_specmodule_plan.py:64,shared_input.py:74module_plan.py:76join_pathmodule_plan.py:70,shared_input.py:149,base.py:2187,structure.py:2651module_plan.py:82iter_variants(base.pykeeps the class-default wrapper_iter_module_tree_variants):norm/:postnorm/noconsumerbase.py:2413-2462_collect_norm_modules_from_tree+_collect_flagged_layer_modulesmodule_plan.py:476ModulePlan.flagged;base.py:2292,2303,2327base.py:2373-2410first-layer-dict key scanbase.py:2273ModulePlan.moe_roots()base.py:8196self.awq_no_scale_consumer_modules(module)→ wrapperbase.py:2511base.py:8010self.get_awq_no_scale_consumer_modules()base.py:2274,2322_collect_moe_modules_from_tree/get_moe_modules,base.py:2517has_norm_flagThere are no new failure paths. A
Nonetree still givesNonefromget_moe_module_nameand[]from the flag getters.Review Requirements
Kernel Accuracy Requirements
Notes
BaseQModel.get_awq_no_scale_consumer_modules()(classmethod,List[str]) has the same signature and output as before. It is now the only accessor.awq_no_scale_consumer_modules(self, layer)is removed, and_norm_scale_consumerscalls the classmethod directly.get_post_norm_modules()andawq_post_norm_modules(layer)keep their signatures. OLMo Hybrid still overrides the latter.:moekeys. A:moeflag on a nested key or on a parent-repeat leaf is now reported byget_moe_module_nametoo.test_registered_module_plansalready assertsset(get_moe_module_name()) == {s.template for s in plan.moe_roots()}for every definition.""keys. They join without a doubled dot.|characters,LazyTurtleused to take the whole raw token as the alias; it now takes the name segment, like the other parsers. No such token exists.🤖 Generated with Claude Code