Repository navigation
refactor(models): one export-shell module selector for the quantized loader and get_model_with_quantize - #6472
Merged
Merged
Conversation
…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
marked this pull request as ready for review
November 30, 2026 03:08
This was referenced Dec 1, 2026
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
from_quantizedandget_model_with_quantizeeach 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-linefor name in list(modules)filter that decides which modulesmake_quantreplaces. 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 inloader.py. Insideget_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_defuse_export_shell(cls, model)runs_meta_fused_expert_params→_convert_model_with_defuser(cleanup_original=True)→_materialize_meta_expert_linears._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, theqcfg.lm_headkeep, declared leaves, layer prefix,EXPERT_INDEX_PLACEHOLDER, Optimumexternal_module_inclusions, ignored base modules andshould_quantize_module.get_base_modules,extract_layers_node,simple_layer_modules) run insidemodule_tree_context.should_quantize_moduleruns outside it, exactly as before on both paths. This matters forMllamaQModel, whose override readsextract_layers_node().from_quantizedcalls both helpers withclsandcls._module_tree_context(effective_module_tree). It still computesignore_modulesforbuild_layerwise_device_map.gptqmodel/models/writer.pyget_model_with_quantizecalls both helpers withself. The instance's__getattribute__already binds its effective tree to the planners.self.lm_head,self.get_base_modulesand the other hooks are still read from the instance (tests/test_writer_instance_attrs.py)._checkpoint_format_on_diskplusqzero_format) was the first statement of both the W4A branch and the checkpoint-fill branch. It now runs once before the branch.from_quantized:_apply_requested_module_treeand the dynamic-cache preparation_module_tree_contextafter_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):declaredand the layer prefixes is pure.declaredper module from asimple_layer_moduleslist it had already computed.self.simple_layer_modules(config, qcfg)andself.extract_layers_node()per module.dynamic_getlookup-cache hit counters (a debug log) see one planner call instead of N. Thebuild_moe_modules_if_neednon-scalar-expert-count warning now fires once instead of once per module.layer_prefix is Nonetest is redundant.relativeisNoneexactly whenlayer_prefixisNone, sorelative_matchis alreadyFalseand the module is dropped with the same log line. The writer already relied on this.checkpoint_diris unchanged. The writer still passesmodel_id_or_pathand the loader still passescheckpoint_dir.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
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 routermlp.gateis quantized only in the effective tree. The model has quantized-embedding/lm_head checkpoint variants, a-:dynamic rule, ashould_quantize_moduleoverride 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 thatshould_quantize_modulesaw the class tree on both paths.Red evidence (each mutation applied to a disposable copy of the branch package):
module_tree_context(planners read the class tree)model.layers.0.mlp.gatemissing)should_quantize_moduleevaluated inside the tree contextExisting tests, branch vs
origin/main(8d52eb918). The branch was later rebased onto94ceaf77e, which brings in #6468-#6470; none of them touchloader.py,writer.pyor any module tree. After that rebase, the structural A/B plustest_export_shell_module_selector,test_writer_instance_attrs,test_export_shell_gemv_resave_4305,test_registered_module_plansandtest_moe_resave_preserves_experts_4589were rerun: 445 passed. CPU runs usedCUDA_VISIBLE_DEVICES=; GPU runs usedCUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=1:CPU files:
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_checktest_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_5809models/test_w4a_resave_roundtrip,models/test_w4a_native_writermodule_tree/test_registered_module_plans,test_save_dispatchSkips and what they leave unverified:
tests/models/test_w4a_native_writer.pyNVFP4 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.test_checkpoint_compatlm_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_identicallyfails the same way onorigin/mainand on the branch. Its fixture saves an OLMoE model without tokenizer files, and the loader's tokenizer-usability check raisesValueError: 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_auditkernel-geometry skips andtest_model_load_lock_4204free-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 26Bdiffusiongemma-26B-A4B-itcheckpoint. I stopped it after 10 minutes of CPU and did not run it.tests/test_diffusion_gemma_support.pycovers the DiffusionGemmaafter_make_quant/ base-module hooks instead.tests/test_docs_contract_refs.py::test_doc_python_example_runs[docs/measurement.md::3](NameError: texts) fails identically onorigin/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 fromgit show origin/main:gptqmodel/models/{loader,writer}.pyand execs them. It then compares them with the new selector, called both ways: as the loader (clsplus_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.MODEL_MAPentries × eachmodule_tree_overridesmethod. 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 raisesNotImplementedError.LocalModelLoaderfrom thetests/module_tree/test_shared_input_cpu_forward.pyconfigs, then defused.lm_head{off, on} × dynamic {none,-:.*down_proj+-:.*\.1\..*o_proj} × Optimum inclusions {none, set} × checkpoint {dense, quantizedembed_tokens/lm_head}.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) →saveagain (rs, which goes throughget_model_with_quantize). A cross check also has the branch reload and re-save the checkpoint thatorigin/mainquantized. Each comparison covers every safetensors key, dtype, shape and sha256 of the raw bytes, plus every JSON byte for byte.-:model\.layers\.1\.mlp\.down_projlm_head=Trueis 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.pypasses, 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_overridestree (Qwen3NextGPTQ/awq) is included in the structural A/B.Logic Flow Documentation
file:lineevidence.docs/repeats the diagrams, titled for the mechanism, and is linked fromREADME.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:#ffebee94ceaf77e)loader.py:3898-3903,writer.py:3210-3226_defuse_export_shellloader.py:1791-1802is_embeddings_module_quantizedloader.py:3937-3958,writer.py:3228-3254_select_export_shell_modulesloader.py:1805-1891loader.py:3961-4012,writer.py:3256-3303loader.py:4039,writer.py:3215declared/ layer prefixeswriter.py:3333-3342and3361-3370writer.py:3241-3258writer.py:3351-3354and3429-3432writer.py:3327-3331Review Requirements
Kernel Accuracy Requirements
Not applicable: no kernel, dispatch or fusion change. GPU A/B outputs are bit-identical.
Notes
name is not owner.lm_headidentity comparison in the "not quantized" log guard unchanged; it was in both copies. It only affects whetherlm_headis logged.🤖 Generated with Claude Code