Skip to content

refactor(lazy-turtle): definitions declare checkpoint aliases and zero-pad rows instead of model_type checks - #6437

Merged
Qubitium merged 1 commit into
mainfrom
refactor/lazy-turtle-declared-aliases
Nov 29, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/lazy-turtle-declared-aliases

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

LazyTurtle had three per-model branches keyed on config.model_type strings: 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 on BaseQModel, the loader passes them to LazyTurtle, 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.
  • DeepSeekV4QModel declares ((r"\.compressor\.indexer\.q_b_proj\.", ".indexer.compressor.wq_b."),). Qwen4ExpQModel declares the root-PLE regex and (".ple.ple_embedding.ngram_embedding.weight",). Qwen4ExpTextQModel inherits both.
  • LazyTurtle.__init__ / maybe_create take checkpoint_aliases=() and zero_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.
  • Deleted from utils/structure.py: _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, 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-gram nn.Embedding weight, which is a parameter in both Qwen4Exp shells. No buffer matches it (asserted in the test below), the module is ple:! (never quantized), and only Qwen4Exp declares a suffix. The A/B shows identical direct-meta results on the short-table fixtures.
  • The 3× "ErnieFuseAndSplitTextVisionExperts" in converter.operation_names checks become one _LazyWeightConverter.is_ernie_text_vision_experts property. The Ernie expert-index math is unchanged.
  • The Qwen4 root alias is a single regex. Like the old component parser, it rewrites only the leftmost layers.N.ple.ple_embedding.<x> segment. It drops ple_embedding. only before ngram_embedding (end or .), handles module paths ending in ngram_embedding, and leaves ...ple_embedding with 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.
  • The aliases stay out of HF_CONVERSION_MAP_REVERSED, because that map has other consumers (convert_hf_checkpoint_key, the save paths).
  • No public API change; MODEL_MAP, module_tree and fusable are unchanged.

Tests

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

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:

    • the set of declaring keys is exactly {deepseek_v4, qwen4_exp, qwen4_exp_text};
    • hand-written expected rewrites hold for those three keys, and no rewrite happens for any other key;
    • a short n-gram table is zero-padded only for the Qwen4 keys.

    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_shards now 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 pass definition= 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_shape fails, so it detects a missing declaration.

Red evidence: each mutant applied through a pytest plugin fails the intended test:

Mutant Failing test
DeepSeek alias removed the new MODEL_MAP test
Qwen4 alias removed the new test and the existing root-n-gram padding test
first-draft two-rule Qwen4 alias the new test
Qwen4 suffix removed the new test and the existing padding test
buffer suffix added (.ple.ple_embedding.layer_multipliers) the Qwen4 lazy test
# GPU 0 visible (CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=0); gptqmodel.__file__ = <clone>/gptqmodel/__init__.py
python -P -m pytest -q -rs -n 8 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_qwen4_exp_exl3_contracts.py tests/test_qwen4_exp_support.py \
  tests/test_deepseek_v4_local_port.py tests/test_deepseek_v4_support.py tests/test_ernie4_5_vl_moe_local_port.py \
  tests/test_ernie4_5_vl_moe_offload_hook.py tests/module_tree/test_deepseek_v4_local_port.py \
  tests/module_tree/test_ernie4_5_vl_moe_local_port.py tests/module_tree/test_ernie_expert_projections.py \
  tests/module_tree/test_ernie_vl_moe_expert_coverage.py tests/module_tree/test_registered_module_plans.py
# 754 passed, 0 skipped

# Wider sweep, CPU only (CUDA_VISIBLE_DEVICES=""): every test file that mentions LazyTurtle/turtle,
# deepseek_v4 or qwen4_exp, plus the 106 files from the #6415 trace set, excluding real-model tests/models/* (131 files)
python -P -m pytest -q -rs -n 12 $(cat wide_tests_nomodels.txt)
# 3112 passed, 880 skipped, 2 xfailed, 0 failed

bash format/check.sh   # ruff 0.14.2: All checks passed!
python -P -m pytest -q tests/test_docs_contract_refs.py -k "lazy or symbol or line or ref"   # 234 passed

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 like loader.py. Each checkpoint is materialized four ways: per-layer materialize_submodule, recurse=False on every module, sync_all_meta, and materialize_direct_meta_tensors on 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:

