Skip to content

refactor(loader): one direct-CPU build, seqlen and tokenizer helper for both load paths - #6457

Merged
Qubitium merged 1 commit into
mainfrom
refactor/loader-direct-cpu-build
Nov 30, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/loader-direct-cpu-build

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

A behavior-preserving debloat of gptqmodel/models/loader.py. Logic that was copied between the load paths now lives in three helpers:

  • _direct_cpu_build handles the two direct-to-CPU source builds in the from_pretrained quantize path: the no-offload load and the meta-shell fallback.
  • _SEQ_LEN_KEYS and _set_model_seqlen replace the sequence-length lookup that was copied into from_pretrained, from_quantized and the tt-blockfloat route.
  • _load_tokenizer replaces the tokenizer branch that was copied into from_pretrained and from_quantized.

Net change: 2 files changed, 88 insertions(+), 115 deletions(-), so 27 fewer lines. There is no change to numerics, checkpoint format or public API.

No issue is fixed by this PR (refactor only).

What Changed

Old (origin/main 1c51b32a7) New
Meta-shell fallback build: loader.py:3216-3232 (retry helper → config copy → Defuser → _model_init_kwargs → tree print) _direct_cpu_build(..., stored_kwargs=fallback_init_kwargs) at loader.py:3251
No-offload build: loader.py:3271-3288 (same five steps) _direct_cpu_build(..., stored_kwargs={**kwargs, **gguf}) at loader.py:3295
Sequence-length lookup: loader.py:3294-3301 (from_pretrained), 4535-4542 (from_quantized) and 2345-2349 (blockfloat) _SEQ_LEN_KEYS / _set_model_seqlen at loader.py:2622-2632. The blockfloat route uses only _SEQ_LEN_KEYS and keeps its silent 4096 default.
Tokenizer branch: loader.py:2980-3003 and 3700-3736 _load_tokenizer at loader.py:2599. Each caller still supplies its own selection kwargs. from_quantized still adds the GGUF kwargs as a separate ** expansion, exactly as before.

Behavior notes:

  • Different stored kwargs are kept on purpose. The meta-shell fallback records fallback_init_kwargs without the GGUF selection. The no-offload load records the merged dict. stored_kwargs is passed explicitly so this stays as it was. This may be a latent inconsistency. Today nothing in gptqmodel/ reads model._model_init_kwargs (LazyTurtle keeps its own copy), so it has no runtime effect. It is reported here and not changed.
  • One log string changed. The from_quantized seqlen fallback warning now has the same Model: prefix as the from_pretrained one. The text is otherwise unchanged and the value is still 4096.
  • Lazy evaluation is unchanged. The tokenizer selection kwargs are still computed only when the checkpoint tokenizer is actually loaded, so a definition with no text path, or a caller-supplied tokenizer, never evaluates them.
  • The dense (quantize_config=None) build is left alone (loader.py:3087-3095). It neither runs Defuser nor copies the config, so it is not the same build.
  • Intentionally not done: the "one wrapper tail" (cls(...) + _set_paged_attention_safe_cuda_graphs) from the debloat map.
    • from_pretrained runs the paged-attention default before the caller-tokenizer pad-id alignment (3115/3117, 3319/3334).
    • from_quantized runs it after (3796/3797, 4605/4612).
    • When the model has no generation_config, _set_paged_attention_safe_cuda_graphs creates one. So the two orders differ for paged attention combined with a caller tokenizer. One shared tail would change one of the paths.
  • Test change: the source-structure check in tests/test_quantize_load_global_state_5301.py::test_every_construction_site_uses_the_guarded_window used to require at least 3 inline retry-helper calls. It now requires at least 2 calls of the retry helper (the dense build and _direct_cpu_build) and at least 2 calls of _direct_cpu_build. Without the update it fails with assert 2 >= 3.

Tests

  • Unit tests have been executed and passed.
  • New unit test: not applicable. No mechanism is replaced; the change extracts helpers from copied code. Equivalence is proven by the structural A/B and GPU A/B below, and existing tests already cover each path.

Environment: Python /root/venv/bin/python (torch 2.15, transformers 5.23). Run with python -P, PYTHONPATH=<clone> and gptqmodel.__file__ checked against the clone. CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=1.

python -P -m pytest -q -rs \
  tests/test_local_model_paths.py tests/test_loader_tokenizer_flag_4941.py tests/test_lazy_turtle_conversion_cache.py \
  tests/test_checkpoint_subfolder_resolution.py tests/test_quantize_load_global_state_5301.py tests/test_compile_load_scope_5304.py \
  tests/test_missing_tokenizer_6361.py tests/test_generation_pad_token_id_6402.py tests/test_generation_pad_token_id_quantize_config_6402.py \
  tests/test_loader_offload_staging_4385.py tests/test_gguf_load_policy_env_removal.py tests/test_local_model_loading.py \
  tests/test_tt_blockfloat_out_axis.py tests/test_blockfloat_save_dtype_4549.py tests/test_tt_blockfloat_cuda_availability.py \
  tests/test_moe_reload_meta_4400.py tests/test_defuser_vendored_classes.py tests/test_converted_moe_experts.py \
  tests/test_local_tokenizer_loading.py tests/test_remote_only_tokenizer.py tests/test_package_tokenizer_selection.py \
  tests/test_tiny_tokenizer_helpers_6404.py tests/test_excluded_device_warmup.py tests/test_model_test_helpers.py \
  tests/test_kernel_config.py tests/test_macaq_rotation_serialization_4225.py tests/test_numpy_free_core.py \
  tests/test_lazy_kernel_registry_import.py tests/test_rocm_exl3_auto.py tests/test_model_port_policy.py \
  tests/test_transformers_unpatched.py tests/test_dense_load_explicit_device_5373.py
# 509 passed, 6 skipped in 451.50s

This set includes the nodes the debloat map names:

  • tests/test_local_model_paths.py::test_model_loader_requires_lazy_turtle_for_offload_to_disk
  • ::test_model_loader_uses_lazy_turtle_for_local_safetensors
  • ::test_model_loader_falls_back_when_meta_shell_build_hits_meta_tensor_item
  • ::test_model_loader_from_pretrained_native_bonsai_fast_profiles_use_dense_path
  • tests/test_lazy_turtle_conversion_cache.py::test_loader_converts_bin_under_configured_offload_path_not_tmpdir

It also includes the GPU tests tests/test_dense_load_explicit_device_5373.py::test_dense_load_honors_an_explicit_cuda_ordinal and ::test_dense_load_honors_device_cpu_on_a_cuda_host; both passed on GPU 1.

Skips, and what they leave unverified:

  • tests/test_package_tokenizer_selection.py:93 ×2: XVERSE-MoE and tiny-gpt2 are not in the local HF cache. Package tokenizer selection for those two repos was not exercised. The new structural A/B covers the tokenizer call shape.
  • tests/test_excluded_device_warmup.py:574/629/698 ×4: these need 2 CUDA devices and only one was assigned. They do not touch the changed code.

Lint: bash format/check.sh → All checks passed! (ruff 0.14.2).

Structural A/B (origin/main vs this branch)

ab_loader_paths.py (kept outside the repo) drives ModelLoader.from_pretrained through test doubles, plus GPTQModel.from_quantized on a real local Qwen2.5-0.5B-Instruct-GPTQ-Int4 checkpoint up to the tokenizer call.

Cases (69 in total):

  • from_pretrained: 64 cases. Each of 4 paths (dense, offload shell, meta-shell fallback, no-offload direct) is run with every combination of GGUF on/off, caller tokenizer on/off, require_load_tokenizer True/False, and a seqlen key in the config present/absent.
  • from_quantized: 5 variants (plain, Hub kwargs, caller tokenizer, tokenizer_trust_remote_code, injected GGUF selection).

Recorded per case:

  • kwargs of the inner loader.from_pretrained call and of build_shell_model
  • model._model_init_kwargs
  • whether the model kept the caller's config object
  • the Defuser marker and seqlen
  • the args and kwargs of every load_hf_tokenizer call
  • the wrapper cls(...) kwargs, the LazyTurtle kwargs, warnings and errors
