Skip to content

feat(looper): add authenticated disk-backed layer outputs - #3588

Merged
Qubitium merged 4 commits into
ModelCloud:mainfrom
tpurtell:upstream/10-disk-backed-layer-outputs-20261108
Nov 8, 2026
Merged

Qubitium merged 4 commits into
ModelCloud:mainfrom
tpurtell:upstream/10-disk-backed-layer-outputs-20261108

Conversation

@tpurtell

@tpurtell tpurtell commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add an opt-in writer and random-access sequence for bounded calibration boundaries. Shard safetensors batches, bind provenance and hashes, publish completion manifests atomically, resume completed shards, and retry post-commit finalizers. Non-owning lifetime diagnostics help verify that readers release issued tensors. The public utility is available to explicit consumers; automatic looper/model wiring remains in the fork remainder. xxhash is imported lazily and is needed only for this optional recovery path.

Stack

Layer 10/36 of a dependency-ordered fork extraction. Depends on #3587. Review only this layer.

GitHub requires this cross-fork PR to target upstream main, so its Files changed tab includes earlier stack layers. After the predecessor lands, rebase this branch and retarget the next layer; do not merge later layers out of order. No predecessor is merged automatically.

Tests

CUDA_VISIBLE_DEVICES='' HIP_VISIBLE_DEVICES='' OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 python -m pytest -q tests/test_disk_backed_layer_outputs.py

6 passed. Used Python 3.12, Torch 2.14.1, Transformers 5.19.0. No model quantization, GPU work, downloads, or heavyweight model validation. Unit fixtures are small and CPU execution is constrained to one math thread.

Review and remaining validation

This layer and its dependency diff were reviewed for scope, existing extension points, and compatibility with the resolved fork snapshot. New focused regression coverage is included. Kept as a draft for maintainer review; hardware paths and end-to-end model behavior have not been revalidated in this session. No speed claim. Original integration/history is preserved in tpurtell#3.

@Qubitium Qubitium left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: layer 10/36 — authenticated disk-backed layer outputs

Rebased onto the layer-9 branch (ef7a8c5e); no conflicts. Diff vs the predecessor is looper/input_cache.py, the new test, and one requirements line. Pushed as ded8fcc1.

Verified

  • tests/test_disk_backed_layer_outputs.py → 7 passed (6 original + 1 added)
  • ruff check clean

Fixed

  1. Finalize crash window — finalize() deleted progress.json before os.replace(temporary, destination). A crash between those two calls left a complete manifest.json in .partial but no progress record, so the next writer started with an empty shard set and recomputed every batch. Progress is now removed only after the rename commits (and a leftover progress.json in a complete directory is ignored by open()). Added a rename-crash regression test that fails on the old ordering.
  2. Manifest path containment — root / shard["path"] lets an absolute path (or ..) escape the root, and _restore_progress did not reject symlinks at all. Added _contained_path() (rejects absolute/escaping paths and symlinks) and used it in both open() and _restore_progress().
  3. Non-POSIX durability — _fsync_directory called os.open(dir, O_RDONLY) + fsync unguarded, which fails on Windows. It is now a no-op off POSIX and uses O_DIRECTORY where available.
  4. _atomic_json hygiene — the temp file leaked on write/replace failure and was created 0600. It is now removed on failure and written 0644.
  5. xxhash dependency — the comment claimed it was "needed only for this optional recovery path", but _flush_shard() and _restore_progress() hash every shard, so the writer hard-requires it. It was undeclared, which makes the feature (and its test) fail on a stock install. Added xxhash>=4.0.2 to requirements.txt and a clear ImportError. If you want it genuinely optional, the writer needs a no-hash/fallback mode rather than a lazy import.

Notes (not blockers)

  • append() computes its index from len(committed) + sum(pending) under the lock, then releases and calls put(). A concurrent put() can race between the two. Sequential ForwardExecutor use is fine; document the single-writer assumption.
  • The Sequence[List[torch.Tensor]] contract suggests multi-tensor batches, but put() accepts exactly one tensor (len(value) != 1 → TypeError). Either widen it or narrow the annotation/docstring.
  • open() verifies every shard hash by default, i.e. reads the whole cache; that is correct but expensive for large activation sets. verify_hashes=False is available but easy to miss.
  • open()/_restore_progress() still pass batch_count/shard_batches through int() without type checks, so a malformed (but self-hashed) manifest can raise a raw TypeError. Minor.
  • lifetime_diagnostic() relies on gc.get_referrers and is heuristic by nature; the __new__ shortcut in DiskBackedLayerOutputSequence is hacky but harmless.

The core design is good: shards are content-hashed, the manifest is canonical-JSON self-hashed, progress is atomic, completed shards resume without rewriting, and finalizer retries work.

@Qubitium
Qubitium marked this pull request as ready for review November 8, 2026 08:10
@Qubitium
Qubitium force-pushed the upstream/10-disk-backed-layer-outputs-20261108 branch 2 times, most recently from 2aeb0e7 to f8842b0 Compare November 8, 2026 08:22
tpurtell and others added 4 commits November 8, 2026 08:35
The new test file used semicolons (E702) and unsorted imports (I001), and the
module import block was unsorted; format/check.sh runs ruff check over tests,
so the PR could not merge as-is. No behavior change: 20 tests still pass.
…utputs

- Keep progress.json until the destination rename commits. A crash after the
  complete manifest is written but before the rename now resumes the finished
  shards instead of recomputing them; add a rename-crash regression test.
- Reject manifest/progress shard paths that escape the root or are symlinks.
- Make _fsync_directory a no-op off POSIX; clean up _atomic_json temp files on
  failure and write them 0644.
- Declare xxhash (the writer hashes every shard, so it is not recovery-only)
  and raise a clear ImportError when it is missing.
@Qubitium
Qubitium force-pushed the upstream/10-disk-backed-layer-outputs-20261108 branch from f8842b0 to d1896b6 Compare November 8, 2026 08:35
@Qubitium
Qubitium merged commit ebbbecb into ModelCloud:main Nov 8, 2026

Copy link
Copy Markdown
Collaborator

Clean review found out-of-order replay batches stayed in RAM and later reads could miss changed shard data. Fixed in merged #3790; 14 focused tests pass with and without the GIL. Concurrent append() is serialized too.

Qubitium added a commit that referenced this pull request Dec 1, 2026
…to disk for every processor (#6656)

ds4rt's disk-backed layer outputs (#3588) were reachable only through
per-model configure_*_store hooks that nothing in-tree calls. Make the same
DiskBackedLayerOutputWriter/Sequence available to every processor through
one typed field, CalibrationConfig.spill_path (map PR-G2):

- spill_writer() gives each pass a private, non-durable directory (no
  fsync, no resume journal) that weakref.finalize removes with its sequence,
  or with the writer when a failed pass never finalizes it.
- ForwardExecutor._output_collection spills every pass that produces all
  batches (replays, native capture) after the unchanged model hook; subset
  forwards that stop early keep their list. The first-layer capture moves
  each batch into a spill writer as soon as its forward returns.
- The writer records each batch's device and the sequence reads it back
  there, so consumers see the same tensors on the same device. Deep copies
  share the immutable files.
- ContinuationCodec stores a spilled cache as the list it replaces, so
  spill composes with CheckpointConfig (layer and subset steps).
- The lm_head stage copies a lazy cache into lists before the in-place
  norm hook.
- Delete TensorLifetimeDiagnostic, whose last consumer #6477 removed.

spill_path=None runs none of this: GPTQ and AWQ on Qwen2.5-0.5B-Instruct
are bit-identical to main. With spill on, GPTQ and AWQ on Qwen2.5-0.5B-Instruct
and GPTQ on OLMoE-1B-7B are bit-identical to spill off, and peak GPU memory
drops by the hidden-state sets the default path keeps resident.

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.

2 participants