Skip to content

fix(offload): finish the in-session materialisation contract (#4572, #4562, #4597) - #4611

Merged
Qubitium merged 1 commit into
mainfrom
fix/issue-4572-4562-insession-contract
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/issue-4572-4562-insession-contract

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4572

Fixes #4562

Fixes #4597

TL;DR

Three gaps in the #4498 in-session contract are closed in the same loop-exit path: resumed packed modules now carry the offload hook the restore needs (#4562), tied lm_heads are re-tied instead of read from a checkpoint that never stores them (#4597), and parameters left without a version counter by param.data = are rebound (#4572). A model that still has meta tensors at loop exit now raises instead of only logging. Net: +166/−12 in utils/offload.py, +18 across the two loopers and the checkpoint adapter, 4 unit tests, 1 end-to-end resume test, 2 docs pages updated.

1. Root causes

#4572 — pre_quantize materializes unquantized layers (MoE routers, dynamic -: exclusions, norms) under torch.inference_mode(); post_quantize then moves them to CPU with param.data = cpu_copy. The result reports is_inference() == False but has no version counter, so F.linear raises Inference tensors do not track version counter. replace_inference_parameters keyed on is_inference(), so it never repaired them.

#4562 — gptq_checkpoint.py rebuilds completed layers with restore_packed_module(...) on meta and set_submodules them with no accelerate offload hook. restore_disk_offloaded_modules only targets hooked modules, and materialize_remaining_meta_modules skips QUANT_TYPE modules, so every resumed packed layer stayed meta with no diagnostic.

#4597 — a tied checkpoint stores only the input embedding. restore_offloaded_modules ties right after restoring base bundles, but the weight-only looper materializes the meta base modules afterwards, and nothing ties again before materialize_remaining_meta_modules gives up on lm_head. The log-only path then led into a partial .to() and a CUDA device-side assert.

Old mechanism Replacement
replace_inference_parameters tested only is_inference() _tracks_version + ensure_version_counters rebind parameters whose ._version raises, at loop exit
Resumed packed module set with no hook attach_disk_offload_hook installs the same hook a fresh offload installs, over the per-attempt index.json
AlignDevicesHook.original_devices all meta (so detach restored nothing) Recorded devices rewritten to the execution device for meta entries
Tied lm_head attempted from the checkpoint _retie_shared_embeddings re-ties after materialization and before the remaining-meta verdict
Remaining meta module → log.error RuntimeError telling the caller to reload the saved checkpoint

2. New loop-exit flow

flowchart TD
    L["looper _loop_impl() returns"] --> B["_restore_offloaded_base_modules(strict=True)"]
    B --> Q["_restore_disk_offloaded_modules(strict=True)"]
    Q --> Q1["undo_offload_to_disk for every hooked module<br/>(fresh offloads and resumed ones)"]
    Q1 --> W{"WeightOnlyLooper?"}
    W -- yes --> M["_materialize_meta_base_modules(strict=True)"]
    W -- no --> R
    M --> R["_materialize_remaining_meta_modules()"]
    R --> T["_retie_shared_embeddings(model)<br/>tied lm_head aliases embed_tokens"]
    T --> V{"any non-quantized module still meta?"}
    V -- yes --> X["RuntimeError: reload the saved checkpoint"]
    V -- no --> C["ensure_version_counters(model)"]
    C --> K["rehome_quantized_kernel"]

    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class X failure;
Loading

3. Per-issue detail

flowchart TD
    A["quantize(checkpoint=...) resumes"] --> B["restore_packed_module -> meta"]
    B --> C["per-attempt index.json"]
    C --> D["attach_disk_offload_hook"]
    D --> E["loop-exit restore materializes CPU tensors"]
    E -. "bundle or index unreadable" .-> X["RuntimeError"]

    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class X failure;
Loading
flowchart TD
    P["pre_quantize: inference_mode materialization"] --> Q["post_quantize: param.data = cpu_copy"]
    Q --> R{"is_inference or _version usable"}
    R -- no --> S["ensure_version_counters: one fresh Parameter per aliased old object"]
    R -- yes --> U["untouched"]

    classDef bad fill:#fee2e2,stroke:#b91c1c,color:#7f1d1d;
    class S bad;
Loading

4. Failure and ambiguity contract

Situation Before After
Resumed packed module, bundle intact stayed meta, silent materialized on CPU at loop exit
Resumed packed module, index/bundle unreadable stayed meta, silent RuntimeError (reload the checkpoint)
Tied lm_head after base materialization meta, .to() raised halfway, next generate() hit a device-side assert re-tied to embed_tokens; no meta
Untied lm_head that cannot be materialized logged only RuntimeError (reload the checkpoint)
Unquantized layer parameter after param.data = F.linear raised Inference tensors do not track version counter rebound, forward and .to() work
Aliased parameters n/a every owner of one old object gets the same replacement
EXL3 reference-offloaded packed modules meta by design unchanged (skipped as QUANT_TYPE)

5. Change inventory

Area File ± Purpose
Offload helpers gptqmodel/utils/offload.py +166/−12 _tracks_version, extended replace_inference_parameters, ensure_version_counters, attach_disk_offload_hook, _retie_shared_embeddings, loud remaining-meta failure
Loop exit gptqmodel/looper/module_looper.py +6 ensure_version_counters after restore/materialize
Loop exit gptqmodel/looper/weight_only_looper.py +5 same
Resume gptqmodel/looper/gptq_checkpoint.py +7/−1 attach the offload hook to each restored packed module
Tests tests/test_offload_quantized_modules_restored_4450.py +156 version-counter repair, resumed-hook materialization, tied VL re-tie, loud failure
Tests tests/test_checkpoint_quantization.py +75 end-to-end stop/resume with a dynamic -: exclusion
Docs docs/in-session-model-after-offload.md, docs/looper-checkpoint-redesign.md +62/−7 new loop-exit steps, resume/version-counter flows, failure contract, stale sentence fixed

6. Tests / guarantees

Test Invariant
test_unquantized_layers_keep_a_version_counter_after_the_cpu_move The exact param.data = state rejects a forward; ensure_version_counters and replace_inference_parameters repair it
test_resumed_packed_module_hook_is_materialized_at_loop_exit A meta packed module with no hook becomes CPU tensors through attach_disk_offload_hook + the strict restore, and its forward is bit-identical
test_tied_vl_lm_head_is_retied_after_base_materialization A tiny Qwen2-VL layout with a broken tie and meta lm_head ends with zero meta tensors and lm_head.weight is embed_tokens.weight
test_untied_meta_output_embedding_fails_loudly A meta lm_head that cannot be loaded raises RuntimeError
test_resumed_quantize_leaves_a_usable_in_session_model Real stop/resume with -:^model\.layers\.1\.: zero meta tensors, every parameter has a usable _version, in-session forward works

7. Validation

All runs with OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 NUMEXPR_NUM_THREADS=4.

# new unit tests, before the fix (source stashed) -> 4 failed
#   ImportError: ensure_version_counters / attach_disk_offload_hook
#   AssertionError: assert ['lm_head'] == []
#   (loud-failure test: no RuntimeError raised)
# new unit tests, after the fix, CUDA venv
pytest tests/test_offload_quantized_modules_restored_4450.py -q
-> 13 passed

# #4572/#4562 end-to-end, before the fix -> FAILED: 35 meta tensors
pytest tests/test_checkpoint_quantization.py -q -k "resumed_quantize_leaves_a_usable"
-> 1 passed

pytest tests/test_checkpoint_quantization.py -q \
  -k "resumed_quantize_leaves_a_usable or dynamic_quantized_tensors_equal_after_resume or quantized_tensors_equal_after_resume"
-> 7 passed

# related offload files, CUDA venv
pytest tests/test_offload_quantized_modules_restored_4450.py tests/test_offload_base_modules_restored.py \
  tests/test_offload_autograd.py tests/test_qzeros_disk_offload_4380.py \
  tests/test_ernie4_5_vl_moe_offload_hook.py -q
-> 55 passed, 1 failed (pre-existing, see notes)

# ROCm venv (HIP_VISIBLE_DEVICES=0), CPU-only new tests
pytest tests/test_offload_quantized_modules_restored_4450.py -q -k "version_counter or resumed_packed or tied_vl or untied_meta"
-> 4 passed

ruff check gptqmodel docs/eora tests setup.py
-> All checks passed!

Hardware: CPU-only tests; CUDA venv pinned to RTX 4090 GPU-1892aea4-cc09-827c-b9a5-93d4eef7f5ae, ROCm venv to R9700 HIP_VISIBLE_DEVICES=0. No accelerator kernel executed.

8. Reviewer notes

  • Chosen behavior: fail loudly. materialize_remaining_meta_modules now raises RuntimeError when a non-quantized module still owns meta tensors, instead of logging. The issue asked for this because the log-only path led into a partial .to() and a CUDA device-side assert. The message names the modules and says to reload the saved checkpoint.
  • Limitation: the loud failure means a run whose source checkpoint genuinely lacks a non-quantized tensor now raises at the end of quantize() instead of producing a saveable-but-unusable in-session model. save() correctness is unchanged for runs that reach it.
  • Limitation: the tied-VL test uses a real Qwen2VLForConditionalGeneration module tree but simulates the fix(offload): leave a normal in-session model after disk-offloaded quantize (#4450) #4498 end state (materialized embedding, broken tie, meta head) rather than running a full VL quantize; the end-to-end resume test covers the loop wiring with a text model.
  • tests/test_offload_base_modules_restored.py::test_loop_restores_base_modules_when_quantize_fails fails identically on unmodified origin/main (AttributeError: 'ModuleLooper' object has no attribute '_inflight_layer') — pre-existing, unrelated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment