Skip to content

Consolidate torch_checkpointing HF final saves - #4190

Merged
ivy-zhou merged 1 commit into
mainfrom
pr4190
Sep 8, 2026
Merged

ivy-zhou merged 1 commit into
mainfrom
pr4190

Conversation

@ivy-zhou

@ivy-zhou ivy-zhou commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

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.

Stack created with Sapling. Best reviewed with ReviewStack.

@meetv18

meetv18 commented Aug 19, 2026

Copy link
Copy Markdown

do we have consolidation numbers for DCPv1 v/s v2? I would suggest to add to the test plan of this diff the following:

  1. Bitwise identical HF checkpoints between DCPv1 and DCPv2
  2. Latency regression checks for E2E HF checkpoint writing (incl. consolidation).

ivy-zhou added a commit that referenced this pull request Aug 19, 2026
…4183)

Pyrefly reports three errors in this file, all of them real:

_save was declared "-> None" while the base declares "-> bool", and it
discarded super()._save()'s result. BaseCheckpointManager.save returns
whatever
_save returns, so save() handed back None for this manager. Nothing
consumes it
today -- torchft/trainer.py ignores the result -- but the contract was
broken
and the next caller to check it would have been surprised. A replica
that skips
the full save now reports False; the per-replica dataloader checkpoint
is a side
channel, not the checkpoint this value describes.

_wait_for_saving dereferenced save_future without narrowing it. The
base's
maybe_wait_for_saving guarantees it is set before dispatching here,
which the
comment already said, so this just asserts what the comment claims.

_ft_save assigned dcp_save's "Future | AsyncSaveResponse | None"
straight into
save_future, typed "Future | None". AsyncMode.ASYNC always yields a
plain
Future, so assert that, matching how the DCP manager narrows the same
call in
its own ASYNC branch.

Only the first of the three is new: it arrived with the disabled-guard
refactor
(#4173), which renamed save to _save and made the base's return type
load
bearing. The other two predate it.

Test Plan:
  python3 -m pyrefly check torchtitan/experiments/torchft/checkpoint.py
  -> 0 errors (was 3)

python3 -m pytest
torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py -q
  -> 2 passed

Adds a test covering both branches of the participating_rank guard, so
the
return value is pinned rather than left to the type checker.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with
[ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4183).
* #4191
* #4190
* #4189
* #4188
* #4197
* #4187
* #4186
* #4185
* #4184
* __->__ #4183
ivy-zhou added a commit that referenced this pull request Aug 20, 2026
Summary:
`components/checkpoint.py` is the last of the three re-export shims left
behind
when the checkpointer was grouped into a package, after the lr_scheduler
shim
in #4172 and checkpoint_utils in the preceding change. With it gone
there are
no compatibility shims left under `torchtitan/components/`.

This one is a pure module rename at the callsite.
`checkpointer/__init__.py` already re-exports exactly the same eight
symbols
the shim forwarded -- `AsyncMode`, `CheckpointManager`, `ModelWrapper`,
and the
`MODEL` / `OPTIMIZER` / `LR_SCHEDULER` / `DATALOADER` / `TRAIN_STATE`
key
constants -- so every importer changes only the module it names, with
the
imported names and their grouping untouched. Verified by parsing each
importer
and checking every imported symbol against the package's `__all__`
before
touching anything; nothing referenced a symbol the package does not
expose, and
no callsite used the plain `import torchtitan.components.checkpoint`
form.

Thirty modules are updated, spanning the checkpoint-conversion scripts,
the
forge, torchft, graph_trainer and rl experiments, and the unit tests. A
thirty-first file, `experiments/rl/__init__.py`, carries the import
inside its
module docstring as a usage example; that is updated too, so the
documented
path matches the working one.

This is an import-path change only; no runtime behavior changes.

Test Plan:
Full `pytest tests/unit_tests` (excluding `test_rope.py`, which cannot
be
collected without the optional `fla` package): 622 passed, 18 failed.
The 18
are the same set that fails on unmodified main in this environment --
missing
optional dependencies (`transformers`, `fla`) and environment-specific
kernel/compile failures (helion rope, inductor lora).

Also verified:
- No `components.checkpoint` references remain anywhere in the repo,
across all
  file types, and no `Compatibility imports` shim remains under
  `torchtitan/components/`.
- `import torchtitan.components.checkpoint` now raises
`ModuleNotFoundError`.
- All eight symbols import cleanly from
`torchtitan.components.checkpointer`.
- All 31 changed files byte-compile, and the affected non-test modules
(`trainer`, `forge.engine`, `torchft.checkpoint`, `torchft.optimizer`,
both
checkpoint-conversion scripts) import cleanly. `experiments.rl` fails
only on
  the absent optional `vllm` package, unrelated to this change.
- `ufmt` and `flake8 --config=.flake8` clean on all 31 files.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with
[ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4184).
* #4240
* #4230
* #4191
* #4190
* #4189
* #4188
* #4197
* #4187
* #4186
* #4185
* __->__ #4184
# backend metadata sits in the nested "sharded" directory the shards
# were written to, and the root holds the consolidated HF files. Probing
# only for the former would classify a finished export as abandoned and
# let the next run's retention delete it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

iiuc, this comment wants to say either torch_checkpointing root file existence or hf index file existence is a valid checkpoint. But the comment is too convoluted.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please fix this comment.

).build()
storage_config=storage_config,
items=item_specs,
pre_finalize_callback=pre_finalize_callback,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

when will pre_finalized_callback be called?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

After all of the ranks have finished writing, but before the atomic rename of the temp dir: meta-pytorch/torch_checkpointing@912006f

@ivy-zhou
ivy-zhou force-pushed the pr4189 branch 2 times, most recently from a26789f to 54400de Compare September 4, 2026 03:58
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

@fegin fegin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please address the two comment issues before landing.

# The backend hands the callback the directory the shards were
# actually written to -- its staging directory when a write barrier
# is configured, the final path otherwise -- so consolidate from
# that path as given, deriving nothing from it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Let's add a comment saying that consolidate_hf_safetensors_checkpoint will call barrier.

# backend metadata sits in the nested "sharded" directory the shards
# were written to, and the root holds the consolidated HF files. Probing
# only for the former would classify a finished export as abandoned and
# let the next run's retention delete it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please fix this comment.

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
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.
@ivy-zhou
ivy-zhou changed the base branch from pr4189 to main September 8, 2026 15:19
@ivy-zhou
ivy-zhou merged commit 85f88b3 into main Sep 8, 2026
31 of 40 checks passed
tianyu-l pushed a commit that referenced this pull request Sep 11, 2026
Follow-up to #4190.  

That PR required moving the pre_finalize callback to *after* the barrier
(meta-pytorch/torch_checkpointing@912006f).
Turns out there are use cases which need this callback to run *before*
the barrier. I've got a diff up to move it back (D119246630).

The last save step is happening synchronously in the main process, so we
are free to use our own `dist.barrier` inside the callback to recover
the previous behaviour. `consolidate_hf_safetensors_checkpoint` already
uses `dist.barrier` internally, so this doesn't add any additional sync
points.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants