Skip to content

perf(checkpoint): stream continuation capture and verify it once - #5925

Merged
Qubitium merged 1 commit into
mainfrom
fix/5749-continuation-stream
Nov 20, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5749-continuation-stream

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Continuation checkpointing on main materializes the whole continuation
payload several times. This PR streams it to disk once on capture and verifies
it once on resume, cutting commit peak RSS by 97.5% and restore peak RSS by
63.0% on a 192 MiB continuation while keeping every restored tensor bitwise
identical.

Fixes #5749

Root cause

ContinuationCodec.dumps() cloned every tensor
(gptqmodel/looper/continuation.py:34: .to(device="cpu").contiguous().clone())
and then built one contiguous bytes object for the whole payload. The caller
passed those bytes to CheckpointStore.put(), which hashed and copied them
again (gptqmodel/looper/checkpoint.py:151). The calibration identity built yet
another full buffer to hash it (gptqmodel/looper/gptq_checkpoint.py:393).

On resume, CheckpointStore._manifest() called get(), which read and hashed
the entire payload into memory only to discard it
(gptqmodel/looper/checkpoint_store.py:267). prepare() then called
get() again, and loads() parsed the header and decoded a second copy
(gptqmodel/looper/checkpoint.py:110). Repeated references to one tensor also
produced one payload entry and one clone per reference.

What Changed

  • ContinuationCodec now separates encoding from I/O:
    • dump_file(state, path) writes the safetensors object directly to a path.
    • dumps(state) keeps the in-memory form for callers that need bytes.
    • sha256(state, directory) hashes exactly the bytes dumps() would produce,
      using a temporary file under the offload root instead of a heap buffer.
    • load_file(path) decodes with safetensors.safe_open, materializing each
      payload tensor once and reusing it for aliases.
  • Encoding registers one entry per distinct tensor object (id). Already-CPU
    tensors are written from the live state without a clone; only a view whose
    storage overlaps another entry is copied, because safetensors rejects shared
    storage. Non-CPU tensors are still moved to CPU.
  • CheckpointStore gains stage() (private staging path, always removed) and
    continuation_path(); _manifest() now streams the continuation through
    object_path() once and records the verified path, and commit() uses
    object_path() instead of get(). collect() also removes stray
    .<32 hex>.tmp staging files.
  • CheckpointExtension.on_boundary() streams capture through
    dump_file() + put_file(); prepare() decodes through load_file().
  • Restore verification compares the decoded tensor against its own live bytes
    and _version, so an in-place transfer that mutates its source still fails;
    inference tensors (no version counter) keep a cloned reference.
  • docs/looper-checkpoint-redesign.md documents the shipped flow, the old
    mechanism and the failure paths.

The continuation is hashed when the manifest is verified and decoded from that
same verified path. External edits during a run remain out of contract, as
before; the change removes one full read plus a second hash, not the integrity
check.

Tests

New file tests/test_checkpoint_continuation_stream_5749.py (6 tests):

Test main (99f4720) This branch
test_file_codec_matches_in_memory_bytes_and_restores_bitwise FAIL (dump_file/sha256 absent) PASS
test_encoder_does_not_clone_contiguous_cpu_tensors FAIL (continuation encoder cloned a CPU tensor) PASS
test_commit_does_not_read_continuation_into_memory FAIL ([4194544, 4194544] full reads) PASS
test_resume_restores_all_tensors_bitwise PASS PASS
test_corrupted_continuation_fails_integrity PASS PASS
test_checkpoint_commit_peak_rss_is_bounded FAIL (2 full reads, 552 MiB delta) PASS (0 reads, 14 MiB delta)

The last test drives the 192 MiB state in a fresh subprocess and asserts no
CheckpointStore.get() of 1 MiB or more and a commit peak-RSS delta below
256 MiB. The codec test asserts the staged file is byte-identical to
dumps() (so existing calibration digests stay valid), alias deduplication
(6 references to 4 payload entries), bitwise restore and alias identity.

Commands and results on this branch (CPU host, Python 3.14.7, Torch
2.15.0+cu132, no GPU):

