Skip to content

refactor(models): one module-tree parser; answer flag/role queries from ModulePlan - #6398

Merged
Qubitium merged 2 commits into
mainfrom
refactor/one-module-tree-parser
Nov 29, 2026
Merged

Qubitium merged 2 commits into
mainfrom
refactor/one-module-tree-parser

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Behavior-preserving debloat. There were four hand-written parsers for the module_tree token grammar, and on top of them base.py walked the tree again to answer flag and MoE-root queries. All of those now go through module_plan.py and the compiled ModulePlan.

  • module_plan.py owns the grammar: split_aliases(), split_spec(), join_path() and iter_variants(). These are the old _split_spec, _join and _iter_variants, now public. split_aliases is the shared alias split.
  • shared_input.py, BaseQModel and LazyTurtle import the grammar. Their copies are deleted.
  • ModulePlan.flagged(flag) answers get_norm_modules(), get_post_norm_modules() and get_awq_no_scale_consumer_modules(). get_moe_module_name() returns ModulePlan.moe_roots().
  • Removed code with no production caller: get_moe_modules + _collect_moe_modules_from_tree, has_norm_flag, and the awq_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 Fixes line: this PR resolves no issue.

What Changed

File Change
gptqmodel/models/module_plan.py Grammar made public (split_aliases, split_spec, join_path, iter_variants). New ModulePlan.flagged().
gptqmodel/models/shared_input.py Deleted the byte-identical _split_spec/_join/_iter_variants copies and imports from module_plan. collect_leaf_specs keeps its own walk, which raises on conflicts.
gptqmodel/models/base.py Deleted _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_modules and has_norm_flag. _iter_module_tree_variants keeps its class-default-tree behavior and delegates to iter_variants. Flag and MoE-root getters read ModulePlan. Parser call sites use split_spec.
gptqmodel/utils/structure.py Deleted LazyTurtle._parse_module_spec/_iter_module_tree_variants and uses split_aliases/iter_variants. The existing isinstance(module_tree, list) guard at the top of _build_moe_alias_specs still rejects frozen tuple trees.
tests/… Callers of the removed private helpers now use split_spec/split_aliases. The get_moe_modules asserts now check ModulePlan.is_moe/moe_roots. New registry-wide reference test (see Tests).
docs/model-tree-resolution.md Short "One token grammar" section with the new flow and an old-vs-new table.

No 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 in gptqmodel/, 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_block would then log "No :moe flag found" and return None. The shipped code returns all moe_roots(). That matches the old output, in order, for every registered tree. test_dotted_moe_root_key_is_reported pins 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) and collect_leaf_specs's conflict-raising walk stay as they are, per the map.

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/module_tree/test_moe_flag_parsing.py:

  • test_plan_flag_and_moe_queries_match_reference_walk[<model_type>] (210 nodes): for every MODEL_MAP entry and every effective tree (gptq + each override method), asserts that get_norm_modules, get_post_norm_modules, get_awq_no_scale_consumer_modules and get_moe_module_name equal, 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 :norm dict key.
  • test_split_aliases_keeps_checkpoint_aliases_in_order.

Red evidence. With the map's "." not in template filter put back, the nemotron_h and nemotronh_nano_omni_reasoning_v3 nodes and test_dotted_moe_root_key_is_reported fail at the assertion. With the not spec.is_expert_placeholder filter removed from flagged(), the synthetic test fails.

The map's CPU list plus the touched families, on this branch:

cd <clone>; HF_HOME=/root/.cache/huggingface CUDA_VISIBLE_DEVICES="" PYTHONPATH=$PWD python -P -m pytest -q -rs \
  tests/module_tree/test_registered_module_plans.py tests/module_tree/test_moe_flag_parsing.py \
  tests/module_tree/test_explicit_module_plan.py tests/module_tree/test_shared_input.py \
  tests/module_tree/test_shared_input_cpu_forward.py tests/test_norm_config.py tests/test_norm_requant.py \
  tests/test_awq_scaling_groups.py tests/test_awq_scale_folding.py tests/module_tree/test_gemma_olmo_family_plan_coverage.py \
  tests/module_tree/test_moe_tags.py tests/module_tree/test_model_alignment.py tests/test_olmo3_support.py \
  tests/module_tree/test_module_tree_variants.py tests/module_tree/test_subset.py
