Skip to content

refactor(lazy-turtle): one checkpoint-source reader replaces five copy-pasted shard read/concat blocks - #6415

Merged
Qubitium merged 1 commit into
mainfrom
refactor/lazy-turtle-one-source-reader
Nov 29, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/lazy-turtle-one-source-reader

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

LazyTurtle read checkpoint tensors through five copy-pasted blocks in gptqmodel/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 is structure.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 407298ad2 line numbers):

Duplicate origin/main location Now
Concat source, submodule materialization: shard lookup, missing-shard error, safe_open, MiMo decode, Qwen4 n-gram padding, assemble, concat error, shape check structure.py:4260-4324 _read_concat_checkpoint_source (structure.py:4176), called at :4406
Concat source, direct-meta param (same steps) structure.py:4609-4664 same helper, called at :4656
Concat source, direct-meta buffer (same steps, but no n-gram padding) structure.py:4765-4811 same helper, pad_qwen4_exp_ngram=(kind == "param") (:4667)
Single source, direct-meta param: shard lookup, error, decode, _transform_checkpoint_tensor, reshape error, shape-mismatch error structure.py:4680-4743 _checkpoint_shard_or_raise (:4145) + _read_transformed_checkpoint_tensor (:4244), called at :4676/:4689
Single source, direct-meta buffer (same steps) structure.py:4825-4888 same, through the merged param/buffer loop (:4644)
Grouped-shard path in _copy_checkpoint_tensors_into_submodule: decode, transform, reshape error, plus separate param and buffer shape-mismatch checks structure.py:4394-4423, :4440-4453, :4473-4486 _read_transformed_checkpoint_tensor on the already-open shard (:4480)
Param missing-shard error while grouping structure.py:4189-4204 _checkpoint_shard_or_raise (:4341)
Two identical buffer re-register branches (meta target / other-device target) structure.py:4488-4503 one elif (:4533)
  • _materialize_direct_meta_tensors is 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 append requires_grad, buffers do not.
  • _copy_checkpoint_tensors_into_submodule keeps its shard-grouped path, which opens each shard once. Its two identical buffer branches ("meta target" and "target on another device") both re-registered empty_like(..., device=device). They are merged into one elif with the same evaluation order.
  • No API, numerics or checkpoint-format change.

Deliberately out of scope (follow-up R7): the deepseek_v4 / qwen4_exp / qwen4_exp_text model_type checks in LazyTurtle are 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 with pad_qwen4_exp_ngram=(kind == "param") and does not unify it.

Assessment: this is not a reachable bug today. _is_qwen4_exp_ngram_embedding only matches *.ple.ple_embedding.ngram_embedding.weight under model_type qwen4_exp/qwen4_exp_text. In the Qwen4Exp port that tensor is an nn.Embedding parameter, 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;
Loading

Tests

  • Unit tests have been executed and passed.
  • I added a new simple/fast unit test for this change.

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.
# CPU, branch (gptqmodel.__file__ = <clone>/gptqmodel/__init__.py)
CUDA_VISIBLE_DEVICES="" python -P -m pytest -q tests/test_lazy_turtle_conversion_cache.py tests/test_lazy_turtle_conversion_mapping.py \
  tests/test_lazy_turtle_materialize_map.py tests/test_lazy_turtle_native_fp32.py tests/test_lazy_turtle_separate_expert_materialization.py \
  tests/test_lazy_turtle_shard_layout_warning.py tests/test_lazy_sync_packed_modules.py tests/test_lazy_native_fp32_materialization.py \
  tests/test_qwen4_exp_support.py tests/test_mimo_mixed_source.py tests/test_mimo_gptq_roundtrip.py tests/test_ernie4_5_vl_moe_local_port.py \
  tests/test_deepseek_v4_support.py tests/test_offload_files.py tests/test_qwen4_exp_exl3_contracts.py \
  tests/test_run_exit_recovery_contract_5060.py tests/test_cpu_lazy_transform_concurrency_4565.py
# 419 passed, 5 skipped (CUDA-gated: test_offload_files.py:979 x2, :2258, test_qwen4_exp_exl3_contracts.py:210 x2)

# The 5 CUDA-gated tests on an RTX 4090 (CUDA_VISIBLE_DEVICES=0)
python -P -m pytest -q tests/test_offload_files.py tests/test_qwen4_exp_exl3_contracts.py
# 94 passed, 0 skipped