PYTHONPATH=$PWD python -m pytest tests/test_checkpoint_continuation_stream_5749.py -q
# 6 passed in 18.47s

PYTHONPATH=$PWD python -m pytest tests/test_processor_continuation.py \
  tests/test_checkpoint_extension.py tests/test_checkpoint_store.py \
  tests/test_checkpoint_telemetry.py tests/test_checkpoint_processor_adapter.py \
  tests/test_checkpoint_continuation_stream_5749.py -q
# 71 passed in 24.07s

PYTHONPATH=$PWD python -m pytest tests/test_checkpoint_quantization.py -q \
  -k "not subprocess_recovery"
# 13 passed, 28 deselected in 15.68s

PYTHONPATH=$PWD python -m pytest tests/test_checkpoint_quantization.py -q \
  -k "subprocess_recovery and llama"
# 7 passed, 34 deselected in 164.06s  (kill-before, kill-after, error, int,
#                                      term, kill-hessian, kill-hessian-early)

ruff check gptqmodel docs/eora tests setup.py   # ruff 0.14.2, the CI gate
# All checks passed!

Broader checkpoint family (test_checkpoint_*, test_fail_closed_checkpoint_5218.py,
test_nested_checkpoint_resave_5380.py): 222 passed, 7 failed. All 7 failures
reproduce unchanged on main and are environment limits, not this change:
test_checkpoint_modules.py::test_qqq_optional_group_scales_schema (missing
optional import), four test_checkpoint_state_invariant.py cases (no AVX-512
/ GPU), and two test_public_exl3_loader_checks_checkpoint_codebook_markers
cases (no EXL3 native build). GPU, AVX-512, EXL3, BitBLAS and bitsandbytes
validation is unavailable on this CPU-only host, so those paths are not
claimed as tested.

Measured Impact

Same machine, same 192 MiB continuation state (128 MiB bf16 replay
(16, 2048, 2048) + 64 MiB bf16 dense (8192, 4096)), fresh subprocess per
revision, resource.getrusage(RUSAGE_SELF).ru_maxrss. No GPU is present, so
these are host RSS measurements; no VRAM claim is made.

Metric (unit) Before (99f4720) After Change (after − before)
Continuation encode peak RSS delta (MiB) 548.0 386.0 −162.0 (−29.6%)
Checkpoint commit peak RSS delta (MiB) 552.0 14.0 −538.0 (−97.5%)
Continuation restore peak RSS delta (MiB) 502.0 186.0 −316.0 (−63.0%)
Full-payload CheckpointStore.get reads, commit + resume (count / bytes) 3 / 576 MiB 0 / 0 MiB −3 / −576 MiB
Restored replay and dense tensors bitwise identical yes yes unchanged
Restored cursor 1 1 unchanged

The standalone issue reproduction counted 3 verification-only full reads
(576 MiB) on main and 0 after this change; the commit harness counted 2
get() reads (402,655,040 B) and the restore harness 2 reads on main, both 0
after. Resume still decodes each tensor once from the file (that is the one
unavoidable read); it no longer copies the whole payload into a bytes
buffer first.

Model Support / Module Plan

Not applicable: no model definitions, MODEL_MAP entries or module plans are
touched.

Logic Flow Documentation

Applicable: this changes tensor materialization and checkpoint persistence.

flowchart TD
    A["CheckpointExtension.on_boundary"] --> B["adapter.capture"]
    B --> C["ContinuationCodec.dump_file"]
    C --> D["ContinuationCodec._encode"]
    D --> E{"device is CPU?"}
    E -- "yes" --> F["Write live tensor; clone only overlapping views"]
    E -- "no" --> G["tensor.to(device=cpu)"]
    F --> H["save_file into CheckpointStore.stage path"]
    G --> H
    H --> I["CheckpointStore.put_file: hash, fsync, rename to objects/sha256"]
    I --> J["CheckpointStore.commit: object_path checks"]
    J --> K["Manifest published; CURRENT replaced"]
    L["CheckpointExtension.prepare"] --> M["CheckpointStore.load: _manifest calls object_path"]
    M --> N["_verified_continuations records the hashed path"]
    N --> O["continuation_path returns the recorded path"]
    O --> P["ContinuationCodec.load_file: safe_open"]
    P --> Q["_decode materializes each tensor once"]
    Q --> R{"version and raw bytes match?"}
    R -- "no" --> X["ValueError; checkpoint_restore_failed"]
    R -- "yes" --> S["adapter.restore; committed cursor"]
    M -- "checksum mismatch" --> Y["CheckpointCorrupt; try the older generation"]
    I -. "exception" .-> Z["stage deletes its temp file"]
    classDef failure fill:#fce8e6,stroke:#a33,color:#111
    class X,Y,Z failure
