Skip to content

refactor(models): one export-shell module selector for the quantized loader and get_model_with_quantize - #6472

Merged
Qubitium merged 1 commit into
mainfrom
refactor/export-shell-selector
Nov 30, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/export-shell-selector

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

from_quantized and get_model_with_quantize each built the quantized export shell with their own copy of the same code. Each had the defuse trio, the embedding-endpoint probe and a ~45-line for name in list(modules) filter that decides which modules make_quant replaces. The writer comment said "Detect them exactly like the loader does so both paths cannot drift". Both paths now call one selector and one defuse helper in loader.py. Inside get_model_with_quantize, the duplicated GPTQ qzero-layout declaration and target-format stamp are now each written once.

Behavior-preserving refactor: numerics, checkpoint format and public API are unchanged. Production code: +144 / −215 (net −71); total with the new test and docs: 4 files changed, 310 insertions(+), 224 deletions(-).

No issue: debloat refactor (loader/writer map, PR4).

What Changed

  • gptqmodel/models/loader.py
    • New _defuse_export_shell(cls, model) runs _meta_fused_expert_params → _convert_model_with_defuser(cleanup_original=True) → _materialize_meta_expert_linears.
    • New _select_export_shell_modules(owner, model, qcfg, config, *, checkpoint_dir, module_tree_context=None) holds the old filter. It covers the embedding probe, is_embeddings_module_quantized, the qcfg.lm_head keep, declared leaves, layer prefix, EXPERT_INDEX_PLACEHOLDER, Optimum external_module_inclusions, ignored base modules and should_quantize_module.
      • The tree planners (get_base_modules, extract_layers_node, simple_layer_modules) run inside module_tree_context.
      • should_quantize_module runs outside it, exactly as before on both paths. This matters for MllamaQModel, whose override reads extract_layers_node().
    • from_quantized calls both helpers with cls and cls._module_tree_context(effective_module_tree). It still computes ignore_modules for build_layerwise_device_map.
  • gptqmodel/models/writer.py
    • get_model_with_quantize calls both helpers with self. The instance's __getattribute__ already binds its effective tree to the planners. self.lm_head, self.get_base_modules and the other hooks are still read from the instance (tests/test_writer_instance_attrs.py).
    • The GPTQ qzero-layout declaration (_checkpoint_format_on_disk plus qzero_format) was the first statement of both the W4A branch and the checkpoint-fill branch. It now runs once before the branch.
    • The target-format stamp was the last statement of both branches. It now runs once after.
  • Loader-only steps stay in from_quantized:
    • _apply_requested_module_tree and the dynamic-cache preparation
    • the GGUF key map
    • rotation admission and the EXL3 placeholders
    • _module_tree_context
    • after_make_quant (one line on each path, after different steps)
  • docs/quantized-moe-resave-defuse.md: the new-flow diagram and text name the two shared helpers.

Equivalence notes (verified on current origin/main):

  • Hoisting declared and the layer prefixes is pure.
    • The loader rebuilt declared per module from a simple_layer_modules list it had already computed.
    • The writer called self.simple_layer_modules(config, qcfg) and self.extract_layers_node() per module.
    • Both are deterministic planners, so computing them once returns the same values.
    • The only observable difference is diagnostic. On re-save, dynamic_get lookup-cache hit counters (a debug log) see one planner call instead of N. The build_moe_modules_if_need non-scalar-expert-count warning now fires once instead of once per module.
  • The loader's layer_prefix is None test is redundant. relative is None exactly when layer_prefix is None, so relative_match is already False and the module is dropped with the same log line. The writer already relied on this.
  • The writer's checkpoint_dir is unchanged. The writer still passes model_id_or_path and the loader still passes checkpoint_dir.
  • Lookup counts. The loader now calls cls.get_base_modules(model) twice (selector plus device map). Both calls are pure.