PYTHONPATH=<base> python -P ab_loader_paths.py base.json; PYTHONPATH=<branch> python -P ab_loader_paths.py new.json
# 69 cases; the only field that differs is LazyTurtle offload_path
# (a fresh TemporaryDirectory per QuantizeConfig on each run).

GPU A/B (GPU 1, origin/main vs this branch, same seed and inputs)

gpu_ab.py + gpu_compare.py:

Case Path Result
GPTQModel.load(Qwen2.5-0.5B-Instruct, device="cuda:0") dense from_pretrained logits for 3 prompts bit-identical. Tokenizer, pad id, generation_config, config, dtypes and devices identical.
GPTQModel.load(Qwen2.5-0.5B-Instruct-GPTQ-Int4, device="cuda:0") from_quantized logits for 3 prompts bit-identical; seqlen 32768 on both; state identical
GPTQModel.load(dense, QuantizeConfig(bits=4, group_size=128)) offload shell seqlen, _model_init_kwargs, tokenizer and config identical
GPTQModel.load(dense, QuantizeConfig(..., offload_to_disk=False)), then quantize (16 rows) and save _direct_cpu_build all 794 saved tensors bit-identical. config.json, quantize_config.json, generation_config.json, tokenizer*.json byte-identical. quant_log.csv holds timings and was not compared.

Measured Impact

Not applicable. This refactor does not change VRAM, performance or accuracy; the GPU A/B is bit-identical.

Model Support / Module Plan

Not applicable. No model, alias, definition or module plan is changed.

AWQ onboarding safety

Not applicable. AWQ grouping, search, replay and folding are not touched.

Logic Flow Documentation

  • This change does not alter a major logic flow. It extracts helpers in place, and every path keeps its order of operations; the old-to-new mapping is tabulated above with file:line. No decision mechanism, selection order or lifecycle changes, so there is no diagram or docs page.

Review Requirements

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions. The helpers are module-level functions that look up module globals at call time, so tests that monkeypatch load_hf_tokenizer, print_module_tree, defuser.convert_model or _hf_loader_from_pretrained_with_dynamic_module_retry still apply.
  • Avoided unnecessary monkeypatching.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions (structural and GPU A/B above).

Kernel Accuracy Requirements

Not applicable. No kernel changes.

Notes

The debloat map also proposed a single wrapper tail (cls(...) + _set_paged_attention_safe_cuda_graphs). It is intentionally left out, because the pad-id alignment and the paged-attention default run in different orders in the two loaders (see What Changed). Unifying the order would be a separate behavior decision.

🤖 Generated with Claude Code

…or both load paths

The quantize path of from_pretrained built its dense source straight to CPU
in two places (the no-offload load and the meta-shell fallback) with the
same five steps: _hf_loader_from_pretrained_with_dynamic_module_retry, a
config copy when the model kept the caller's config, Defuser conversion,
recording _model_init_kwargs and the optional module-tree print. Both now
call _direct_cpu_build. The recorded kwargs are passed explicitly
(stored_kwargs) because the two sites differ: the fallback records its
kwargs without the GGUF selection, the no-offload load merges it in. That
difference is preserved as-is.

The sequence-length lookup was copied in from_pretrained, from_quantized
and the tt-blockfloat route. The key tuple is now _SEQ_LEN_KEYS and the two
warning sites call _set_model_seqlen; the blockfloat route keeps its silent
4096 default.

The tokenizer branch (no-text-path definitions, caller tokenizer, checkpoint
tokenizer with selection kwargs) was copied in from_pretrained and
from_quantized; both now call _load_tokenizer with their own selection
kwargs.

The wrapper construction plus _set_paged_attention_safe_cuda_graphs is not
merged: from_pretrained runs it before the caller-tokenizer pad-id
alignment and from_quantized after, and the two do not commute when the
model has no generation_config.

The source-structure check in test_quantize_load_global_state_5301 now
counts the shared helper's call sites instead of three inline calls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium marked this pull request as ready for review November 30, 2026 02:32
@Qubitium
Qubitium merged commit 615aef7 into main Nov 30, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/loader-direct-cpu-build branch November 30, 2026 02:32
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