Skip to content

fix(models): resolve module roles from explicit model trees - #3565

Merged
Qubitium merged 7 commits into
mainfrom
fix/explicit-module-tree-matching
Nov 7, 2026
Merged

Qubitium merged 7 commits into
mainfrom
fix/explicit-module-tree-matching

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Module classification and quantization selection now use the architecture's declared module_tree, compiled into a layer-relative ModulePlan. Paths that merely resemble a declared module no longer inherit its expert family or rotation behavior. Unknown architectures require an explicit definition or injected tree.

The PR also exposes model.module_plan() for inspection and adds an always-run contract for every active model registry entry. New model support must add both a registry case and a model-specific module-plan unit test.

Measured diff against main (0aaf40e): 45 files, +5,468 / −234. The explicit registry expectation fixture accounts for 2,461 added lines. Flow reference: docs/model-tree-resolution.md.

1. Removed decisions and their replacements

Source references in the “before” column refer to base commit 0aaf40e.

Area Before Resulting behavior
Expert grouping looper/module_looper.py:924: split on .experts., .shared_experts., or .shared_expert. Resolve the declared expert container; require the full path to exist in ModulePlan.find()
Attention grouping looper/module_looper.py:947: substring checks for attn / attention Query declared projection roles
MoE membership models/base.py:836: substring/suffix membership Strip the declared decoder prefix and match the layer-relative declaration
Loading and saving models/loader.py:1926, models/writer.py:1322: suffix-based quantizability Compare decoder-relative paths with the declared quantization inventory
Rotation models/loader.py:676: endswith("mlp.down_proj") With a plan, require a declared decoder path carrying down; no suffix fallback for undeclared paths
Unsupported architecture runtime module-tree guessing Explicit definition/injection required; diagnostic auto-detection remains available

For example, declaring mlp.experts.#.gate_proj permits mlp.experts.3.gate_proj. It does not permit mlp_extra.experts.3.gate_proj or mlp.experts.3.undeclared. Hymba's literal moe.experts.0 is also recognized as an expert family; it is not classified as a shared branch.

2. Compilation and ownership

flowchart TD
    LOAD["model loaded"] --> RES["_resolve_effective_module_tree()"]
    RES --> INJECT{"explicit injected tree?"}
    INJECT -->|"yes"| OVERRIDE["apply method override"]
    INJECT -->|"no"| DEF["registered definition.module_tree"]
    DEF --> OVERRIDE
    OVERRIDE --> CHECK{"tree exists?"}
    CHECK -->|"no"| ERROR["ValueError: explicit definition required"]
    CHECK -->|"yes"| FREEZE["freeze effective_module_tree"]
    FREEZE --> PLAN["ModulePlan.from_tree()"]
    PLAN --> API["model.module_plan()"]
    API --> CONSUMERS["AWQ / loopers / rotation / GSQ"]
    API --> HOOKS["per-instance copied MoE hooks"]
    style ERROR fill:#ffa39e,stroke:#a8071a
    style PLAN fill:#d9f7be,stroke:#237804
Loading

The effective tree is stable for the instance. Live model consumers obtain the compiled plan through model.module_plan(). Definition-level planning remains available before a wrapper exists. Unbound lifecycle hooks compile from the definition or call the live wrapper accessor; they do not mistake the accessor method for a plan object. Hook copies keep instance-specific trees from leaking to later models.

ModuleSpec records exact template paths and flags. Explicit projection tags override legacy canonical names declared in the tree. The legacy PROJECTION_ROLE_NAMES fallback (q_proj, w1, gate_up_proj, etc.) remains; this PR does not claim that every existing definition has been migrated to explicit role tags.

Declaration Meaning
q_proj:0:q:in=x Quantization group 0, query role, shared-input tag x
norm:!:norm Excluded from quantization, explicitly tagged normalization module
mlp:moe:? MoE root with capture-only behavior
experts.# Indexed expert template
experts.0 Explicit fixed expert index
gate_proj|w1 Canonical runtime name followed by checkpoint alias

3. Exact expert queries and lifecycle consumption

flowchart TD
    ROOT["declared MoE root"] --> CHILD{"declared child structure"}
    CHILD -->|"# placeholder"| ROUTED["expert_containers()"]
    CHILD -->|"numeric child with projection leaves"| ROUTED
    CHILD -->|"other projection family"| SHARED["shared_expert_containers()"]
    ROUTED --> FIND{"ModulePlan.find(path)"}
    FIND -->|"declared"| GROUP["is_expert() / expert_root()"]
    FIND -->|"undeclared"| REJECT["False / None"]
    GROUP --> LOOP["ModuleLooper / WeightOnlyLooper grouping"]
    ROUTED --> HOOK["MoE lifecycle container lookup"]
    SHARED --> HOOK
    style REJECT fill:#ffa39e,stroke:#a8071a