# 2 failed, 1584 passed, 2 skipped in 121.58s
  • 2 failures, both pre-existing on origin/main 1615acc with the same assertion: test_registered_module_plans.py::test_registered_model_plan_matches_quantization_consumers[gemma4] and [gemma4_text]. The checked-in registered_module_plans.json blocks 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 shows build_layer_modules is identical old vs new.
  • 2 skips (test_awq_scaling_groups.py:571: opt350, muse_glimmer are 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/main and on this branch, and the per-node outcomes were compared:

87 test files: tests/ minus tests/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 --junitxml and CUDA_VISIBLE_DEVICES="".

passed failed skipped
origin/main 1615acc 2968 4 121
this branch 3180 4 121
  • Identical per-node outcomes. All 3091 nodes that exist on both sides have the same outcome.
  • Nodes that exist on one side only.
    • The branch adds 214 nodes, all passing: 210 reference-walk nodes plus 4 new tests.
    • Two old nodes in test_shared_input.py::TestFlagParsing tested the deleted LazyTurtle._parse_module_spec and BaseQModel._parse_module_flags. They are replaced by test_module_tree_grammar_keeps_in_tag_as_plain_flag.
  • The same 4 failures on both sides, all pre-existing on main:
    • 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_keys and test_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) with ValueError: The tokenizer ... is unusable.
  • 121 skips, the same on both sides:
    • 118 CUDA-only: 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.
    • 1 missing mamba_ssm (test_jamba_support:303).
    • 2 non-buildable AWQ families (see above).

Measured Impact

