Repository navigation
Conversation
ivy-zhou
requested review from
fegin,
tianyu-l,
wconstab and
wwwjn
as code owners
August 22, 2026 02:07
This was referenced Aug 22, 2026
tianyu-l
approved these changes
Aug 31, 2026
ivy-zhou
force-pushed
the
pr4279
branch
2 times, most recently
from
September 1, 2026 16:50
02b6c61 to
662a9ee
Compare
ivy-zhou
force-pushed
the
pr4279
branch
2 times, most recently
from
September 4, 2026 03:49
a374426 to
13de887
Compare
ivy-zhou
added a commit
that referenced
this pull request
Sep 4, 2026
Summary: Run retention only after the previous save has completed and before the next save starts. `_purge_stale_checkpoints` receives the step being saved so rank 0 can preserve the exact current published and staging directory names even if another rank creates them while cleanup is running. This avoids a cross-rank barrier in the checkpoint save path. The method accepts an optional staging directory prefix and matches those directories separately instead of teaching `_parse_step` about backend-specific temporary names. Valid published checkpoints alone participate in retention, and the manager keeps `keep_latest_k - 1` of them to reserve a slot for the current save. Unknown directory names remain untouched. Abandoned directories from other steps use the existing purge thread. The current step is excluded before paths are queued, so background deletion cannot target the active save. The DCP manager moves its purge call from after save dispatch to the settled window before dispatch and passes the current step. Test Plan: `pytest tests/unit_tests/cpu/test_checkpoint.py tests/unit_tests/cpu/test_torch_checkpointing.py -q` 64 passed. Tests cover DCP purge ordering, current-save protection, retention slot reservation, incomplete checkpoint cleanup through the purge thread, and canonical parsing. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4197). * #4457 * #4277 * #4279 * #4278 * #4191 * #4190 * #4189 * #4188 * __->__ #4197
ivy-zhou
added a commit
that referenced
this pull request
Sep 4, 2026
Summary: `TorchCheckpointingManager` has been config-only since #4058: it builds its backend and then raises `NotImplementedError` from every operation. This implements the save path against that backend, leaving load for a later change. Saves follow the same cadence contract as the DCP manager -- interval, first step, and last step -- and hand the flattened state dict to the backend, which returns a future tracked in `save_future` and awaited by `maybe_wait_for_saving`. On a step where no save is due, the manager prewarms the backend's staging buffers once, so the first real save does not also pay for pinned-memory allocation. The manager constructs each backend configuration from a concrete saver configuration. Regular saves use an asynchronous saver with pinned-memory staging and a checkpoint barrier. Load-only runs use a synchronous saver with no barrier. The final write uses a fresh synchronous saver with a barrier so it must complete before the process exits. Building each mode directly avoids copying and incrementally rewriting nested dataclass configurations. Backend storage is a defaulted `__init__` parameter rather than a `Config` field. `Configurable.Config` is Tyro-parsed, and a backend storage object is not a command-line option; callers needing remote storage pass it programmatically. The backend config receives the same storage object, so saves, loads, and path probes agree. Retention reuses the shared `purge_thread` worker from `checkpointer/base.py`, draining through the backend `Storage` abstraction rather than the filesystem directly, and matches the same `step-(\d+)` names the DCP manager purges. `last_save_in_hf` is rejected in `Config.__post_init__`; HF export lands in a later change and would otherwise fail deep in the backend. This adapts the implementation to the current OSS layout: `components/torch_checkpointing_manager.py` is now `components/checkpointer/torch_checkpointing.py`, `CheckpointManagerConfig` is `BaseCheckpointManager.Config`, `purge_worker` is `purge_thread`, and `LRSchedulersContainer` comes from `components.optimizer`. The earlier version also carried its own `if not self.enable` guard in every public method; those are gone, since the base class now owns that check and dispatches to the `_save` / `_wait_for_saving` / `_maybe_wait_for_staging` / `_close` hooks. `_should_save` and `_create_checkpoint_id` move to the base because they depend only on fields already declared by `BaseCheckpointManager.Config`. Retention, step discovery, state selection, and the final-step payload stay per-manager because each backend reaches storage differently. Test Plan: `pytest tests/unit_tests/cpu/test_torch_checkpointing.py`: 23 passed. The tests cover save cadence and future tracking, prewarm running once before the first scheduled save, load-only selecting a synchronous barrier-free backend, load-only never constructing a barrier, staging waits through the backend lock, configured save timeouts, cleanup after failed saves, retention, and the final synchronous model-only save. Also verified: - The required backend APIs exist in `torch_checkpointing` 0.1.0. - `TorchCheckpointingManager.__abstractmethods__` is empty. - `ufmt` and `flake8 --config=.flake8` pass on both changed files. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4188). * #4457 * #4277 * #4279 * #4278 * #4191 * #4190 * #4189 * __->__ #4188
ivy-zhou
added a commit
that referenced
this pull request
Sep 8, 2026
Summary: `torch_checkpointing` emits `EventLogger` metadata on ordinary Python logging records. TorchTitan kept its structured handlers on a separate non-propagating logger, so those backend records reached the console but not the structured log. Install one private handler on the root logger during `init_structured_logger()`. It forwards records carrying `log_type_name` to TorchTitan's structured handlers and ignores plain text. The forwarding stays private to the structured logging implementation instead of adding a backend-specific public API. Async writers start in a fresh process. The backend-config factory stores the resolved parent source, output directory, and rank in the subprocess init arguments. The child runs any existing initializer first, restores TorchTitan structured logging, and admits backend INFO events only when the backend logger is unset and inherits a stricter level. Explicit DEBUG, WARNING, and ERROR settings remain unchanged. Preserve the backend's `context` and `measured_from_start_time_ms` fields in JSONL output, and stamp `checkpoint_logging_context` with the save step before the backend snapshots it for asynchronous work. Test Plan: `pytest tests/unit_tests/cpu/test_torch_checkpointing.py`: 27 passed. The tests cover handler forwarding, field preservation, subprocess logger initialization, composition with an existing subprocess initializer, and save step propagation. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4189). * #4457 * #4277 * #4279 * #4278 * #4191 * #4190 * __->__ #4189
ivy-zhou
added a commit
that referenced
this pull request
Sep 8, 2026
Summary:
`TorchCheckpointingManager` rejected `last_save_in_hf` because the
backend
writes one shard per rank while Hugging Face consumers expect a
consolidated
safetensors checkpoint. Implement that consolidation and lift the
rejection.
On a final save with `last_save_in_hf`, the model state is converted
through
the state dict adapter's `to_hf`, and the model item receives a
safetensors
layout so each rank writes `model_{rank}.safetensors`. Those shards go
into a
nested `sharded/` directory. The backend's `pre_finalize_callback`
merges them
into the checkpoint directory before publication, so readers never
observe the
sharded intermediate state.
The callback reuses the manager's configured storage, falling back to
local
filesystem storage with direct IO disabled. The backend-config factory
accepts
the HF item schema and callback directly rather than constructing a
config and
then rewriting its dataclass fields.
Only the final save changes. Periodic saves remain in native format,
matching
the DCP manager where `last_save_in_hf` is also a final-save-only
option. The
preceding commit's temporary validation is removed now that this path
exists.
Test Plan:
`pytest tests/unit_tests/cpu/test_torch_checkpointing.py`: 30 passed.
The HF final-save test checks state-dict conversion, the nested shard
path, the
safetensors layout, consolidation arguments, storage reuse, and
publication
through the pre-finalize callback.
Also verified:
- The required consolidation, layout, callback, and storage APIs exist
in
`torch_checkpointing` 0.1.0.
- `ufmt` and `flake8 --config=.flake8` pass on both changed files.
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with
[ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4190).
* #4457
* #4277
* #4279
* #4278
* #4191
* __->__ #4190
fegin
approved these changes
Sep 9, 2026
Comment on lines
+493
to
+504
| if async_save_started_at is not None: | ||
| assert self.save_future is not None | ||
| self.save_future.add_done_callback( | ||
| lambda _: sl.log_trace_scalar( | ||
| { | ||
| "train.checkpoint_write.native_dcp.execute.async_total.latency_ms": ( | ||
| time.monotonic() - async_save_started_at | ||
| ) | ||
| * 1000 | ||
| } | ||
| ) | ||
| ) |
Contributor
There was a problem hiding this comment.
This is only the staging cost, right?
Contributor
Author
There was a problem hiding this comment.
It should track the full save future no? I'm a bit confused why this is only the staging?
ivy-zhou
added a commit
that referenced
this pull request
Sep 10, 2026
Summary: `TorchCheckpointingManager` could save but not load: `_load` raised `NotImplementedError`, so a run configured for this backend could write checkpoints and never resume from them. Implement the native load path, completing the round trip. Resolution mirrors the DCP manager. With no explicit step, the latest valid step in the checkpoint folder is used; with an explicit step, a missing folder or missing checkpoint is an error rather than a silent fresh start. When no step is found, `initial_load_path` is used if configured, and otherwise the run starts fresh. Step 0 is treated as a seed checkpoint and loads model state only. Step discovery only accepts directories that actually contain the backend's `metadata.pkl`. A crashed save leaves a `step-N` directory with no metadata, and without this check that partial directory would win the `max()` and be loaded as the resume point. Directory listing, existence checks, and the load itself all go through the configured `Storage`, so remote checkpoint folders work the same as local ones. The backend returns a plain dict rather than writing through the live objects, so `_restore_state_dict` puts values back: `Stateful` entries get `load_state_dict`, plain dicts are updated in place so callers holding a reference see the result, and anything else that is not already the same object raises rather than being silently skipped. Keys in `exclude_from_loading` are dropped before the load, and an excluded key that is not in the state dict is an error, matching the DCP manager. Hugging Face loads are explicitly rejected for now; they land separately. Ported from an internal change. Besides the path and naming translation, the internal version defines `load()` with its own `if not self.enable` guard; here the body moves to the `_load` hook and the guard is dropped, since `BaseCheckpointManager` owns it. Test Plan: `pytest tests/unit_tests/test_torch_checkpointing.py`: 24 passed. Four new tests: an explicit-step load restores both model weights and optimizer state from the backend payload and passes the full state dict as the load target; a latest-step load of `step-0` requests model state only; discovery and load go through a configured non-local `Storage` rather than the filesystem; and a folder containing valid `step-2` and `step-5`, a metadata-less `step-8`, and a `tmp_step-9` resolves to `step-5`, so an interrupted save is not mistaken for the newest checkpoint. `pytest tests/unit_tests/test_checkpoint.py tests/unit_tests/observability/ torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py` alongside the above: 147 passed, 2 subtests passed. Also verified: - `TorchCheckpointingManager.__abstractmethods__` is empty; with `_load` implemented the manager now satisfies the full `BaseCheckpointManager` contract. - `METADATA_FILE_NAME` and `CheckpointManager.load(checkpoint_id, into=...)` exist in `torch_checkpointing` 0.1.0. - `ufmt` and `flake8 --config=.flake8` clean on both changed files. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4191). * #4457 * #4277 * #4279 * #4278 * __->__ #4191
ivy-zhou
added a commit
that referenced
this pull request
Sep 10, 2026
Summary: Move `checkpoint_save` and `checkpoint_load` tracing to the guarded public methods on `BaseCheckpointManager`. This gives every checkpoint backend one consistent trainer-facing timing boundary while keeping disabled managers silent and avoiding duplicate backend spans. Test Plan: `PYTHONPATH=/tmp/torchtitan-additional-packages.iGrJ91/checkpointing /home/ivyzhou/local/torchtitan-venv/bin/python -m pytest tests/unit_tests/test_checkpoint.py -q` (55 passed) `PYTHONPATH=/tmp/torchtitan-additional-packages.iGrJ91/checkpointing /home/ivyzhou/local/torchtitan-venv/bin/python -m pytest tests/unit_tests/test_torch_checkpointing.py -q` (36 passed) `PYTHONPATH=/tmp/torchtitan-additional-packages.iGrJ91/checkpointing /home/ivyzhou/local/torchtitan-venv/bin/python -m pytest torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py -q` (2 passed) `PATH=/home/ivyzhou/local/torchtitan-venv/bin:$PATH PYTHONPATH=/tmp/torchtitan-additional-packages.iGrJ91/checkpointing /home/ivyzhou/local/torchtitan-venv/bin/pre-commit run --all-files` (passed) --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4278). * #4457 * #4277 * #4279 * __->__ #4278
Summary: Record native DCP asynchronous save latency from entry into dcp_save until the returned save future completes. Capture one monotonic timestamp at submission and attach a completion callback that subtracts it from the completion timestamp and emits the structured metric. The metric measures the save future lifetime, not filesystem-only write time. The existing wait path remains responsible for surfacing save failures. Test Plan: env TORCH_DISABLE_ADDR2LINE=1 PYTHONPATH=/data/users/ivyzhou/torchtitan:/tmp/torchtitan_additional_packages_3e4a.nRk7S7/checkpointing:/tmp/torchtitan_additional_packages_3e4a.nRk7S7/ao:/tmp/torchtitan_additional_packages_3e4a.nRk7S7/torchtitan_runtime_deps /home/ivyzhou/local/torchtitan-venv/bin/python -m pytest tests/unit_tests/observability/test_structured_logging.py tests/unit_tests/test_checkpoint.py -q 138 passed. Changed-file pre-commit hooks passed, including ufmt, flake8, pydoclint, codespell, and Pyrefly.
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:
Record native DCP asynchronous save latency from entry into dcp_save until the returned save future completes. Capture one monotonic timestamp at submission and attach a completion callback that subtracts it from the completion timestamp and emits the structured metric.
The metric measures the save future lifetime, not filesystem-only write time. The existing wait path remains responsible for surfacing save failures.
Test Plan:
env TORCH_DISABLE_ADDR2LINE=1 PYTHONPATH=/data/users/ivyzhou/torchtitan:/tmp/torchtitan_additional_packages_3e4a.nRk7S7/checkpointing:/tmp/torchtitan_additional_packages_3e4a.nRk7S7/ao:/tmp/torchtitan_additional_packages_3e4a.nRk7S7/torchtitan_runtime_deps /home/ivyzhou/local/torchtitan-venv/bin/python -m pytest tests/unit_tests/observability/test_structured_logging.py tests/unit_tests/test_checkpoint.py -q
138 passed.
Changed-file pre-commit hooks passed, including ufmt, flake8, pydoclint, codespell, and Pyrefly.
Stack created with Sapling. Best reviewed with ReviewStack.