Repository navigation
refactor(lazy-turtle): one checkpoint-source reader replaces five copy-pasted shard read/concat blocks - #6415
Merged
Conversation
…y-pasted shard read/concat blocks LazyTurtle read checkpoint tensors through five near-identical blocks: three concat-source copies (submodule materialization, direct-meta param, direct-meta buffer) that each looked up the shard, raised the missing-shard error, opened the shard, decoded MiMo storage, applied the Qwen4 n-gram zero-padding, assembled the parts and checked the shape; and single-source copies that each decoded, transformed, and raised the reshape and shape-mismatch errors. Replace them with three helpers: - `_checkpoint_shard_or_raise`: shard lookup plus the shared missing-shard error. - `_read_concat_checkpoint_source`: read, decode, pad, assemble and shape-check one concatenated target. - `_read_transformed_checkpoint_tensor`: decode and transform one tensor from an open shard, raising the reshape or shape-mismatch error. `_materialize_direct_meta_tensors` becomes one loop over (param, buffer). `_copy_checkpoint_tensors_into_submodule` keeps its shard-grouped path, which opens each shard once. Its two identical buffer re-register branches (meta target, other-device target) are merged. Behavior is unchanged. Error text, error order, cache keys, dtypes and devices stay the same. Direct-meta buffers still skip the Qwen4 n-gram padding (`pad_qwen4_exp_ngram=(kind == "param")`). The table that pads is an embedding param, so no buffer reaches that branch today. The deepseek_v4 and qwen4_exp model_type checks are left for a follow-up. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Qubitium
marked this pull request as ready for review
November 29, 2026 15:24
12 tasks done
Qubitium
added a commit
that referenced
this pull request
Nov 29, 2026
…o-pad rows instead of model_type checks (#6437) 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
LazyTurtleread checkpoint tensors through five copy-pasted blocks ingptqmodel/utils/structure.py. This PR replaces them with one checkpoint-source reader: three small helpers that every materialization path now calls. It is behavior-preserving. Tensors, dtypes, devices, cache keys, error text and error order are all unchanged.git diff --shortstat:2 files changed, 391 insertions(+), 446 deletions(-). That isstructure.py+266/-446 (-180 net) plus a 125-line targeted test.No issue is fixed. This is a debloat refactor (R6 of the LazyTurtle debloat map).
What Changed
The removed duplicates (origin/main
407298ad2line numbers):safe_open, MiMo decode, Qwen4 n-gram padding, assemble, concat error, shape checkstructure.py:4260-4324_read_concat_checkpoint_source(structure.py:4176), called at:4406structure.py:4609-4664:4656structure.py:4765-4811pad_qwen4_exp_ngram=(kind == "param")(:4667)_transform_checkpoint_tensor, reshape error, shape-mismatch errorstructure.py:4680-4743_checkpoint_shard_or_raise(:4145) +_read_transformed_checkpoint_tensor(:4244), called at:4676/:4689structure.py:4825-4888:4644)_copy_checkpoint_tensors_into_submodule: decode, transform, reshape error, plus separate param and buffer shape-mismatch checksstructure.py:4394-4423,:4440-4453,:4473-4486_read_transformed_checkpoint_tensoron the already-open shard (:4480)structure.py:4189-4204_checkpoint_shard_or_raise(:4341)structure.py:4488-4503elif(:4533)_materialize_direct_meta_tensorsis now one loop over(param, buffer). Params still sync before buffers, and each kind's names are listed when its pass starts. Cache keys are the same tuples as before: params appendrequires_grad, buffers do not._copy_checkpoint_tensors_into_submodulekeeps its shard-grouped path, which opens each shard once. Its two identical buffer branches ("meta target" and "target on another device") both re-registeredempty_like(..., device=device). They are merged into oneelifwith the same evaluation order.Deliberately out of scope (follow-up R7): the
deepseek_v4/qwen4_exp/qwen4_exp_textmodel_typechecks inLazyTurtleare untouched.Preserved divergence: direct-meta buffers skip the Qwen4 n-gram padding
On origin/main, the direct-meta buffer concat block never called
_append_qwen4_exp_ngram_padding. The other two concat blocks, including the submodule-path buffer branch, did call it. This PR keeps that exactly withpad_qwen4_exp_ngram=(kind == "param")and does not unify it.Assessment: this is not a reachable bug today.
_is_qwen4_exp_ngram_embeddingonly matches*.ple.ple_embedding.ngram_embedding.weightundermodel_typeqwen4_exp/qwen4_exp_text. In the Qwen4Exp port that tensor is annn.Embeddingparameter, so no buffer reaches the padding branch. R7, which moves the padding rule into declared definition data, can decide whether to drop the flag.New flow
flowchart TD S["materialize_submodule"] --> C["_copy_checkpoint_tensors_into_submodule"] D["materialize_direct_meta_tensors / sync_all_meta"] --> M["_materialize_direct_meta_tensors<br/>one loop: param then buffer"] C --> R{"_resolve_concat_checkpoint_tensor_sources"} M --> R R -- "concat source" --> CR["_read_concat_checkpoint_source"] R -- "single source" --> SH["_checkpoint_shard_or_raise"] CR --> SH SH --> OPEN["safe_open shard<br/>grouped once per shard in the submodule path"] OPEN -- "concat parts" --> DEC["_decode_mimo_checkpoint_tensor"] DEC --> PAD["_append_qwen4_exp_ngram_padding<br/>skipped for direct-meta buffers"] PAD --> ASM["_assemble_checkpoint_tensor_parts"] ASM --> SHAPE{"shape == target?"} OPEN -- "single tensor" --> RT["_read_transformed_checkpoint_tensor<br/>decode + _transform_checkpoint_tensor"] RT --> SHAPE2{"transform ok and shape == target?"} SHAPE -- yes --> PUB["publish param / buffer<br/>unchanged code"] SHAPE2 -- yes --> PUB SH -- "no shard" --> E1["RuntimeError: resolved to a missing shard"] ASM -- "cat fails" --> E2["RuntimeError: could not be concatenated"] SHAPE -- no --> E3["RuntimeError: concatenated shape does not match"] SHAPE2 -- "transform None" --> E4["RuntimeError: could not be reshaped"] SHAPE2 -- "shape differs" --> E5["RuntimeError: shape does not match transformed tensor"] classDef failure fill:#ffe8e8,stroke:#b30000,color:#111; class E1,E2,E3,E4,E5 failure;Tests
New tests in
tests/test_lazy_turtle_conversion_mapping.py. They pass on both origin/main and this branch, so they pin current behavior:test_lazy_turtle_every_path_reads_concat_and_direct_sources_across_shards_identically[submodule|leaves|direct|sync_all_meta]: a fused gate/up param and a fused buffer, with their halves in two different shard files, plus one direct param. All four materialization paths produce bit-exact bf16 values on CPU with unchanged buffer persistence.test_lazy_turtle_source_shape_errors_name_the_phase_and_checkpoint[concat|direct × submodule|direct]: exact error strings for the concat shape mismatch and the single-source reshape failure, in both phases.These results are after rebasing onto
407298ad2. The pre-rebase run onc32f2b346, before the 8 new tests, was 411 passed with the same 5 CUDA skips. The skips leave nothing unverified: those 5 tests pass on GPU.tests/test_docs_contract_refs.pypasses everyfile:lineand symbol citation check, includingdocs/cancelled-run-contract.md -> _copy_checkpoint_tensors_into_submodule. Itstest_doc_python_example_runssubprocess cases fail on unrelated pages (quantization-guide, thread-caps, supported-models and others) on origin/main as well: 15 failures on origin/main, 4 on the branch, varying with machine load, and the branch's 4 are a subset of origin/main's.Structural A/B 1: LazyTurtle materialization dumps (CPU, origin/main vs branch)
Each tiny deterministic checkpoint is built once and read by both revisions. Each revision materializes it four ways, each from a fresh lazy load (
GPTQModel.load(..., offload_to_disk=True)):materialize_submoduleper decoder layer, then per top-level child.materialize_submodule(recurse=False)on every module.sync_all_meta.materialize_direct_meta_tensorson every module.Every param and buffer is then dumped with class, dtype, shape, device, requires_grad, persistence, tie owner and raw bytes. Injected failures are recorded too: a missing shard and a bad target shape, each on a single source and on a concat source, through both phases.
inv_freq/original_inv_freqnon-persistent bufferslm_head.weightowned bymodel.embed_tokens.weighthash_moe+ compressed sparse attention (test fixturenative_model), fp16, shardedmoe+ sliding attention, bf16, shardedtests/test_qwen4_exp_support.py), n-gram shards in two files (realConcatenateconverter)The comparer is sensitive. A mutant with the n-gram padding disabled reported
DIFFon the short-table case.Structural A/B 2: traced test suite (CPU, origin/main vs branch)
A pytest plugin wraps
materialize_submodule,materialize_direct_meta_tensors,sync_all_meta,_copy_checkpoint_tensors_into_submoduleand_materialize_direct_meta_tensors. After every call it snapshots the target module's tensors (meta and raw bytes) and the raised error. It also records every test outcome. It ran over 106 test files that touch LazyTurtle, on both revisions, withtorch.manual_seed(1234)per test. These files cover the MiMo FP8 decode, Ernie text/vision experts, MergeModulelist, fused dense gate_up, MiniMax-M3 shared experts, DeepSeek-V4 w123, and Qwen4 root n-gram padding fixtures.test_lazy_native_fp32_materialization.py: the first run differed only in AWQqweight/scalesof one expert. origin/main also differs from itself the same way (base vs base: DIFF, only those packed tensors). On a rerun, base vs branch was IDENTICAL (184 calls). This is AWQ quantizer nondeterminism under CPU load, not a LazyTurtle read.test_run_exit_recovery_contract_5060.py: the first run differed in call count inside the thread-timedtest_pack_fault_leaves_no_half_built_kernel[gptq-offload]. Two reruns: base vs base, branch vs branch and base vs branch all IDENTICAL (458 calls).test_checkpoint_quantization.py(42 tests, 1693 in-process calls, 16,109 snapshots) is included in the 103 identical files. Its subprocess-recovery children are not traced.test_deepseek_v2_local_port.py(12) andtest_checkpoint_method_compatibility.py(2). They fail in the tokenizer usability check before LazyTurtle runs.tests/models/*(real-model gated) was not traced.GPU A/B: full quantize with
offload_to_disk(RTX 4090,CUDA_VISIBLE_DEVICES=0)Both revisions use the same script, seed, 128 synthetic calibration rows,
QuantizeConfig(bits=4, group_size=128, device="cuda:0", offload_to_disk=True)anddtype=bfloat16. The comparer checks every saved tensor bit-for-bit plus every json file (_name_or_pathexcluded).*Runs overlapped with CPU-heavy trace jobs, so wall times are not comparable. The GPU A/B ran on the pre-rebase base
c32f2b346(base vs this commit on top of it). The rebase onto407298ad2had no conflicts and does not change this diff. The CPU materialization A/B was rerun on407298ad2vs the rebased branch: all 12 cases IDENTICAL.Lazy-load smoke test (
gptqmodel-lazy-load-smoke-testing)Tiny CPU Llama:
Loader: using checkpoint-backed lazy turtle source. The firstshell_module_materializemodule_pathismodel.layers.0. The first layer has no meta params and no NaN. Quantize, save, reload and generate all succeed ([[2, 5, 11, 67, 26, 1, 87]]). SMOKE PASS.Measured Impact
Not applicable: not a claimed issue. Peak VRAM is unchanged in the GPU A/B above.
Model Support / Module Plan
Not applicable: no
MODEL_MAP, alias, definition or module-plan change.AWQ onboarding safety
Not applicable: no model onboarding and no AWQ grouping, search, replay or fold change.
Logic Flow Documentation
file:linetable are above for review. Adocs/page is not added becausedocs/lazy-checkpoint-materialization.md,docs/cancelled-run-contract.mdanddocs/fp8-save-offload.mdstill describe the code accurately: both the concatenated and grouped-shard branches of_copy_checkpoint_tensors_into_submoduleremain.Review Requirements
Kernel Accuracy Requirements
Not applicable: no kernel, dispatch or fusion change.
Notes
_copy_checkpoint_tensors_into_submodule, a concat-sourced buffer that is already materialized on another device iscopy_'d in place. A grouped single-source buffer is re-registered on the target device. No current model has a concat-sourced buffer, so this is not reachable today.model_typechecks in LazyTurtle.🤖 Generated with Claude Code