Not applicable: no claimed issue. This is a behavior-preserving refactor with no runtime cost change. The flag getters compile a ModulePlan per call, as is_moe_module already 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_consumers now reads self.get_awq_no_scale_consumer_modules() directly instead of through the removed one-line awq_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/main and this branch in separate processes, dumps JSON, then diffs in order. Two baselines were used: the pristine origin/main worktree at 1615acc (this branch's base) and the read-only debloat base at 390a032. Their dumps are byte-identical.

PYTHONPATH=<origin/main> python -P ab_module_tree.py dump old.json
PYTHONPATH=<branch>      python -P ab_module_tree.py dump new.json
python -P ab_module_tree.py diff old.json new.json

Coverage:

  • All 210 MODEL_MAP entries.
  • 422 trees, each as a mutable list and as the _freeze_module_tree tuple: 844 tree queries. The trees are:
    • the class module_tree;
    • every module_tree_overrides[method] applied via apply_module_tree_override;
    • every _resolve_effective_module_tree result for gptq plus each override method;
    • every tree-shaped class attribute, such as Falcon's module_tree_two_norm.

Per tree, 24 outputs are compared in order:

  • All five old token parsers against the shared grammar, on 20,932 tokens per parser.
  • has_moe_flag.
  • Every iter_variants copy and _iter_module_tree_variants (explicit and class-default).
  • get_norm_modules, get_post_norm_modules, get_awq_no_scale_consumer_modules and get_moe_module_name, both class-level under _module_tree_context and instance-bound.
  • The _norm_scale_consumers no-scale call site.
  • extract_layers_node, and is_moe_module on every declared path.
  • build_layer_modules (with and without capture-only), build_shared_input_plan, collect_leaf_specs, collect_module_specs and ModulePlan.to_dict.
  • LazyTurtle._build_moe_alias_specs and generate_layers_modules_tree_simple.
  • flagged_any: the old generic _collect_flagged_layer_modules(f) against ModulePlan.flagged(f) for every flag that appears in the tree.

Coverage is not vacuous. The non-empty results are:

Query Tree queries with a non-empty result
norm 132
postnorm 52
noconsumer 8
MoE roots 326

Result:

MODEL_MAP entries: 210 old / 210 new; tree queries: 844
informational: 658 old-walker `parent..leaf` paths for non-production flags ['!', '0', '1', 'down', 'gate', 'in=x', 'k', 'nosrc', 'o', 'q', 'up', 'v']
production differences: 0

The 658 informational differences come only from flagged_any, for flags that no production code asks _collect_flagged_layer_modules about. The old walker joined an empty "" dict key (llama4 feed_forward:moe → "", and similar) as mlp..gate_proj, while ModulePlan joins it as mlp.gate_proj. No :norm, :postnorm or noconsumer flag sits under an empty key in any definition, so production output is identical.

ab_module_tree.py
"""Structural A/B for the one-module-tree-parser refactor.

Run once per checkout, each in its own process with that checkout first on
PYTHONPATH, then diff the two dumps:

    PYTHONPATH=<old> python -P ab_module_tree.py dump old.json
    PYTHONPATH=<new> python -P ab_module_tree.py dump new.json
    python -P ab_module_tree.py diff old.json new.json

The dump covers every MODEL_MAP class and, for each, the class tree, every
``module_tree_overrides[method]`` applied via ``apply_module_tree_override``,
every effective tree from ``_resolve_effective_module_tree`` (gptq + override
methods), and every other tree-shaped class attribute (layout variants such as
Falcon's ``module_tree_two_norm``). Each tree is queried both as the mutable
class-level list and as the deeply frozen tuple an instance stores. Lists are
kept in order, so ordering differences fail the diff.
"""

import json
import sys
from types import SimpleNamespace


def _jsonable(value):
    if isinstance(value, dict):
        return {str(k): _jsonable(v) for k, v in value.items()}
    if isinstance(value, (list, tuple)):
        return [_jsonable(v) for v in value]
    if isinstance(value, (set, frozenset)):
        return sorted(repr(v) for v in value)
    if isinstance(value, (str, int, float, bool)) or value is None:
        return value
    return repr(value)


def _call(fn, *args, **kwargs):
    try:
        return {"ok": _jsonable(fn(*args, **kwargs))}
    except Exception as exc:  # recorded, compared like any other output
        return {"error": f"{type(exc).__name__}: {exc}"}


def _is_tree(value):
    if not isinstance(value, (list, tuple)) or not value:
        return False
    variants = value if all(isinstance(v, (list, tuple)) for v in value) else [value]
    return any("#" in list(v) for v in variants)


def _tokens(node, out):
    """Every string token in a tree: prefixes, dict keys and leaves, in walk order."""
    if isinstance(node, str):
        out.append(node)
    elif isinstance(node, dict):
        for key, value in node.items():
            if isinstance(key, str):
                out.append(key)
            _tokens(value, out)
    elif isinstance(node, (list, tuple)):
        for item in node:
            _tokens(item, out)
    return out


def dump(path):
    import gptqmodel
    from gptqmodel.models import base as B
    from gptqmodel.models import module_plan as MP
    from gptqmodel.models import shared_input as SI
    from gptqmodel.models.auto import MODEL_MAP
    from gptqmodel.utils.structure import LazyTurtle

    new = hasattr(MP, "split_spec")
    print("gptqmodel.__file__ =", gptqmodel.__file__, "| new API:", new, file=sys.stderr)

    # Token grammar, one adapter per old copy. Old: four parsers; new: one.
    if new:
        parsers = {
            "base._parse_module_flags": MP.split_spec,
            "base._parse_module_aliases": lambda t: MP.split_aliases(t)[0],
            "LazyTurtle._parse_module_spec": lambda t: tuple(map(tuple, MP.split_aliases(t))),
            "module_plan._split_spec": MP.split_spec,
            "shared_input._split_spec": SI.split_spec,
        }
        variant_fns = {"module_plan._iter_variants": MP.iter_variants, "shared_input._iter_variants": SI.iter_variants}
    else:
        parsers = {
            "base._parse_module_flags": B.BaseQModel._parse_module_flags,
            "base._parse_module_aliases": B.BaseQModel._parse_module_aliases,
            "LazyTurtle._parse_module_spec": LazyTurtle._parse_module_spec,
            "module_plan._split_spec": MP._split_spec,
            "shared_input._split_spec": SI._split_spec,
        }
        variant_fns = {"module_plan._iter_variants": MP._iter_variants, "shared_input._iter_variants": SI._iter_variants}

    def flagged(cls, tree, flag):
        # Old generic walker vs new ModulePlan.flagged, for any flag in the tree.
        if new:
            return list(MP.ModulePlan.from_tree(tree).flagged(flag))
        with cls._module_tree_context(tree):
            return cls._collect_flagged_layer_modules(":" + flag)

    def no_scale_call_site(inst):
        # base.py `_norm_scale_consumers`: old wrapper vs new direct call.
        if new:
            return sorted(set(inst.get_awq_no_scale_consumer_modules()))
        return sorted(set(inst.awq_no_scale_consumer_modules(None)))

    def query_tree(cls, tree):
        rec = {}
        toks = _tokens(tree, [])
        rec["tokens"] = {name: [_call(fn, t) for t in toks] for name, fn in parsers.items()}
        rec["has_moe_flag"] = [cls.has_moe_flag(t) for t in toks]
        rec["iter_variants"] = {name: _call(fn, tree) for name, fn in variant_fns.items()}
        rec["iter_variants"]["BaseQModel._iter_module_tree_variants"] = _call(cls._iter_module_tree_variants, tree)
        flags = sorted({f for t in toks for f in t.split(":")[1:] if f})
        rec["flagged_any"] = {f: _call(flagged, cls, tree, f) for f in flags}
        with cls._module_tree_context(tree):
            rec["get_norm_modules"] = _call(cls.get_norm_modules)
            rec["get_post_norm_modules"] = _call(cls.get_post_norm_modules)
            rec["get_awq_no_scale_consumer_modules"] = _call(cls.get_awq_no_scale_consumer_modules)
            rec["get_moe_module_name"] = _call(cls.get_moe_module_name)
            rec["iter_variants_default"] = _call(cls._iter_module_tree_variants)
            rec["extract_layers_node"] = layers = _call(cls.extract_layers_node)
            plan = MP.ModulePlan.from_tree(tree)
            probes = []
            for layer in layers.get("ok") or []:
                for spec in plan.specs:
                    concrete = spec.template.replace(B.EXPERT_INDEX_PLACEHOLDER, "3")
                    probes += [f"{layer}.0.{concrete}", f"{layer}.0.{concrete}.x"]
            rec["is_moe_module"] = [cls.is_moe_module(p) for p in probes]
        for capture in (False, True):
            rec[f"build_layer_modules[{capture}]"] = blocks = _call(cls.build_layer_modules, tree, include_capture_only=capture)
            if "ok" in blocks:
                rec[f"shared_input_plan[{capture}]"] = _call(
                    lambda: repr(SI.build_shared_input_plan(tree, blocks["ok"]))
                )
        rec["collect_leaf_specs"] = _call(lambda: {k: repr(v) for k, v in SI.collect_leaf_specs(tree).items()})
        rec["collect_module_specs"] = _call(lambda: {k: repr(v) for k, v in MP.collect_module_specs(tree).items()})
        rec["ModulePlan.to_dict"] = _call(lambda: MP.ModulePlan.from_tree(tree).to_dict())
        rec["LazyTurtle._build_moe_alias_specs"] = _call(LazyTurtle._build_moe_alias_specs, tree)
        # Instance-bound path: the effective tree is stored frozen on the wrapper.
        inst = object.__new__(cls)
        object.__setattr__(inst, "effective_module_tree", B._freeze_module_tree(tree))
        rec["inst.get_norm_modules"] = _call(lambda: inst.get_norm_modules())
        rec["inst.get_post_norm_modules"] = _call(lambda: inst.get_post_norm_modules())
        rec["inst.get_moe_module_name"] = _call(lambda: inst.get_moe_module_name())
        rec["inst.no_scale_consumers(call site)"] = _call(no_scale_call_site, inst)
        rec["inst.generate_layers_modules_tree_simple"] = _call(
            lambda: inst.generate_layers_modules_tree_simple(B._thaw_module_tree(tree))
        )
        return rec

    out = {}
    n_trees = 0
    for model_type, cls in sorted(MODEL_MAP.items()):
        trees = {}
        if cls.module_tree is not None:
            trees["module_tree"] = cls.module_tree
        for method, override in (cls.module_tree_overrides or {}).items():
            method = getattr(method, "value", method)
            if cls.module_tree is not None:
                trees[f"override[{method}]"] = B.apply_module_tree_override(cls.module_tree, override)
        for method in sorted({"gptq", *(getattr(m, "value", m) for m in (cls.module_tree_overrides or {}))}):
            try:
                eff = cls._resolve_effective_module_tree(SimpleNamespace(), SimpleNamespace(method=method))
            except Exception as exc:
                out.setdefault(model_type, {})[f"effective[{method}]"] = {"error": repr(exc)}
                continue
            if eff is not None:
                trees[f"effective[{method}]"] = eff
        for attr in sorted(dir(cls)):
            if attr == "module_tree" or attr.startswith("__"):
                continue
            try:
                value = getattr(cls, attr)
            except Exception:
                continue
            if _is_tree(value):
                trees[f"attr[{attr}]"] = value
        entry = out.setdefault(model_type, {"class": cls.__name__})
        for label, tree in trees.items():
            for form, t in (("list", B._thaw_module_tree(tree)), ("frozen", B._freeze_module_tree(tree))):
                entry[f"{label}/{form}"] = query_tree(cls, t)
                n_trees += 1
    with open(path, "w") as fh:
        json.dump(out, fh, indent=1, sort_keys=True)
    print(f"dumped {len(out)} MODEL_MAP entries, {n_trees} tree queries -> {path}", file=sys.stderr)


def _walk_diff(a, b, path, diffs):
    if type(a) is not type(b):
        diffs.append((path, a, b))
    elif isinstance(a, dict):
        for key in sorted(set(a) | set(b)):
            if key not in a or key not in b:
                diffs.append((f"{path}/{key}", a.get(key, "<missing>"), b.get(key, "<missing>")))
            else:
                _walk_diff(a[key], b[key], f"{path}/{key}", diffs)
    elif isinstance(a, list):
        if len(a) != len(b):
            diffs.append((path, f"len {len(a)}", f"len {len(b)}"))
        for i, (x, y) in enumerate(zip(a, b)):
            _walk_diff(x, y, f"{path}[{i}]", diffs)
    elif a != b:
        diffs.append((path, a, b))


def diff(old_path, new_path):
    old, new = json.load(open(old_path)), json.load(open(new_path))
    diffs = []
    _walk_diff(old, new, "", diffs)
    queries = sum(len([k for k in v if "/" in k]) for v in old.values())
    print(f"MODEL_MAP entries: {len(old)} old / {len(new)} new; tree queries: {queries}")
    keys = sorted({k for v in old.values() for q in v.values() if isinstance(q, dict) for k in q})
    print(f"compared outputs per tree: {len(keys)}: {', '.join(keys)}")
    # `flagged_any` asks the old generic `_collect_flagged_layer_modules` walker
    # about every flag in the tree, not just the three production callers
    # (norm/postnorm/noconsumer). The old walker joined a `""` dict key as
    # `parent..leaf`; ModulePlan joins it as `parent.leaf`. Report those apart.
    production_flags = {"norm", "postnorm", "noconsumer"}
    informational, failures = [], []
    for item in diffs:
        parts = item[0].split("/")
        if len(parts) > 5 and parts[4] == "flagged_any" and parts[5] not in production_flags and ".." in str(item[1]):
            informational.append(item)
        else:
            failures.append(item)
    flags = sorted({item[0].split("/")[5] for item in informational})
    print(f"informational: {len(informational)} old-walker `parent..leaf` paths for non-production flags {flags}")
    for p, x, y in failures[:50]:
        print(f"DIFF {p}\n  old: {str(x)[:300]}\n  new: {str(y)[:300]}")
    print(f"production differences: {len(failures)}")
    return 1 if failures else 0


if __name__ == "__main__":
    if sys.argv[1] == "dump":
        dump(sys.argv[2])
    else:
        sys.exit(diff(sys.argv[2], sys.argv[3]))

GPU A/B

Run on one GPU (CUDA_DEVICE_ORDER=PCI_BUS_ID), origin/main 1615acc vs this branch. Both sides used the same QuantizeConfig(bits=4, group_size=128) (GPTQ) or quant_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 *.json file was compared.

Model Method Saved tensors Mismatched tensors JSON files differing Result
Qwen/Qwen2.5-0.5B-Instruct GPTQ 4-bit g128 794 0 0 of 5 bit-identical
Qwen/Qwen2.5-0.5B-Instruct AWQ GEMM 4-bit g128 626 0 0 of 5 bit-identical
trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6 (MoE + VL, 24 expert qweights) GPTQ 4-bit g128 200 0 0 of 6 bit-identical
same tiny Qwen3.5-MoE AWQ GEMM 4-bit per-channel (g-1; g128 rejects its 16-wide experts on both sides) 163 0 0 of 6 bit-identical
PYTHONPATH=<checkout> CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=<gpu> python -P quant_ab.py quant <model> <gptq|awq|awq_pc> <out>
python -P quant_ab.py compare <out_main> <out_branch>   # torch.equal on every safetensors tensor's bytes, == on every *.json

Logic Flow Documentation

  • This change does not alter a major logic flow, or the required diagrams and docs page are included below.
  • New-flow Mermaid diagram(s) describe the shipped code using real symbol names.
  • The removed/replaced mechanism is shown or tabulated with file:line evidence.
  • Failure and ambiguity paths are marked and visually distinct from success.
  • A reference page under docs/ repeats the diagrams, titled for the mechanism, and is linked from README.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 to docs/model-tree-resolution.md, which README.md already 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:#a8071a
Loading
Concern Before (origin/main 1615acc) After
token parse module_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_spec module_plan.py:59,70 split_aliases/split_spec
path join module_plan.py:64, shared_input.py:74 module_plan.py:76 join_path
variant split module_plan.py:70, shared_input.py:149, base.py:2187, structure.py:2651 module_plan.py:82 iter_variants (base.py keeps the class-default wrapper _iter_module_tree_variants)
:norm / :postnorm / noconsumer base.py:2413-2462 _collect_norm_modules_from_tree + _collect_flagged_layer_modules module_plan.py:476 ModulePlan.flagged; base.py:2292,2303,2327
MoE roots base.py:2373-2410 first-layer-dict key scan base.py:2273 ModulePlan.moe_roots()
no-scale call site base.py:8196 self.awq_no_scale_consumer_modules(module) → wrapper base.py:2511 base.py:8010 self.get_awq_no_scale_consumer_modules()
unused base.py:2274,2322 _collect_moe_modules_from_tree/get_moe_modules, base.py:2517 has_norm_flag removed

There are no new failure paths. A None tree still gives None from get_moe_module_name and [] from the flag getters.

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

Notes

  • AWQ interface point (for the parallel AWQ lifecycle refactor).
    • BaseQModel.get_awq_no_scale_consumer_modules() (classmethod, List[str]) has the same signature and output as before. It is now the only accessor.
    • The instance wrapper awq_no_scale_consumer_modules(self, layer) is removed, and _norm_scale_consumers calls the classmethod directly.
    • get_post_norm_modules() and awq_post_norm_modules(layer) keep their signatures. OLMo Hybrid still overrides the latter.
    • No other AWQ code is touched.
  • Corners where the new reading differs from the old walkers. No registered definition hits any of these; the A/B and the 210 reference-walk nodes prove it.
    • Order across variants. If a path is declared without the flag in an earlier variant and with it in a later one, it now keeps its first-declaration position.
    • Nested :moe keys. A :moe flag on a nested key or on a parent-repeat leaf is now reported by get_moe_module_name too. test_registered_module_plans already asserts set(get_moe_module_name()) == {s.template for s in plan.moe_roots()} for every definition.
    • Empty "" keys. They join without a doubled dot.
    • Degenerate tokens. For a token whose name segment is only | characters, LazyTurtle used to take the whole raw token as the alias; it now takes the name segment, like the other parsers. No such token exists.
  • No behaviour switches or environment variables were added.

🤖 Generated with Claude Code

Qubitium added a commit that referenced this pull request Nov 29, 2026
@Qubitium
Qubitium marked this pull request as ready for review November 29, 2026 13:55
Qubitium and others added 2 commits November 29, 2026 13:56
…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]>
@Qubitium
Qubitium force-pushed the refactor/one-module-tree-parser branch from 2eec7ed to 8505e4b Compare November 29, 2026 13:57
@Qubitium
Qubitium merged commit 1ffe683 into main Nov 29, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/one-module-tree-parser branch November 29, 2026 14:05
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