Loading

Shared containers are derived from declared projection structure rather than an allow-list of names. Fixed numeric expert branches are excluded from shared-container classification. The new regressions cover both unbound routed/shared hooks and Hymba's fixed index, including rejection of an undeclared index.

4. Public debugging and extraction API

plan = model.module_plan()
plan.print()                     # TUI tree, terminal colors detected
plan.print(color=False)          # plain output for logs
plan.print(max_depth=2)          # limit large trees
text = plan.render(color=False)
payload = plan.to_dict()
json_text = plan.to_json()
summary = plan.summary()
flowchart LR
    MODEL["model.module_plan()"] --> PLAN["ModulePlan"]
    PLAN --> TUI["print() / render()"]
    PLAN --> EXPORT["to_dict() / to_json() / summary()"]
    PLAN --> QUERY["find() / roles() / expert_root()"]
Loading

The renderer shows quantization/exclusion/capture flags, projection roles, normalization and input tags, and expert/shared container structure. to_dict() exposes a separate container field: structural containers must not be interpreted as weight-bearing quantization targets merely because they lack an exclusion flag. ModulePlan and ModuleSpec are exported from gptqmodel and gptqmodel.models.

5. Consumer changes and rotation guarantees

Consumer Declared information consumed
AWQ Projection roles, expert families, capture/exclusion flags
Module and weight-only loopers Expert family keys and gate/up roles for grouping
Loader/writer Declared decoder prefixes and quantizable relative paths
Rotation norm flags and q/k/v/o/gate/up/down roles
GSQ Projection inventory and attention/MLP partitions
EXL3 Exact LM-head path

Normalization is a tag, not a projection role. fuse_layer_norms() now reads norm flags directly; querying projection roles for norm would always produce an empty list. A real tiny Llama test initializes non-unit norm weights and verifies logits before and after fusion at atol=rtol=1e-6. Both explicit-plan and public-default calls are tested.

flowchart TD
    P["rotation plan"] --> N["root specs with norm flag"]
    N --> COUNT{"exactly two layer norms?"}
    COUNT -->|"no"| FAIL["ValueError"]
    COUNT -->|"yes"| FUSE["fuse_layer_norms()"]
    P --> PATH["declared decoder-relative path"]
    PATH --> DOWN{"down role?"}
    DOWN -->|"yes"| HAD["attach online Hadamard state"]
    DOWN -->|"no / undeclared"| IGNORE["leave module untouched"]
    style FAIL fill:#ffa39e,stroke:#a8071a
Loading

The legacy online-rotation suffix default is retained only for public calls that supply no plan. With a plan, a quantized module outside the declared decoder cannot acquire a transform through a matching suffix. GSQ's existing Llama/Qwen3 staged-capture limits remain; accepting declared inventories does not imply arbitrary architecture support.

6. Checkpoint-owned weight coverage

The compiled plan is a layer-relative decoder inventory. Base-module/embedding metadata remains separate. The real Flash-family tests audit every checkpoint-weight owner within their decoder layers, including non-quantized routers, norms, compressors, and other inference weights.

flowchart TD
    FIX["real model architecture fixture: state_dict()"] --> OWNER["deepest owning module"]
    CKPT["actual checkpoint keys + conversion mappings"] --> OWNED{"checkpoint-owned?"}
    OWNED -->|"yes"| OWNER
    OWNED -->|"runtime-created only"| OUT["not a definition obligation"]
    OWNER --> FIND{"ModulePlan.find(owner)"}
    FIND -->|"missing"| FAIL["undeclared-weight failure"]
    FIND -->|"found"| QUANT{"quantizable inventory?"}
    QUANT -->|"yes"| OK["declared quantization target"]
    QUANT -->|"no"| TAG{"explicit exclusion/capture tag?"}
    TAG -->|"no"| FAIL
    TAG -->|"yes"| DENSE["declared non-quantized weight"]
    style FAIL fill:#ffa39e,stroke:#a8071a
Loading

state_dict() is an architecture fixture, not proof of checkpoint provenance after runtime tensors have been created. Actual checkpoint audits use checkpoint keys and declared conversion mappings. Runtime-created buffers/parameters do not create declaration obligations solely because they appear in memory.

The real model tests cover Qwen 3.8 (qwen3_5), GLM 5.3 Flash, MiniMax M3.1 Flash, DeepSeek V4 Flash, and Ripple's real remote-code fixture. The DeepSeek V4.1 test remains conditional on upstream deepseek_v41 support and does not relabel V4 coverage as V4.1 coverage.

