Repository navigation
refactor(lazy-turtle): definitions declare checkpoint aliases and zero-pad rows instead of model_type checks - #6437
Merged
Conversation
…o-pad rows instead of model_type checks LazyTurtle carried three per-model branches keyed on `config.model_type`: the composed DeepSeek-V4 `compressor.indexer.q_b_proj` -> `indexer.compressor.wq_b` alias, the Qwen4Exp root PLE checkpoint alias (`layers.N.ple.ple_embedding.*` -> root `ngram_embedding.*` / `ple_embedding.*`), and the Qwen4Exp n-gram zero padding. The variation is data, so the definitions now declare it: - `BaseQModel.lazy_checkpoint_aliases`: `(regex, replacement)` rewrites tried once on every runtime->checkpoint candidate. - `BaseQModel.lazy_zero_pad_row_suffixes`: tensor-name suffixes whose shorter concatenated checkpoint table is zero-filled to the shell's rows. The loader and the DeepSeek-V4 MTP auxiliary pass them to `LazyTurtle`, which drops `_model_type`, `_deepseek_v4_compressor_indexer_alias`, `_qwen4_exp_root_checkpoint_alias`, `_is_qwen4_exp_ngram_embedding` and `_can_zero_pad_qwen4_exp_ngram_embedding`; `_append_qwen4_exp_ngram_padding` becomes the generic `_append_zero_pad_rows`. The Qwen4 root alias is one regex with the same leftmost-match semantics as the old component parser. The `pad_qwen4_exp_ngram=(kind == "param")` flag left by #6415 is dropped: it only skipped padding for a direct-meta buffer whose name ends with the declared suffix, and the suffix names the n-gram `nn.Embedding` weight, a parameter, in both Qwen4Exp shells (now asserted in the Qwen4 lazy test). The three `"ErnieFuseAndSplitTextVisionExperts" in operation_names` tests become one `_LazyWeightConverter.is_ernie_text_vision_experts` property. No behavior change: candidate lists, resolved names, concat sources and zero-pad decisions are identical to origin/main for every MODEL_MAP key and for real DeepSeek-V4, Qwen4Exp, Qwen4ExpText, Llama, Qwen2, Qwen3-MoE and OLMoE shells, and LazyTurtle materialization is bit-identical. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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
LazyTurtle had three per-model branches keyed on
config.model_typestrings: the composed DeepSeek-V4 indexer alias, the Qwen4Exp root PLE checkpoint alias, and the Qwen4Exp n-gram zero padding. These differ only in data, so each definition now declares two plain tuples onBaseQModel, the loader passes them toLazyTurtle, and LazyTurtle has no model-type checks left. The three Ernie op-name string tests now use one property.No behavior change. Library diff: +74 / −122 (net −48) in
gptqmodel/. With the new tests and the short docs section:8 files changed, 173 insertions(+), 122 deletions(-).What Changed
BaseQModel.lazy_checkpoint_aliases: Tuple[Tuple[str, str], ...] = ():(regex, replacement)rewrites that LazyTurtle applies once to every runtime->checkpoint candidate, after the conversion-map renamings.BaseQModel.lazy_zero_pad_row_suffixes: Tuple[str, ...] = (): tensor-name suffixes whose concatenated checkpoint table may have fewer rows than the shell's. The missing rows are zero-filled.DeepSeekV4QModeldeclares((r"\.compressor\.indexer\.q_b_proj\.", ".indexer.compressor.wq_b."),).Qwen4ExpQModeldeclares the root-PLE regex and(".ple.ple_embedding.ngram_embedding.weight",).Qwen4ExpTextQModelinherits both.LazyTurtle.__init__/maybe_createtakecheckpoint_aliases=()andzero_pad_row_suffixes=(). The patterns are compiled once. The loader (loader.py) and the DeepSeek-V4 MTP auxiliary (its shell config is a copy of the V4 config, so the old check applied there too) pass the definition's tuples.utils/structure.py:_model_type,_deepseek_v4_compressor_indexer_alias,_qwen4_exp_root_checkpoint_alias,_is_qwen4_exp_ngram_embeddingand_can_zero_pad_qwen4_exp_ngram_embedding._append_qwen4_exp_ngram_paddingbecomes the generic_append_zero_pad_rows, with the same checks in the same order.pad_qwen4_exp_ngram=(kind == "param")(from refactor(lazy-turtle): one checkpoint-source reader replaces five copy-pasted shard read/concat blocks #6415) is dropped. It skipped padding only for a direct-meta buffer whose name ends with the declared suffix. That suffix names the n-gramnn.Embeddingweight, which is a parameter in both Qwen4Exp shells. No buffer matches it (asserted in the test below), the module isple:!(never quantized), and only Qwen4Exp declares a suffix. The A/B shows identical direct-meta results on the short-table fixtures."ErnieFuseAndSplitTextVisionExperts" in converter.operation_nameschecks become one_LazyWeightConverter.is_ernie_text_vision_expertsproperty. The Ernie expert-index math is unchanged.layers.N.ple.ple_embedding.<x>segment. It dropsple_embedding.only beforengram_embedding(end or.), handles module paths ending inngram_embedding, and leaves...ple_embeddingwith no child untouched. A first draft with two rules differed on names containing two such segments. The A/B caught that difference, and the single rule removes it.HF_CONVERSION_MAP_REVERSED, because that map has other consumers (convert_hf_checkpoint_key, the save paths).MODEL_MAP,module_treeandfusableare unchanged.Tests
New or extended tests:
tests/test_lazy_turtle_conversion_mapping.py::test_lazy_turtle_applies_only_the_declared_checkpoint_aliases_of_each_definition: for every MODEL_MAP key (210), it opens a LazyTurtle with that definition's declared tuples and checks the following:{deepseek_v4, qwen4_exp, qwen4_exp_text};The expected values were checked against origin/main's model_type-gated code, with the loader's
config.model_type=<key>: 210 keys × 10 probe names + the pad check, 0 mismatches.tests/test_qwen4_exp_support.py::test_qwen4_exp_outer_lazy_materialization_loads_ple_shardsnow checks that the declared suffix matches exactly one parameter (model.language_model.layers.1.ple.ple_embedding.ngram_embedding.weight) and no buffer. It also passes the declared tuples, as the loader does.The existing LazyTurtle tests that build turtles over fake
model_type="deepseek_v4"/"qwen4_exp"/"qwen4_exp_text"shells now passdefinition=to_build_lazy_turtle, which forwards the declared tuples as the loader does. Without that,test_lazy_turtle_pads_qwen4_text_root_ngram_shards_to_shell_shapefails, so it detects a missing declaration.Red evidence: each mutant applied through a pytest plugin fails the intended test:
.ple.ple_embedding.layer_multipliers)Structural A/B 1: LazyTurtle materialization dumps (CPU, origin/main vs branch)
This reuses the #6415 harness. Every revision opens each tiny deterministic checkpoint through the loader (
GPTQModel.load(..., offload_to_disk=True)), or through a mirror of the loader's offload branch for Qwen4 fixtures that have no processor files. The mirror passes the declared tuples exactly likeloader.py. Each checkpoint is materialized four ways: per-layermaterialize_submodule,recurse=Falseon every module,sync_all_meta, andmaterialize_direct_meta_tensorson every module. The dump records every param and buffer with class, dtype, shape, device, requires_grad, persistence, tie owner and raw bytes, plus injected missing-shard and bad-shape errors. The original 12 cases are kept, and 3 Qwen4 cases are added that exercise the declared alias and padding:qwen4_exp_text), shardedmodel.language_model.ngram_embedding.shard_*,...ple_embedding.*) + short tablemodel.ngram_embedding.shard_*) + short table, fp32The harness is sensitive. A branch run whose Qwen4 mirror did not pass the declared tuples reported DIFF on all three short/root cases: the shape-mismatch error and meta tensors left behind.
Structural A/B 2: candidate lists and the MODEL_MAP attribute A/B (CPU, origin/main vs branch)
cand_ab.pyruns on both revisions and dumps JSON;cand_compare.pydiffs every field:Real shells (11 fixtures: Llama, Qwen2, Qwen3-MoE, OLMoE, both DeepSeek-V4 variants, three Qwen4Exp and two Qwen4ExpText) are opened as the loader opens them. For every param, buffer and module path, plus 50 random names and 32 edge names, the script records:
_all_runtime_to_checkpoint_candidates(exact list and order);_runtime_to_checkpoint_alias_candidates;_resolve_checkpoint_tensor_name;_resolve_concat_checkpoint_tensor_sources;The edge names cover module paths ending in
ngram_embedding, empty components, look-alike segments, twople_embeddingsegments, and DeepSeekq_b_projvariants.Every MODEL_MAP key (210): a LazyTurtle opened with
config.model_type=<key>, which is what origin/main gated on, and the key's definition tuples on the branch. Over 617 probe names (all the shell names above plus edges and random names), the script records every rewrite and the zero-pad decisions.Result: IDENTICAL. Only
deepseek_v4(4 probes),qwen4_exp(26) andqwen4_exp_text(26) rewrite anything, on both revisions, and only the two Qwen4 keys pad. Mutants report DIFF: two-rule Qwen4 alias (24 diffs), DeepSeek alias removed (24), Qwen4 suffix removed (69).GPU A/B: full quantize with
offload_to_disk(GPU 0)Same script, seed, 128 synthetic calibration rows,
QuantizeConfig(bits=4, device="cuda:0", offload_to_disk=True),dtype=bfloat16. The comparison covers every saved tensor bit-for-bit plus every json file (_name_or_pathexcluded).ngram_embedding.weightis (168, 4) with 2 zero rows.Skips: the focused command has none. The wider CPU sweep's 880 skips are CUDA-, accelerator- or opt-in-gated (
CUDA required,requires NVIDIA SM...,-m checkpoint_recovery, ...) and are not counted as validation. GPU coverage of this change comes from the focused set (run with GPU 0) and the GPU A/B below.tests/models/*real-model tests were not run.Measured Impact
Not applicable: no numerics or performance change is intended, and the A/Bs above are bit-identical.
Model Support / Module Plan
Not applicable for new models.
DeepSeekV4QModel,Qwen4ExpQModelandQwen4ExpTextQModelgain LazyTurtle checkpoint-name metadata only.module_tree, roles, tags andfusableare unchanged, andtests/module_tree/test_registered_module_plans.pyplustests/module_tree/test_deepseek_v4_local_port.pypass (in the command above).AWQ onboarding safety
Not applicable: no AWQ grouping, search, replay or fold change.
Logic Flow Documentation
file:lineevidence.docs/lazy-checkpoint-materialization.md(linked fromdocs/README.md) has a short new section with the same diagram.flowchart TD A["BaseQModel.lazy_checkpoint_aliases<br/>lazy_zero_pad_row_suffixes"] --> B["LazyTurtle.maybe_create"] B --> C["_runtime_to_checkpoint_alias_candidates:<br/>renamings, then declared rewrites"] B --> D["_read_concat_checkpoint_source"] D --> E{"dim 0, declared suffix,<br/>fewer rows than shell?"} E -- Yes --> F["append zero rows"] E -- No --> G["assemble parts as read"] F --> H{"shape equals shell?"} G --> H H -- No --> X["RuntimeError: concatenated shape mismatch"] classDef failure fill:#ffe8e8,stroke:#b30000,color:#111; class X failure;gptqmodel/utils/structure.py)_deepseek_v4_compressor_indexer_aliasL3023, gatedself._model_type != "deepseek_v4"L3026 (_model_typeset L1294-1296)DeepSeekV4QModel.lazy_checkpoint_aliases(definitions/deepseek_v4.py:1458), applied atstructure.py:3017_qwen4_exp_root_checkpoint_aliasL3034, gatedmodel_type not in {"qwen4_exp","qwen4_exp_text"}L3037, called L3002-3007Qwen4ExpQModel.lazy_checkpoint_aliases(definitions/qwen4_exp.py:42), same loop_is_qwen4_exp_ngram_embeddingL3091 (model_type gate L3096),_can_zero_pad_qwen4_exp_ngram_embeddingL3102,_append_qwen4_exp_ngram_paddingL3120Qwen4ExpQModel.lazy_zero_pad_row_suffixes(qwen4_exp.py:51),_append_zero_pad_rowsstructure.py:3048pad_qwen4_exp_ngramL4187, L4210,=(kind == "param")L4667_LazyWeightConverter.is_ernie_text_vision_expertsstructure.py:901config.model_typeinside LazyTurtleloader.py:3193-3194,definitions/deepseek_v4.py:412(MTP auxiliary)Review Requirements
Kernel Accuracy Requirements
Not applicable: no kernel change.
Notes
LazyTurtle(...)built directly (outside the loader) now gets no model-specific aliases unless it passes the tuples. Tests that built fake DeepSeek-V4/Qwen4 turtles were updated. No other library call site builds a turtle for these models:loader.pyand the DeepSeek-V4 MTP auxiliary are the onlymaybe_createcallers.getattr(cls, ..., ()), matching itsgetattr(cls, "module_tree", None)beside it, because test doubles that are notBaseQModelsubclasses go through this path.🤖 Generated with Claude Code