Out of scope: no behavior changes, no other loader/writer regions.

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/test_export_shell_module_selector.py (5 nodes, CPU, about 3 s). A synthetic definition uses an effective tree that differs from its class tree: the router mlp.gate is quantized only in the effective tree. The model has quantized-embedding/lm_head checkpoint variants, a -: dynamic rule, a should_quantize_module override and Optimum inclusions. The test asserts that the loader call and the writer call return the same ordered key list, the same module objects and the hand-listed expected names. It also asserts that should_quantize_module saw the class tree on both paths.

Red evidence (each mutation applied to a disposable copy of the branch package):

Mutation Result
selector drops module_tree_context (planners read the class tree) 4/5 fail at the expected key list (model.layers.0.mlp.gate missing)
should_quantize_module evaluated inside the tree context 4/5 fail at the class-tree assertion
unmodified branch 5/5 pass

Existing tests, branch vs origin/main (8d52eb918). The branch was later rebased onto 94ceaf77e, which brings in #6468-#6470; none of them touch loader.py, writer.py or any module tree. After that rebase, the structural A/B plus test_export_shell_module_selector, test_writer_instance_attrs, test_export_shell_gemv_resave_4305, test_registered_module_plans and test_moe_resave_preserves_experts_4589 were rerun: 445 passed. CPU runs used CUDA_VISIBLE_DEVICES=; GPU runs used CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=1:

# CPU, 37 files (list below), both checkouts
python -P -m pytest <files> -q -rs -p no:cacheprovider -n 8
#   origin/main: 764 passed, 32 skipped
#   branch:      753 passed, 32 skipped (+5 new selector nodes); identical node outcomes, no status changes
# GPU 1: accelerator-gated nodes skipped on CPU
python -P -m pytest tests/models/test_w4a_native_writer.py tests/models/test_w4a_resave_roundtrip.py -q -rs
#   origin/main: 24 passed, 4 skipped | branch: 24 passed, 4 skipped
python -P -m pytest tests/test_moe_reload_meta_e2e_4400.py tests/test_checkpoint_compat.py tests/test_requant_embed_endpoint_5116.py tests/test_requant_embed_lm_head.py tests/test_diffusion_gemma_support.py -q -rs
#   origin/main: 85 passed, 1 failed | branch: 85 passed, 1 failed (same node, pre-existing, see below)
# lint
bash format/check.sh   # ruff 0.14.2: All checks passed!

CPU files:

  • the 10 map-listed resave tests except tests/models/test_diffusion_gemma.py (see below)
  • test_writer_instance_attrs, test_model_load_lock_4204, test_trust_remote_code_isolation, test_moe_reload_meta_4400, test_moe_reload_meta_e2e_4400, test_tiny_moe_quant_smoke, test_checkpoint_subfolder_resolution, test_writer_attention, test_defuser_vendored_classes, test_defuser_version_check
  • test_format_conversion_flow, test_inmemory_qzero_format, test_int3_legacy_qzeros_6375, test_qzeros_format_invariant, test_qzeros_format_load_4377, test_qzeros_state_machine_audit, test_requant_embed_endpoint_5116, test_requant_embed_lm_head_flag_6244, test_resave_dense_parameter_dtype_4466, test_checkpoint_compat, test_checkpoint_quant_buffer_dtypes_4458, test_gptq_p_markerless_qzeros_5809
  • models/test_w4a_resave_roundtrip, models/test_w4a_native_writer
  • module_tree/test_registered_module_plans, test_save_dispatch