bash format/check.sh   # ruff 0.14.2: All checks passed!

These results are after rebasing onto 407298ad2. The pre-rebase run on c32f2b346, 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.py passes every file:line and symbol citation check, including docs/cancelled-run-contract.md -> _copy_checkpoint_tensors_into_submodule. Its test_doc_python_example_runs subprocess 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)):

  1. materialize_submodule per decoder layer, then per top-level child.
  2. materialize_submodule(recurse=False) on every module.
  3. sync_all_meta.
  4. materialize_direct_meta_tensors on 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.

Case Result
Llama untied, single file (bf16 and fp32); rotary inv_freq/original_inv_freq non-persistent buffers IDENTICAL: 90 tensors x 2, 4/4 error messages each
Llama untied, 12 KB shards (bf16) IDENTICAL: 90 tensors, 4/4 errors
Qwen2 tied embeddings, single file (bf16) and sharded (fp16); lm_head.weight owned by model.embed_tokens.weight IDENTICAL: 114 tensors x 2, 4/4 errors
Qwen3-MoE, 6 KB shards (each expert's gate/up/down in different shard files) IDENTICAL: 186 tensors, 4/4 errors
OLMoE (tiny), 6 KB shards IDENTICAL: 186 tensors, 4/4 errors
DeepSeek-V4 hash_moe + compressed sparse attention (test fixture native_model), fp16, sharded IDENTICAL: 220 tensors, 4/4 errors
DeepSeek-V4 moe + sliding attention, bf16, sharded IDENTICAL: 156 tensors, 4/4 errors
Qwen4Exp outer (config from tests/test_qwen4_exp_support.py), n-gram shards in two files (real Concatenate converter) IDENTICAL: 404 tensors, 5 concat hits, 8/8 errors
Qwen4Exp with a short n-gram table (166 rows vs shell 168, so zero padding applies on all four paths), bf16 and fp32 IDENTICAL: 404 tensors x 2, 5 concat hits, 8/8 errors

The comparer is sensitive. A mutant with the n-gram padding disabled reported DIFF on 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_submodule and _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, with torch.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.

  • 104 of 106 files produced a trace on both revisions. 103 of those pairs are IDENTICAL on the first pass: 2519 test outcomes, 7793 LazyTurtle calls, 54,092 tensor snapshots bit-equal, 18 raised errors with equal text.
  • test_lazy_native_fp32_materialization.py: the first run differed only in AWQ qweight/scales of 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-timed test_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.
  • Pre-existing failures, identical on both revisions: test_deepseek_v2_local_port.py (12) and test_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) and dtype=bfloat16. The comparer checks every saved tensor bit-for-bit plus every json file (_name_or_path excluded).

Model origin/main branch Saved checkpoint
Qwen2.5-0.5B-Instruct 284 s, peak 463 MiB 455 s*, peak 467 MiB BIT-IDENTICAL: 794 tensors (438.0 MiB), 5 json files
OLMoE-1B-7B-0924 (3 shards; layers 5 and 11 have experts split across shards) 286 s, peak 3016 MiB 239 s, peak 3038 MiB BIT-IDENTICAL: 12,627 tensors (3742.8 MiB), 5 json files

*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 onto 407298ad2 had no conflicts and does not change this diff. The CPU materialization A/B was rerun on 407298ad2 vs 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 first shell_module_materialize module_path is model.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

  • This change does not alter a major logic flow. No decision, resolution order, cache policy or tensor lifecycle changes; it deduplicates the readers. The new-flow diagram and the old/new file:line table are above for review. A docs/ page is not added because docs/lazy-checkpoint-materialization.md, docs/cancelled-run-contract.md and docs/fp8-save-offload.md still describe the code accurately: both the concatenated and grouped-shard branches of _copy_checkpoint_tensors_into_submodule remain.

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.

Notes

  • One latent asymmetry is kept as-is and is not touched here. In _copy_checkpoint_tensors_into_submodule, a concat-sourced buffer that is already materialized on another device is copy_'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.
  • Follow-up R7: definitions declare checkpoint aliases and zero-pad rows instead of model_type checks in LazyTurtle.

🤖 Generated with Claude Code

…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
Qubitium marked this pull request as ready for review November 29, 2026 15:24
@Qubitium
Qubitium merged commit 649f5da into main Nov 29, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/lazy-turtle-one-source-reader branch November 29, 2026 15:24
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]>
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