7. Every registered model has a module-plan unit test

The always-run registry contract covers 198 model-type entries, 173 definition classes, and 175 definition/method cases in the tested environment. It pins decoder prefixes and ordered quantization/capture/exclusion blocks in a reviewed fixture derived from the independent subset planner. It checks plan agreement with the subset/shared-input/norm/MoE planners, exact path rejection, looper expert grouping, per-variant compilation, and printable/serializable output.

Original dbrx is a documented unsupported registry sentinel and receives a rejection test. dbrx_converted receives positive coverage. Thus the suite contains 197 positive model-type contracts, one explicit rejection case, and one registry-completeness gate: 199 passed, zero skipped.

flowchart TD
    REG["MODEL_MAP entry"] --> CASE{"explicit inventory case?"}
    CASE -->|"missing"| FAIL["test failure: add model-plan case"]
    CASE -->|"present"| TREE["definition and method override"]
    TREE --> PLAN["ModulePlan.from_tree()"]
    TREE --> SUB["build_layer_modules() / shared-input metadata"]
    PLAN --> CHECK["compare paths, flags, norms, MoE and exact lookup"]
    SUB --> CHECK
    CHECK --> USE["loopers via module_plan()"]
    TREE --> REAL["separate real-model tests: actual layout and weight owners"]
    style FAIL fill:#ffa39e,stroke:#a8071a
Loading

This registry suite is compiler/consumer unit coverage, not a claim that all remote checkpoints have been instantiated. Real model validation is separate. AGENTS.md, .agents/skills/gptqmodel-model-plan-tests/SKILL.md, and the PR template now require every new model/alias to add an explicit case plus a model-specific test using the real model class, including variants, method overrides, weight tags, and relevant consumers. Missing optional implementations must be reported precisely; blanket exception skips and tree-generated fake models do not qualify as real-model validation.

8. Validation

Final head validation on Python 3.14, Torch 2.15.0+cu132, Transformers 5.22.1:

Command Result
pytest tests/module_tree/test_registered_module_plans.py -q --disable-warnings 199 passed, no skips
pytest tests/test_rotation_persistence.py -q --disable-warnings 11 passed, 1 skipped (saved rotated checkpoint fixture absent)
CUDA_VISIBLE_DEVICES=0 pytest tests/module_tree tests/test_rotation_persistence.py tests/test_afmoe_support.py -q --disable-warnings 880 passed, 135 skipped
Ruff on changed Python files Passed
python -m compileall -q gptqmodel Passed
Skill validator and git diff --check Passed

Existing broader-suite skips remain; the registry contract does not require opt-in flags, checkpoint downloads, or GPUs and has no skips.

The Llama 3.2 1B E2E tests also passed on earlier PR head 2d0ecbd. These used fast mode (final 2/16 layers quantized, 512 calibration examples). GPTQ's evaluation used eager attention because the configured FlashAttention2 package was absent. These scores are not presented as a full 16-layer quantization run:

Metric GPTQ/MARLIN AWQ/MARLIN AWQ/GEMM
GSM8K Platinum 0.4557 0.4723 0.4715
ARC Challenge 0.3140 0.3200 0.3208
ARC normalized 0.3439 0.3490 0.3498
MMLU STEM not run 0.3933 0.3945

9. Change inventory

Measured against 0aaf40e; grouped totals include all changed files.

Area Added Removed
Documentation, skills, and PR requirements +753 −0
Lookup utilities and exports +47 −8
Looper consumers +70 −59
Model loading, writing, lifecycle, and API +242 −58
Model definitions +37 −10
ModulePlan core +564 −0
Rotation, AWQ, and GSQ +162 −67
Tests and explicit registry expectations +3,593 −32

No quantization math, checkpoint format, or public quantization-config schema is changed. The new rules and diagrams are committed in the repository so future model support can follow the same contracts.

Add $gptqmodel-logic-flow-diagrams skill, wire it into AGENTS.md and the PR
template, and commit the resolved model-tree flow as a reference page.

- .agents/skills/gptqmodel-logic-flow-diagrams: when the rule applies, required
  artifacts (new-flow diagram, before/after evidence, docs page), accuracy
  rules, Mermaid authoring rules for GitHub rendering, and a review checklist.
- AGENTS.md: repo-wide instruction to apply the skill before opening a PR.
- .github/PULL_REQUEST_TEMPLATE.md: reviewable checklist for the same gate.
- docs/model-tree-resolution.md: the PR #3565 flow, diagrams and contracts,
  kept for future reference.
- README.md: link the new page from the quantization support section.
@Qubitium
Qubitium merged commit 7d03a34 into main Nov 7, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/explicit-module-tree-matching branch November 7, 2026 02:36
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