Repository navigation
feat(calibration): CalibrationConfig.spill_path streams layer inputs to disk for every processor - #6656
Merged
Conversation
…to disk for every processor 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]>
Qubitium
marked this pull request as ready for review
December 1, 2026 13:26
This was referenced Dec 1, 2026
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
…6689) #6656 added CalibrationConfig.spill_path and #6683 re-enabled split_by="layer" after #6640 refreshed the notes. Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Second generic piece of the ds4rt deprecation (map PR-G2), built next to G1 (#6492). The ds4rt "authenticated disk-backed layer outputs" (#3588) could only be switched on through per-model
configure_base_replay_store/configure_mtp_activation_storehooks, and nothing in-tree calls them. This PR makes the sameDiskBackedLayerOutputWriter/DiskBackedLayerOutputSequenceavailable to every processor through one typed field:With
spill_path, the first-layer capture and every pass that produces the next layer's inputs stream one safetensors file per calibration batch to disk. Host and accelerator memory then hold one batch of hidden states instead of the whole calibration set (per-batch kwargs and masks stay resident; see Notes). Every batch reads back onto the device it was written from, so each consumer (subset forwards, replay, AWQ's scale search, GPTAQ's native stream, Paro/G2PTQ references, checkpoint capture) sees the same tensors on the same device as before.spill_path=None(the default) takes no new branch: every spill step is guarded by the field (one exception: thelm_headlist copy also applies to a non-list cache, which only the unreachable ds4rt hooks produce). The GPU A/B below (GPTQ and AWQ on Qwen2.5-0.5B-Instruct, origin/main efc3239 vs this branch) is bit-identical. With the field set, GPTQ and AWQ on Qwen2.5-0.5B-Instruct and GPTQ on OLMoE-1B-7B are bit-identical to spill off, and the run's peak memory drops (table below).No new mechanism is added. The existing writer and sequence are reused, and no meta keys, environment switches or classes are added.
gptqmodel/is +172/-135: the deadTensorLifetimeDiagnosticis removed, which offsets most of the new code.No issue is fixed. This is the planned feature step of the ds4rt deprecation.
What Changed
quantization/config.py:CalibrationConfig.spill_path: Optional[str | os.PathLike] = None. A value that is not a path raisesTypeError. It is a calibration field, so it stays out of the checkpoint identity, which hashesQuantizeConfig.looper/input_cache.pyspill_writer(spill_path, *, layer_index, expected_batches)returns a writer that owns a private directory (tempfile.mkdtempunderspill_path, resolved once so a later cwd change cannot redirect cleanup) and stores one file per batch. If the writer rejects its geometry, that directory is removed before the error propagates.progress.json. It is scratch space and is never resumed. With fsync, the first GPU smoke spent 1.2 s per batch file in fsync on this host.weakref.finalizewith the finalized sequence, or with the writer when a failed pass never finalizes it.put(). The sequence reads the batch back onto that device (batch_placementreports it). A sequence reopened from disk still reads CPU, as before.DiskBackedLayerOutputSequence.__deepcopy__returnsself. The files are immutable, and a copy must not let the original's finalizer delete files the copy still reads. GPTAQ deep-copies the native capture (module_looper.py:1951).DiskBackedLayerOutputWriter(durable=True)is the existing behaviour.durable=Falseskips the fsyncs and the resume journal.TensorLifetimeDiagnosticandDiskBackedLayerOutputSequence.lifetime_diagnostic, plus the per-read weakref list behind them. Their only production consumer, the boundary diagnostic atstage_layer.py:1078-1084named by the map, was removed by refactor(looper): fold quantization_layer_boundary_checkpoint into LoopExtensions #6477. The list grew by one entry on every read, and that matters now that every processor can read a spilled cache.looper/forward_executor.py:_output_collectionnow receives the processor and the subset names. The model hookcreate_quantization_layer_output_writerstill comes first, unchanged; the ds4rt models keep it until PR-E1. After the hook, a pass spills whenprocessor.calibration.spill_pathis set and the pass can produce every batch, which covers layer replays and the native-capture subset forward. A subset forward whose capture hooks stop each batch early (replay_after_processorsubset_early_stop) yields no output, so it keeps the list.looper/stage_inputs_capture.py,module_looper.py:cache_inputs(..., spill_path=). After each calibration example the captured batch moves into the writer, so the capture never holds the full set. Three captures stay in memory: concurrent module-tree branches, captures of unknown length, and captures with extra positional layer inputs (Gemma 3n/4 per-layer inputs), which the one-tensor file format cannot hold.looper/stage_layer.py: beforelm_head_pre_quantize_generate_hook, a cache that is not a list is copied into lists. The hook rewrites batches in place, and a spilled cache hands out fresh lists, so without the copy the head would calibrate on un-normed inputs.looper/continuation.py:ContinuationCodecencodes a spilled sequence as the list it stands for and keeps the read batches alive until the encode ends, so a later tensor cannot reuse anidalready in the dedup table. Spilled and in-memory runs therefore resume from each other's checkpoints. The resumed layer's inputs come back in memory, and the layers after it spill again.docs/calibration-config.md: new section "Spilling layer inputs to disk", with the flow diagram and limits. One README line.configure_*enablers have no in-tree caller.qcfg.meta["ds4rt_*"]spill switch on main to alias or remove. feat(looper): add authenticated disk-backed layer outputs #3588 was enabled only by the per-modelconfigure_base_replay_store/configure_mtp_activation_storehooks (no in-tree caller), and those stay until PR-E1.CalibrationConfig.spill_pathis the only new switch; no meta key is read.Map deviations (re-verified on efc3239):
utils/atomic_io.pydedup was dropped. Four of the fivecanonical_json/fsynccopies live in EXL3 files that PR-E1/X1 delete, so the dedup would touch EXL3 code for no lasting gain.spill_shard_batcheswas dropped. One file per batch needs no knob, and the multi-batch staging path stays only for the ds4rt hooks.CalibrationConfigis atconfig.py:401(map: 352), the writer and sequence atinput_cache.py:179-656(map: 271-695), andstage_layer.py:1078-1084no longer exists (refactor(looper): fold quantization_layer_boundary_checkpoint into LoopExtensions #6477).Tests
New tests:
tests/test_checkpoint_quantization.py::test_spilled_layer_inputs_are_bit_identical_and_resume[llama-cpu, qwen3_moe-cpu, llama-cpu-lm_head, llama-cuda, qwen3_moe-cuda]quantize(). Exactly the capture (written from CPU) and layer 0's replay (written from the layer device) are spilled, plus layer 1's replay withlm_head. Every saved tensor is bit-identical to spill off. The spill dir is empty afterwards. Spill plusCheckpointConfig(interval="subset:1")is stopped atmodel.layers.1:subset1, resumed with spill, and the result is bit-identical.tests/test_disk_backed_layer_outputs.py::test_spilled_batches_read_back_on_the_device_they_were_written_from__getitem__andbatch_placement. A reopened sequence still reads CPU.tests/test_disk_backed_layer_outputs.py::test_spilled_batches_keep_their_dtype[float32/float16/bfloat16]tests/test_disk_backed_layer_outputs.py::test_spilled_pinned_batch_is_not_retainedtests/test_disk_backed_layer_outputs.py::test_spill_writer_rejected_geometry_leaves_no_directorytests/test_disk_backed_layer_outputs.py::test_spilled_cuda_batch_reads_back_on_cudacuda:0.tests/test_disk_backed_layer_outputs.py::test_spill_writer_files_live_exactly_as_long_as_their_sequencetests/test_disk_backed_layer_outputs.py::test_forward_executor_spills_only_complete_passes[...]spill_path=None/need_outputs=False.tests/test_calibration_config.py::test_defaults_match_the_previous_quantize_defaults,test_invalid_fields_are_rejected[...]None; a non-path value raisesTypeError.Red evidence: each defect below was injected into a disposable worktree of this branch (
scratch/red.sh), and the guarding test failed at the intended point.test_spilled_batches_read_back_on_the_device_they_were_written_fromassert 'cpu' == 'meta'test_spilled_layer_inputs_are_bit_identical_and_resume[llama-cpu]FileNotFoundError: .../spill/shared/layer-000000/outputs-000000.safetensors(the capture's cleanup deletes the replay's files)...resume[llama-cpu]TypeError: unsupported continuation value: DiskBackedLayerOutputSequenceat the subset checkpointlm_head_pre_quantize_generate_hook...resume[llama-cpu-lm_head]AssertionError: lm_head.qweightdiffers from spill offtest_forward_executor_spills_only_complete_passes[forward2-...]assert True is False(a writer thatfinalize()would reject withcoverage is incomplete)test_spill_writer_files_live_exactly_as_long_as_their_sequenceFileNotFoundErrorreading a live sequenceCommands and results (this branch at
fff5abe57, origin/mainefc323957):Skips and what they leave unverified:
lm_headaccelerator nodes, and the two-CUDA-devicetest_calibration_data_devicenodes. The CUDA spill nodes were run on GPU 4 (above).exllamav3is not installed. There is also noqcfg.meta["ds4rt_*"]spill switch on main to alias or remove: feat(looper): add authenticated disk-backed layer outputs #3588 was enabled only by the per-modelconfigure_base_replay_store/configure_mtp_activation_storehooks (no in-tree caller), and those stay until PR-E1.CalibrationConfig.spill_pathis the only new switch.efc323957; the required GPTQ/AWQ/OLMoE A/B was re-run.calibration_data_device="balanced"with spill) are untested. The per-batch recorded device is built to keep balanced placement, but only one GPU was available.-m checkpoint_recoverysubprocess matrix was not re-run onefc323957; the previous run of this branch gave 73 passed, 15 skipped.InputCache, and G2PTQ's early-stopping subset forward is covered by the executor unit test, but no end-to-end run was made.Measured Impact
GPU A/B on GPU 4 (
CUDA_VISIBLE_DEVICES=4, otherwise idle). Setup:BACKEND.TORCH, seed 0; 128 wikitext-2 rows x 512 tokens,batch_size=8, 16 batches. Hidden set 112 MiB.batch_size=8. Hidden set 128 MiB.torch.cuda.max_memory_allocated()duringquantize()minus the allocation at its start. Peak host = RSS/anon sampled every 20 ms duringquantize()minus the value at its start.Equivalence when off (origin/main
efc323957vs this branch,spill_path=None):Capability (this branch,
spill_pathon the host NVMe vsNone):quantize()quantize(): Qwen GPTQ 12.1 s off / 23.9 s on; Qwen AWQ 54.5 s off / 59.9 s on; OLMoE GPTQ 194.9 s off / 136.6 s on (the OLMoE run-to-run spread is larger than the spill cost). Spill trades I/O time for memory.quantize().Model Support / Module Plan
Not applicable. No model, alias, definition or module tree changes.
AWQ onboarding safety
Not applicable: AWQ grouping, search, replay and folding are untouched. AWQ reads the same
InputCacheand now gets spilled batches on their original device. AWQ with spill is bit-identical to AWQ without spill (table above).Logic Flow Documentation
file:lineevidence.docs/repeats the diagrams, titled for the mechanism, and is linked fromREADME.md(docs/calibration-config.md, linked from the README's calibration paragraph).flowchart TD Q["quantize(CalibrationConfig(spill_path=dir))"] --> C["StageInputsCapture.cache_inputs"] C --> CS{"spill_path set, batch count known,<br/>single branch"} CS -- "no" --> CL["capture list in memory"] CS -- "yes" --> CB{"first batch has<br/>one positional tensor"} CB -- "no (Gemma 3n/4)" --> CL CB -- "yes" --> W["spill_writer(...).put(i, batch)<br/>one file per batch, no fsync"] F["ForwardExecutor._output_collection"] --> H{"model hook<br/>create_quantization_layer_output_writer"} H -- "writer" --> HW["model writer (ds4rt, unchanged)"] H -- "none" --> E{"spill_path set and pass<br/>cannot stop early"} E -- "no" --> FL["list in memory"] E -- "yes" --> W W --> S["DiskBackedLayerOutputSequence<br/>batch i read on its recorded device"] S --> N["next layer: subset forwards, replay,<br/>AWQ / GPTAQ / Paro / G2PTQ consumers"] S -- "lm_head stage" --> LH["copied to lists before<br/>lm_head_pre_quantize_generate_hook"] S -- "CheckpointConfig boundary" --> K["ContinuationCodec: encoded as the list it replaces"] S -- "last reference dropped" --> D["weakref.finalize: rmtree its directory"] W -- "pass fails before finalize" --> D2["writer finalizer: rmtree"] W -- "batch count differs at finalize" --> X["RuntimeError: coverage is incomplete"] style X fill:#ffe8e8,stroke:#cc3333forward_executor.py:67-91callscreate_quantization_layer_output_writer, which returns a writer only afterconfigure_base_replay_store(deepseek_v4.py:304,glm5_next.py:378,glm_moe_dsa.py:112, no in-tree caller)CalibrationConfig.spill_pathfor any processor (forward_executor.py:101-114)stage_inputs_capture.py:446)spill_writerafter each example (stage_inputs_capture.py:673-676, finalized at:757)input_cache.py:357)input_cache.py:306; recorded at:542)input_cache.py:627-661); ds4rt hooks unchangedTypeError: unsupported continuation value(continuation.py:101-118)continuation.py:100-103)lm_headinput norm on a lazy cachestage_layer.py:834)stage_layer.py:834-837)TensorLifetimeDiagnostic(input_cache.py:76-170), no production consumer since #6477Review Requirements
AI-assisted code is welcome. Open the PR as a draft. Mark it ready only after
review and after GitHub confirms the pushed head has no conflicts with the
current remote base.
I or an AI agent (such as Codex or Claude) have:
Kernel Accuracy Requirements
Not applicable: no kernel, packer or dispatch change. Spilled bf16 batches go through safetensors losslessly; the A/B is bit-identical.
Notes
CheckpointStoreis the map's longer-term idea and a possible follow-up._extract_cache_batch_lengths).expected_batchesmust match exactly. A capture whose examples do not all reach the first layer would fail at finalize withcoverage is incomplete. No such case is known for the single-branch capture (every example raisesStopForwardat the first layer).spill_path. Nothing is written under the model output directory, and no default directory is derived from it; each writer's private subdirectory is removed when its sequence is collected.🤖 Generated with Claude Code