Skip to content

Add torch_checkpointing save config plumbing - #4058

Merged
ivy-zhou merged 1 commit into
pytorch:mainfrom
ivy-zhou:export-D112860926
Aug 17, 2026
Merged

ivy-zhou merged 1 commit into
pytorch:mainfrom
ivy-zhou:export-D112860926

Conversation

@ivy-zhou

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

Copy link
Copy Markdown
Contributor

Summary:
Introduce TorchCheckpointingManager as an independent Configurable component
rather than adding backend selectors and branches to the legacy DCP
CheckpointManager.

TorchCheckpointingManager.Config intentionally adds no fields beyond
BaseCheckpointManager.Config, but it must still be declared: Config._owner is
set on the class that declares it, so a subclass that inherited Config
unchanged would build the abstract base. It remains buildable for Trainer
construction, while TorchCheckpointingManager constructs its fixed
torch_checkpointing backend internally. The backend supplies the model and
optimizer DTensor resharding schema, pinned-memory async staging, and the
TorchTitan TCPStore barrier without exposing backend resharders or callbacks
through TorchTitan configuration or Tyro.

The manager lives at components/checkpointer/torch_checkpointing.py, named to
match its siblings base.py and dcp.py. It is not re-exported from
checkpointer/__init__.py; it is selected by config, not by import.

When checkpointing is disabled, load, save, and maybe_wait_for_staging are
no-ops, matching the DCP manager. When it is enabled they raise
NotImplementedError: the routing lands in later changes, and they are stubbed
rather than omitted because BaseCheckpointManager declares them abstract, so a
partial implementation could not be instantiated at all.

torch_checkpointing moves from an optional extra to a required dependency in
pyproject.toml, superseding the optional-dependency arrangement added in
#4123. Note this makes it the only core dependency with an unconditional
torch requirement (torch>=2.6.0); the others declare torch only under
extras. pip install torchtitan will therefore pull a stable torch wheel,
which users who installed a nightly first should be aware of.

It is deliberately NOT added to .ci/docker/requirements.txt. That file is
symlinked from the repo root, so one entry feeds both the Docker image build
and the lint job, and it is installed with dependencies -- which would drag a
stable torch into an image whose stated invariant is that it ships no torch and
every job installs a nightly. The image already installs the library, from git
@main with --no-deps, in .ci/docker/common/install_conda.sh. The lint job
needs it importable too, because pyrefly type-checks
components/checkpointer/torch_checkpointing.py, so it gets the same
--no-deps install, ordered after the nightly torch install so it cannot
displace it.

Selecting TorchCheckpointingManager.Config selects the implementation; the
legacy manager and its config remain unchanged.