Skips and what they leave unverified:

  • tests/models/test_w4a_native_writer.py NVFP4 cases (4): need GB10 / SM 12.1, which this host lacks. The W4A NVFP4 branch of the hoisted qzero declaration is verified only structurally. The w4afp8 cases passed on GPU 1.
  • CPU-run accelerator skips (test_checkpoint_compat lm_head, test_requant_embed_endpoint_5116, test_moe_reload_meta_e2e_4400) were rerun on GPU 1 (see above). tests/test_moe_reload_meta_e2e_4400.py::test_meta_expert_shell_reloads_bitwise_identically fails the same way on origin/main and on the branch. Its fixture saves an OLMoE model without tokenizer files, and the loader's tokenizer-usability check raises ValueError: Tokenizer files are missing, so that node gives no evidence either way. The quantized MoE reload path it targets is covered by the tiny Qwen3-MoE GPU A/B below.
  • test_qzeros_state_machine_audit kernel-geometry skips and test_model_load_lock_4204 free-threaded-only node: skipped identically on both sides.
  • tests/models/test_diffusion_gemma.py (listed in the map as CPU) is a full quantization of the local 26B diffusiongemma-26B-A4B-it checkpoint. I stopped it after 10 minutes of CPU and did not run it. tests/test_diffusion_gemma_support.py covers the DiffusionGemma after_make_quant / base-module hooks instead.
  • One pre-existing failure, not touched here: tests/test_docs_contract_refs.py::test_doc_python_example_runs[docs/measurement.md::3] (NameError: texts) fails identically on origin/main. All other 236 docs-contract nodes pass on the branch.

Structural A/B (every MODEL_MAP definition)

The script (struct_ab.py) extracts the old loader filter and the old writer filter verbatim from git show origin/main:gptqmodel/models/{loader,writer}.py and execs them. It then compares them with the new selector, called both ways: as the loader (cls plus _module_tree_context) and as the writer (instance with a frozen effective tree). Each run compares the ordered key list, the module identities and the "The layer X is not quantized." log lines.

  • Part A: 210 MODEL_MAP entries × each module_tree_overrides method. Each model is a meta model built from the definition's effective tree. It has 2 layers with every declared leaf and expanded {expert_index}, plus undeclared siblings, an out-of-layer linear, embeddings, lm_head, VL side towers and an mllama-style cross-attention layer. The output-embedding accessor variant raises NotImplementedError.
  • Part B: 35 real tiny models built on meta by the definitions' own LocalModelLoader from the tests/module_tree/test_shared_input_cpu_forward.py configs, then defused.
  • Axes: lm_head {off, on} × dynamic {none, -:.*down_proj + -:.*\.1\..*o_proj} × Optimum inclusions {none, set} × checkpoint {dense, quantized embed_tokens/lm_head}.
PYTHONPATH=<branch> python -P struct_ab.py <branch> struct_ab.json
runs 7296, identical 7296, diff 0, matching errors 0, non-empty selections 7214,
old loader vs old writer differ: 0, log lines compared: 193644, build failures: 0

GPU end-to-end A/B (GPU 1, same config, seed and calibration)

Flow per side: quantize → save (q) → GPTQModel.load (reload logits on 3 prompts) → save again (rs, which goes through get_model_with_quantize). A cross check also has the branch reload and re-save the checkpoint that origin/main quantized. Each comparison covers every safetensors key, dtype, shape and sha256 of the raw bytes, plus every JSON byte for byte.

Case q tensors q reload logits re-save cross re-save
Qwen2.5-0.5B-Instruct GPTQ 4-bit g128 (MarlinLinear) 794 bit-identical bit-identical bit-identical bit-identical
same + -:model\.layers\.1\.mlp\.down_proj 791 bit-identical bit-identical bit-identical bit-identical
tiny Qwen3-MoE (test_tiny_moe_quant_smoke geometry, 4 experts, all-expert routing, TritonV2Linear) 72 bit-identical bit-identical bit-identical bit-identical

lm_head=True is not in the GPU matrix: GPT-QModel rejects it for the tied Qwen2.5 head. The structural A/B and the unit test cover it.

Measured Impact

Not applicable: no claimed issue and no performance or accuracy change. Outputs are bit-identical.

Model Support / Module Plan

Not applicable: no MODEL_MAP, definition or module-tree change. tests/module_tree/test_registered_module_plans.py passes, and the structural A/B covers every registered definition.

AWQ onboarding safety

Not applicable: no AWQ grouping, search, replay or fold change. The one AWQ module_tree_overrides tree (Qwen3NextGPTQ/awq) is included in the structural A/B.

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 order is unchanged; two copies of the shell-slot decision become one. The existing page docs/quantized-moe-resave-defuse.md, linked from README, now names both helpers.

flowchart TD
    L["from_quantized"] --> D["_defuse_export_shell"]
    W["get_model_with_quantize"] --> D
    D --> S{"_select_export_shell_modules"}
    S -- "quantized embedding endpoint" --> K[keep]
    S -- "qcfg.lm_head and name == lm_head" --> K
    S -- "outside layers / base module /<br/>undeclared / not included" --> X[drop + log]
    S -- "should_quantize_module False" --> X
    S -- "declared layer leaf" --> K
    K --> M["make_quant"]
    style X fill:#ffebee
Loading
Step Old (origin/main; unchanged at 94ceaf77e) New
Defuse trio loader.py:3898-3903, writer.py:3210-3226 _defuse_export_shell loader.py:1791-1802
Embedding probe + is_embeddings_module_quantized loader.py:3937-3958, writer.py:3228-3254 _select_export_shell_modules loader.py:1805-1891
Module filter loop loader.py:3961-4012, writer.py:3256-3303 same selector; called at loader.py:4039, writer.py:3215
declared / layer prefixes rebuilt per module in both copies computed once inside the tree context
GPTQ qzero-layout declaration writer.py:3333-3342 and 3361-3370 once, writer.py:3241-3258
Target-format stamp writer.py:3351-3354 and 3429-3432 once, writer.py:3327-3331

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 or fusion change. GPU A/B outputs are bit-identical.

Notes

  • I kept the name is not owner.lm_head identity comparison in the "not quantized" log guard unchanged; it was in both copies. It only affects whether lm_head is logged.

🤖 Generated with Claude Code

…loader and get_model_with_quantize

`from_quantized` and `get_model_with_quantize` each carried their own copy of
the quantized-shell build: the defuse trio (`_meta_fused_expert_params` ->
`_convert_model_with_defuser` -> `_materialize_meta_expert_linears`), the
NotImplementedError embedding-endpoint probe plus
`is_embeddings_module_quantized`, and the ~45-line `for name in list(modules)`
filter (declared leaves, layer prefix, expert placeholder, Optimum inclusions,
ignored base modules, `should_quantize_module`). The writer comment already
said "Detect them exactly like the loader does so both paths cannot drift".

Both now call two plain helpers in loader.py:

- `_defuse_export_shell(cls, model)` runs the defuse trio.
- `_select_export_shell_modules(owner, model, qcfg, config, *, checkpoint_dir,
  module_tree_context=None)` returns the modules `make_quant` replaces. The
  loader passes the definition class with `cls._module_tree_context(tree)`;
  the writer passes the instance, whose `__getattribute__` already binds its
  effective tree to the planners. As before, `should_quantize_module` runs
  outside the tree context on both paths.

`declared` and the layer prefixes are computed once instead of per module.
Both copies rebuilt them from pure planners (`simple_layer_modules`,
`extract_layers_node`), so this only drops repeated work. The loader's extra
`layer_prefix is None` test is implied by `relative_match` (relative is None
exactly when layer_prefix is None), which is how the writer already handled it.

In `get_model_with_quantize`, the GPTQ qzero-layout declaration was the first
statement of both the W4A and the checkpoint-fill branch and the
target-format stamp was the last statement of both; each is now written once
before / after the branch.

No numerics, checkpoint-format or public-API change. A structural A/B
(every MODEL_MAP definition, old loader filter vs old writer filter vs new
selector) and a GPU quantize -> save -> reload -> re-save A/B (Qwen2.5-0.5B
dense, dense with a `-:` rule, tiny Qwen3-MoE) are identical, bit for bit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium marked this pull request as ready for review November 30, 2026 03:08
@Qubitium
Qubitium merged commit 47aa824 into main Nov 30, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/export-shell-selector branch November 30, 2026 03:08
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