Case Result
Llama untied single (bf16, fp32), sharded (bf16) IDENTICAL: 90 tensors × 3, 4/4 errors
Qwen2 tied single (bf16), sharded (fp16) IDENTICAL: 114 tensors × 2, 4/4 errors
Qwen3-MoE, OLMoE (6 KB shards) IDENTICAL: 186 tensors × 2, 4/4 errors
DeepSeek-V4 hash_moe + compressed sparse attention (fp16), moe + sliding (bf16) IDENTICAL: 220 and 156 tensors, 4/4 errors
Qwen4Exp outer, n-gram shards in two files IDENTICAL: 404 tensors, 5 concat hits, 8/8 errors
Qwen4Exp outer, short n-gram table (166 vs 168 rows; padding on all 4 paths), bf16 and fp32 IDENTICAL: 404 tensors × 2, 8/8 errors
new Qwen4ExpText (qwen4_exp_text), sharded IDENTICAL: 314 tensors, 5 concat hits, 8/8 errors
new Qwen4Exp outer, root-keyed PLE (model.language_model.ngram_embedding.shard_*, ...ple_embedding.*) + short table IDENTICAL: 404 tensors, 5 concat hits, 8/8 errors
new Qwen4ExpText, root-keyed PLE (model.ngram_embedding.shard_*) + short table, fp32 IDENTICAL: 314 tensors, 5 concat hits, 8/8 errors

The 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.py runs on both revisions and dumps JSON; cand_compare.py diffs every field:

  1. 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 zero-pad decision for 11 synthetic part/target shapes per tensor.

    The edge names cover module paths ending in ngram_embedding, empty components, look-alike segments, two ple_embedding segments, and DeepSeek q_b_proj variants.

  2. 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) and qwen4_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_path excluded).

Model group_size Saved checkpoint
Qwen2.5-0.5B-Instruct (no declarations, control) 128 BIT-IDENTICAL: 794 tensors (438.0 MiB), 5 json files
Tiny DeepSeek-V4 hash_moe fixture (declared indexer alias) -1 BIT-IDENTICAL: 94 tensors, 5 json files
Tiny Qwen4ExpText, root-keyed PLE + short n-gram table (declared alias + zero padding) -1 BIT-IDENTICAL: 170 tensors, 5 json files. The saved ngram_embedding.weight is (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, Qwen4ExpQModel and Qwen4ExpTextQModel gain LazyTurtle checkpoint-name metadata only. module_tree, roles, tags and fusable are unchanged, and tests/module_tree/test_registered_module_plans.py plus tests/module_tree/test_deepseek_v4_local_port.py pass (in the command above).

AWQ onboarding safety

Not applicable: no AWQ grouping, search, replay or fold change.

Logic Flow Documentation

  • The required diagrams and docs page are included below.
  • New-flow Mermaid diagram uses real symbol names.
  • The replaced mechanism is tabulated with file:line evidence.
  • Failure paths are marked.
  • docs/lazy-checkpoint-materialization.md (linked from docs/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;
Loading
Decision origin/main (gptqmodel/utils/structure.py) This PR
DeepSeek-V4 composed indexer alias _deepseek_v4_compressor_indexer_alias L3023, gated self._model_type != "deepseek_v4" L3026 (_model_type set L1294-1296) DeepSeekV4QModel.lazy_checkpoint_aliases (definitions/deepseek_v4.py:1458), applied at structure.py:3017
Qwen4 root PLE alias _qwen4_exp_root_checkpoint_alias L3034, gated model_type not in {"qwen4_exp","qwen4_exp_text"} L3037, called L3002-3007 Qwen4ExpQModel.lazy_checkpoint_aliases (definitions/qwen4_exp.py:42), same loop
Qwen4 n-gram zero padding _is_qwen4_exp_ngram_embedding L3091 (model_type gate L3096), _can_zero_pad_qwen4_exp_ngram_embedding L3102, _append_qwen4_exp_ngram_padding L3120 Qwen4ExpQModel.lazy_zero_pad_row_suffixes (qwen4_exp.py:51), _append_zero_pad_rows structure.py:3048
Direct-meta buffer skip pad_qwen4_exp_ngram L4187, L4210, =(kind == "param") L4667 removed; the suffix names a parameter only
Ernie many-to-many op string tests L3070, L3323, L3413 _LazyWeightConverter.is_ernie_text_vision_experts structure.py:901
Who supplies the data config.model_type inside LazyTurtle loader.py:3193-3194, definitions/deepseek_v4.py:412 (MTP auxiliary)

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 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.py and the DeepSeek-V4 MTP auxiliary are the only maybe_create callers.
  • The loader reads the tuples with getattr(cls, ..., ()), matching its getattr(cls, "module_tree", None) beside it, because test doubles that are not BaseQModel subclasses go through this path.
  • Unchanged scope: MiMo decode (config-driven) and the Ernie expert-index math.

🤖 Generated with Claude Code

…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]>
@Qubitium
Qubitium marked this pull request as ready for review November 29, 2026 20:07
@Qubitium
Qubitium merged commit 2d504f4 into main Nov 29, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/lazy-turtle-declared-aliases branch November 29, 2026 20:07
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