Loading
Mechanism Before Now
Capture buffer gptqmodel/looper/continuation.py:34 cloned every tensor, then gptqmodel/looper/checkpoint.py:151 built a second full bytes buffer with dumps(), which put() copied again. dump_file() streams the payload into CheckpointStore.stage(); put_file() hashes and renames it without a second buffer. CPU tensors are written as-is.
Repeated references Each reference to the same tensor produced its own payload entry and clone. _encode() registers one entry per distinct tensor object (id); aliases restore to the same object.
Calibration identity gptqmodel/looper/gptq_checkpoint.py:393 serialized the whole continuation to bytes to hash it. ContinuationCodec.sha256() hashes the same bytes from a temporary file in the offload root.
Manifest verification gptqmodel/looper/checkpoint_store.py:267 called get(), reading and hashing the whole payload into memory only to discard it. _manifest() calls object_path(), which streams and hashes the file, and records the verified path.
Resume decode gptqmodel/looper/checkpoint.py:110 called loads(store.get(...)): one full bytes read, a header parse, then safetensors.load() copied the payload again. load_file() decodes with safe_open; each payload tensor is materialized once and shared by aliases.
Bitwise verification Compared every stored tensor against a cloned copy. Compares the live decoded tensor and its _version; inference tensors keep a cloned reference.

The same diagram and table are committed in
docs/looper-checkpoint-redesign.md
(new "Continuation capture and restore I/O" section), which is already linked
from docs/README.md.

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, kernel-selection or packed-layout code is changed.

Notes

  • dumps()/loads() remain, so existing callers and tests keep working; the
    staged file is byte-identical to dumps() and the calibration digest is
    unchanged for the same state.
  • _verified_continuations is per lease and cleared in __enter__.
  • Trade-off: the continuation is hashed once at manifest verification rather
    than again at prepare time. A file mutated between those two points is not
    re-hashed; editing checkpoint objects during a run was already outside the
    documented contract.
  • Out of scope: further reducing the single decode pass, and GPU-side
    validation of the restore path.

@Qubitium
Qubitium force-pushed the fix/5749-continuation-stream branch from 1dd3606 to 065eb43 Compare November 20, 2026 14:34
Continuation capture built the full safetensors payload in memory, cloned
every tensor, then copied the bytes again through CheckpointStore.put().
Resume read the whole continuation into a bytes buffer just to verify it,
read it again in prepare(), and decoded a second copy; every repeated
tensor reference also carried its own payload entry.

ContinuationCodec now exposes dump_file(), which writes the safetensors
object straight into CheckpointStore.stage(); put_file() hashes and renames
it without a second buffer, and sha256() reuses the same bytes for the
calibration identity. Encoding registers one entry per distinct tensor
object, writes already-CPU tensors without a clone, and copies only views
whose storage overlaps another entry. On resume, _manifest() streams the
continuation through object_path() once and records the verified path;
prepare() decodes it with safe_open, materializing each tensor once for all
aliases. Bitwise verification compares the decoded tensor and its version
counter, with a cloned reference for inference tensors.

Measured on a 192 MiB continuation (128 MiB replay + 64 MiB dense):
commit peak delta 552 -> 14 MiB and 2 -> 0 full-payload store reads;
restore peak delta 502 -> 186 MiB with 2 -> 0 full reads; encode peak delta
548 -> 386 MiB. Restored tensors remain bitwise identical.
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.

[Audit][checkpoint] Quantization continuation copies and rereads the full replay and dense state at each checkpoint

1 participant