Rebased onto main at 0d2438f ("Add remat as an optional dependency",
#4163). That change added a remat optional-dependency group immediately after
the torch-checkpointing group this commit deletes, so the two collided in
pyproject.toml; the resolution keeps remat and drops torch-checkpointing,
which is this commit's intent unchanged.

Test Plan:
pytest tests/unit_tests at the top of the rebased stack: 624 passed, 18
failed. Every failure reproduces identically on unmodified remote/main
(0d2438f) in the same environment, so none are attributable to this change.
They split into missing optional dependencies (transformers for the flux
config and dataset tests, fla for the qwen3.5 rope test) and
environment-specific kernel/compile failures (14 helion rope tests, one
inductor C++ compile error in lora).

Scoped to the code this stack touches -- test_checkpoint,
test_state_dict_keys, test_lr_scheduler, test_torch_checkpointing,
test_config_manager -- 85 passed, with only the known transformers failure.

Also verified:

  • TorchCheckpointingManager subclasses BaseCheckpointManager and its
    Config._owner resolves to itself.
  • torchtitan.components.checkpointer.torch_checkpointing imports standalone.
  • The resolved pyproject.toml parses under tomllib, with
    torch_checkpointing>=0.1.0 in the core dependency list and the optional
    groups reduced to exactly dev and remat.
  • ufmt and codespell clean on the changed files; flake8 --config=.flake8
    clean apart from one F824 in graph_trainer/simple_fsdp.py that is
    pre-existing on main and untouched here.

Stack created with Sapling. Best reviewed with ReviewStack.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 3, 2026
@meta-codesync

meta-codesync Bot commented Aug 3, 2026

Copy link
Copy Markdown

@ivy-zhou has exported this pull request. If you are a Meta employee, you can view the originating Diff in D112860926.

@meta-codesync meta-codesync Bot changed the title Add torch_checkpointing save config plumbing Add torch_checkpointing save config plumbing (#4058) Aug 5, 2026
ivy-zhou added a commit to ivy-zhou/torchtitan that referenced this pull request Aug 5, 2026
Summary:

Adds TorchTitan-facing configuration for selecting the `torch_checkpointing` save backend and configuring backend-specific behavior. The default remains DCP, the `torch_checkpointing` options are scoped under their own dataclass, and validation rejects unsupported backend values and HF final-save mode for the new backend.

Differential Revision: D112860926
@ivy-zhou
ivy-zhou force-pushed the export-D112860926 branch from 8670204 to 2c4efb2 Compare August 5, 2026 17:26
Comment thread torchtitan/components/checkpoint.py Outdated
Comment on lines +405 to +411
save_backend: Literal["dcp", "torch_checkpointing"] = "dcp"
"""Checkpoint save backend. `dcp` keeps current behavior."""

torch_checkpointing: TorchCheckpointingConfig = field(
default_factory=TorchCheckpointingConfig
)
"""Options that only apply when `save_backend="torch_checkpointing"`."""

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.

How does this compare with "having another CheckpointManager"?

I feel intertwining the logic would make it difficult to read / review / deprecate DCPv1.

ivy-zhou added a commit to ivy-zhou/torchtitan that referenced this pull request Aug 10, 2026
Summary:

Adds TorchTitan-facing configuration for selecting the `torch_checkpointing` save backend and configuring backend-specific behavior. The default remains DCP, the `torch_checkpointing` options are scoped under their own dataclass, and validation rejects unsupported backend values and HF final-save mode for the new backend.

Differential Revision: D112860926
ivy-zhou added a commit to ivy-zhou/torchtitan that referenced this pull request Aug 11, 2026
Summary:

Adds TorchTitan-facing configuration for selecting the `torch_checkpointing` save backend and configuring backend-specific behavior. The default remains DCP, the `torch_checkpointing` options are scoped under their own dataclass, and validation rejects unsupported backend values and HF final-save mode for the new backend.

Differential Revision: D112860926
ivy-zhou added a commit to ivy-zhou/torchtitan that referenced this pull request Aug 11, 2026
Summary:

Adds TorchTitan-facing configuration for selecting the `torch_checkpointing` save backend and configuring backend-specific behavior. The default remains DCP, the `torch_checkpointing` options are scoped under their own dataclass, and validation rejects unsupported backend values and HF final-save mode for the new backend.

Differential Revision: D112860926
ivy-zhou added a commit to ivy-zhou/torchtitan that referenced this pull request Aug 12, 2026
Summary:

Introduce `TorchCheckpointingManager` as an independent `Configurable` component rather than adding backend selectors and branches to the legacy DCP `CheckpointManager`.

`TorchCheckpointingManager.Config` intentionally adds no fields beyond `CheckpointManagerConfig`. It remains buildable for `Trainer` construction, while `TorchCheckpointingManager` constructs its fixed `torch_checkpointing` backend internally. The backend supplies the model and optimizer DTensor resharding schema, pinned-memory async staging, and TorchTitan TCPStore barrier without exposing backend resharders or callbacks through TorchTitan configuration or Tyro.

A dedicated Buck target owns the `torch_checkpointing` dependency while the core `torchtitan_lib` remains independent. Selecting `TorchCheckpointingManager.Config` selects the implementation; the legacy manager and its config remain unchanged.

Differential Revision: D112860926
@ivy-zhou
ivy-zhou requested a review from felipemello1 as a code owner August 12, 2026 21:01
TRAIN_STATE = "train_state"


class CheckpointManagerProtocol(Protocol):

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.

This is duck-typing only?

def close(self) -> None: ...


def purge_worker(

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.

private helper?

Suggested change
def purge_worker(
def _purge_worker(



@dataclass(kw_only=True, slots=True)
class CheckpointManagerConfig(Configurable.Config):

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.

Can we

  • not have CheckpointManagerConfig but have a common CheckpointManager(Configurable) which has a Config field to hold this?
  • Either the DCPv1 or the DCPv2 one could be the base, as long as the methods are overwritten properly. Or we could have a BaseCheckpointManager class which acts as a abstract class that defines the CheckpointManagerProtocol.

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.

You're right, we should aim to define a Configurable on the class it configures. I think your idea is better, I'll revise, thanks!

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.

Could we group things related to checkpointing under e.g. components/checkpointer/?

@ivy-zhou ivy-zhou changed the title Add torch_checkpointing save config plumbing (#4058) Add torch_checkpointing save config plumbing Aug 14, 2026
from monarch.actor import Actor, current_rank, endpoint
from torchtitan.components.checkpoint import CheckpointManager
from torchtitan.components.checkpoint_utils import canonical_fqn
from torchtitan.components.checkpointer.dcp import CheckpointManager

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.

nit: if you re-expose CheckpointManager in checkpointer/__init__.py, we won't see these changes

Comment thread torchtitan/trainer.py Outdated
from torch.distributed.elastic.multiprocessing.errors import record

from torchtitan.components.checkpoint import CheckpointManager
from torchtitan.components.checkpointer.dcp import CheckpointManager

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.

config_registry should use the actual class, but here it should be able to use the interface class?

Comment thread torchtitan/trainer.py Outdated
from torchtitan.components.lr_scheduler import LRSchedulersContainer
from torchtitan.components.metrics import ensure_pp_loss_visible, MetricsProcessor
from torchtitan.components.optimizer import OptimizersContainer
from torchtitan.components.optimizer.lr_scheduler import LRSchedulersContainer

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.

can we re-expose in optimizer/init.py so that the import path is shorter and combined with OptimizersContainer

import torch.distributed.checkpoint as dcp
from torch.distributed.checkpoint import HuggingFaceStorageWriter
from torchtitan.components.checkpoint import ModelWrapper
from torchtitan.components.checkpointer.base import ModelWrapper

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.

re-expose in init.py so that we don't need these changes

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.

will do! would it be OK to add a cleanup PR after to remove the legacy import paths? agree that it's a mess to introduce this change and then also change a bunch of other unrelated files

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.

makes a lot of sense!

@ivy-zhou
ivy-zhou force-pushed the export-D112860926 branch 2 times, most recently from 19e281c to e659b28 Compare August 14, 2026 19:33
@ivy-zhou
ivy-zhou force-pushed the export-D112860926 branch 2 times, most recently from b8576b0 to 9d6c48d Compare August 17, 2026 18:49
ivy-zhou added a commit that referenced this pull request Aug 17, 2026
Summary:
@tianyu-l asked for a dedicated folder for the optimizer components, and
both
@fegin and @tianyu-l pointed out that `checkpoint_utils.py` is not an
optimizer
module even though three of its four public functions are
optimizer-only.

Split it on that line and group the result:

components/optimizer.py -> components/optimizer/optimizer.py
components/lr_scheduler.py -> components/optimizer/lr_scheduler.py
  components/checkpoint_utils.py:optimizer state helpers
-> components/optimizer/utils.py

`init_optim_state`, `get_flat_optim_state_dict`, and
`load_flat_optim_state_dict`
all take a `torch.optim.Optimizer`, so they move. `canonical_fqn(name:
str, ...)`
does not: it strips activation-checkpoint wrapper segments from a dotted
FQN and
is a checkpointing concern. It stays in `components/checkpoint_utils.py`
here and
moves to `components/checkpointer/utils.py` in the next change, which is
the one
that creates that folder, so it only ever moves once.

Nothing outside the package has to change its imports:

- `components/optimizer/__init__.py` re-exports `OptimizersContainer`,
`ParamGroupConfig`, `default_adamw`, `register_moe_load_balancing_hook`,
and
`LRSchedulersContainer`, so `torchtitan.components.optimizer` keeps
working and
  the scheduler now comes from the same short path as the container.
- `components/lr_scheduler.py` and `components/checkpoint_utils.py` stay
as
  forwarding modules for their old names.

EMA has no module today, so there is nothing to move for it yet.

Test Plan:
`pytest tests/unit_tests/test_checkpoint.py
tests/unit_tests/test_state_dict_keys.py
tests/unit_tests/test_lr_scheduler.py
tests/unit_tests/test_optimizer_param_groups.py`
passes (68 tests) at this commit, in a venv matching the CPU CI job.

`torchtitan.trainer` and `torchtitan.components.optimizer` both import
standalone
at this commit. `flake8` and `ufmt` (pinned black 22.12.0 / usort 1.0.5,
matching
`.pre-commit-config.yaml`) are clean on the changed files.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with
[ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4140).
* #4172
* #4058
* #4141
* __->__ #4140
@ivy-zhou
ivy-zhou force-pushed the export-D112860926 branch 2 times, most recently from 4455f2a to d3743c5 Compare August 17, 2026 19:45
ivy-zhou added a commit that referenced this pull request Aug 17, 2026
Summary:
Introduce a dependency-neutral checkpoint manager contract for
TorchTitan and
group the checkpointing modules under `components/checkpointer/`.

`BaseCheckpointManager(Configurable, ABC)` owns the trainer-facing
checkpoint
policy as its nested `Config`, the runtime contract as
`@abstractmethod`s, the
checkpoint item names, and the model-state wrapper shared by concrete
managers.
Keeping the config nested matches how every other Configurable works:
`Configurable.__init_subclass__` sets `Config._owner` on the class that
declares
it and `build()` constructs `_owner`, so selecting a config selects its
manager.
A config declared outside a manager could not be built at all.

Making the contract an abstract base rather than a `Protocol` means a
manager
that omits a method fails at class definition instead of at call time,
and
extension is the same shape as the rest of the repo: subclass, declare
`class Config(BaseCheckpointManager.Config)` with any extra fields, and
`_owner`
auto-wires.

Module layout, using the short names @tianyu-l asked for:

components/checkpoint.py -> components/checkpointer/dcp.py
components/checkpoint_utils.py:canonical_fqn ->
components/checkpointer/utils.py
(new) -> components/checkpointer/base.py

`checkpointer/__init__.py` re-exports the public names and
`components/checkpoint.py` stays as a forwarding module, so call sites
outside
this folder are untouched.

That re-export is only possible because `dcp.py` now imports
`OptimizersContainer`,
`LRSchedulersContainer`, `BaseDataLoader`, and `nn` under
`TYPE_CHECKING`. They
appear only in annotations, and importing them at runtime would close a
cycle:
`optimizer` -> `checkpointer.utils` -> `checkpointer/__init__` -> `dcp`
->
`optimizer`. Importing a submodule runs the package init first, so there
is no
way to re-export the managers while that runtime edge exists.

Keep the existing DCP `CheckpointManager` as the default implementation
while its
config defines only the DCP-specific `async_mode`; all shared fields and
validation live in the base config. `Trainer.checkpointer` is typed as
`BaseCheckpointManager` and its config field as
`BaseCheckpointManager.Config`
with `CheckpointManager.Config` as the default factory, so an
independent manager
can be selected without adding backend branches. Model config registries
keep
naming the concrete class. TorchFT remains explicitly tied to the legacy
DCP
implementation.

Two follow-on fixes the rename requires:

- Checkpoint tests patch `torch.distributed.checkpoint` functions
directly with
`mock.patch.object`, avoiding relocation-sensitive paths through the
local
  `dcp` alias, including the TorchFT async-save test.
- The TorchFT workflows filtered on
`torchtitan/components/checkpoint.py`, so
  they would have stopped triggering; they now filter on
  `torchtitan/components/checkpointer/**`.

Test Plan:
`pytest tests/unit_tests/test_checkpoint.py
tests/unit_tests/test_state_dict_keys.py
tests/unit_tests/test_lr_scheduler.py
tests/unit_tests/test_optimizer_param_groups.py`
passes (73 tests) at this commit, in a venv matching the CPU CI job.

`torchtitan.trainer` and `torchtitan.components.optimizer` import
standalone at
this commit, confirming the cycle is gone. `flake8` and `ufmt` are clean
on the
changed files.

Also verified:
- `BaseCheckpointManager.__abstractmethods__` is
`{load, save, maybe_wait_for_staging, close}`; the base cannot be
instantiated.
- `CheckpointManager` subclasses the base and `Config._owner` resolves
to it;
  `async_mode` stays on the DCP config only.
- A throwaway subclass with an extra config field builds via
`Config(...).build()`
  and returns that subclass; inherited validation still raises on
  `keep_latest_k=1`.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with
[ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4141).
* #4172
* #4058
* __->__ #4141
Summary:
Introduce `TorchCheckpointingManager` as an independent `Configurable` component
rather than adding backend selectors and branches to the legacy DCP
`CheckpointManager`.

`TorchCheckpointingManager.Config` intentionally adds no fields beyond
`BaseCheckpointManager.Config`, but it must still be declared: `Config._owner` is
set on the class that declares it, so a subclass that inherited `Config`
unchanged would build the abstract base. It remains buildable for `Trainer`
construction, while `TorchCheckpointingManager` constructs its fixed
`torch_checkpointing` backend internally. The backend supplies the model and
optimizer DTensor resharding schema, pinned-memory async staging, and the
TorchTitan TCPStore barrier without exposing backend resharders or callbacks
through TorchTitan configuration or Tyro.

The manager lives at `components/checkpointer/torch_checkpointing.py`, named to
match its siblings `base.py` and `dcp.py`. It is not re-exported from
`checkpointer/__init__.py`; it is selected by config, not by import.

When checkpointing is disabled, `load`, `save`, and `maybe_wait_for_staging` are
no-ops, matching the DCP manager. When it is enabled they raise
`NotImplementedError`: the routing lands in later changes, and they are stubbed
rather than omitted because `BaseCheckpointManager` declares them abstract, so a
partial implementation could not be instantiated at all.

`torch_checkpointing` moves from an optional extra to a required dependency in
`pyproject.toml`, superseding the optional-dependency arrangement added in
pytorch#4123. Note this makes it the only core dependency with an unconditional
`torch` requirement (`torch>=2.6.0`); the others declare torch only under
extras. `pip install torchtitan` will therefore pull a stable torch wheel,
which users who installed a nightly first should be aware of.

It is deliberately NOT added to `.ci/docker/requirements.txt`. That file is
symlinked from the repo root, so one entry feeds both the Docker image build
and the lint job, and it is installed with dependencies -- which would drag a
stable torch into an image whose stated invariant is that it ships no torch and
every job installs a nightly. The image already installs the library, from git
`@main` with `--no-deps`, in `.ci/docker/common/install_conda.sh`. The lint job
needs it importable too, because pyrefly type-checks
`components/checkpointer/torch_checkpointing.py`, so it gets the same
`--no-deps` install, ordered after the nightly torch install so it cannot
displace it.

Selecting `TorchCheckpointingManager.Config` selects the implementation; the
legacy manager and its config remain unchanged.

Rebased onto main at 0d2438f ("Add remat as an optional dependency",
pytorch#4163). That change added a `remat` optional-dependency group immediately after
the `torch-checkpointing` group this commit deletes, so the two collided in
`pyproject.toml`; the resolution keeps `remat` and drops `torch-checkpointing`,
which is this commit's intent unchanged.

Test Plan:
`pytest tests/unit_tests` at the top of the rebased stack: 624 passed, 18
failed. Every failure reproduces identically on unmodified `remote/main`
(0d2438f) in the same environment, so none are attributable to this change.
They split into missing optional dependencies (`transformers` for the flux
config and dataset tests, `fla` for the qwen3.5 rope test) and
environment-specific kernel/compile failures (14 helion rope tests, one
inductor C++ compile error in lora).

Scoped to the code this stack touches -- `test_checkpoint`,
`test_state_dict_keys`, `test_lr_scheduler`, `test_torch_checkpointing`,
`test_config_manager` -- 85 passed, with only the known `transformers` failure.

Also verified:
- `TorchCheckpointingManager` subclasses `BaseCheckpointManager` and its
  `Config._owner` resolves to itself.
- `torchtitan.components.checkpointer.torch_checkpointing` imports standalone.
- The resolved `pyproject.toml` parses under `tomllib`, with
  `torch_checkpointing>=0.1.0` in the core dependency list and the optional
  groups reduced to exactly `dev` and `remat`.
- `ufmt` and `codespell` clean on the changed files; `flake8 --config=.flake8`
  clean apart from one `F824` in `graph_trainer/simple_fsdp.py` that is
  pre-existing on main and untouched here.
@ivy-zhou
ivy-zhou merged commit 7c6f9f7 into pytorch:main Aug 17, 2026
22 checks passed
ivy-zhou added a commit that referenced this pull request Sep 2, 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.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants