Repository navigation
Move the checkpointing-disabled guard into BaseCheckpointManager - #4173
Merged
Merged
Conversation
This was referenced Aug 17, 2026
ivy-zhou
added a commit
that referenced
this pull request
Aug 17, 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 `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. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4058). * #4173 * #4172 * __->__ #4058
ivy-zhou
marked this pull request as ready for review
August 18, 2026 01:21
ivy-zhou
requested review from
fegin,
felipemello1,
tianyu-l,
wconstab and
wwwjn
as code owners
August 18, 2026 01:21
tianyu-l
approved these changes
Aug 18, 2026
ivy-zhou
added a commit
that referenced
this pull request
Aug 18, 2026
Summary: `components/lr_scheduler.py` became a re-export shim when the optimizer components were grouped into a package. Keeping it means every importer can pick either path, and the two-path state is the thing reviewers flagged: the shim exists only so unrelated files did not have to change in that diff, not because either path is meaningfully better. Delete the shim and move all 17 importers to `torchtitan.components.optimizer`. Every one of them already imported something else from that package -- `default_adamw`, `OptimizersContainer`, `ParamGroupConfig` -- so each becomes a single combined import rather than two adjacent ones, which is what the package re-export was for. `torchtitan.components.optimizer.lr_scheduler` is untouched and remains the module that defines `LRSchedulersContainer`; only the `components.lr_scheduler` alias is gone. Files updated span all model variants (llama3, qwen3, qwen3_5, deepseek_v3, gpt_oss, kimi_k2_7, muse_glimmer, flux) plus the forge, torchft, transformers_modeling_backend, and rl experiments. This is an import-path change only; no runtime behavior changes. Test Plan: `pytest tests/unit_tests/test_lr_scheduler.py tests/unit_tests/test_optimizer_param_groups.py tests/unit_tests/test_checkpoint.py tests/unit_tests/test_state_dict_keys.py`: 72 passed, 2 subtests passed. Dropped `TestLRScheduler.test_legacy_import_path`, which asserted the shim resolved to the same object; it cannot outlive the shim. `test_optimizer_package_import_path` still covers the surviving contract, that the package re-export is the same object as the submodule definition. Also verified: - No `components.lr_scheduler` references remain anywhere in the repo (py, md, yaml, toml, txt). - `import torchtitan.components.lr_scheduler` now raises `ModuleNotFoundError`. - All 17 touched modules byte-compile, and the 10 whose optional dependencies are installed import cleanly. The other 6 fail only on absent optional packages (`fla`, `transformers`, `vllm`), unrelated to this change. - `ufmt` and `flake8 --config=.flake8` 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/4172). * #4173 * __->__ #4172
Summary: A disabled checkpoint manager returns early from `__init__` without setting up any state, so none of its attributes exist. Every public method therefore had to open with `if not self.enable: ...` before touching anything, and `close()` additionally needed `hasattr(self, "enable")` because `__del__` can run on a partially constructed object. That check was repeated at six sites in `dcp.py` and three in `torch_checkpointing.py`, and nothing forced a new manager to remember it. Make `BaseCheckpointManager` own the check once. `load`, `save`, `maybe_wait_for_staging`, and `close` become concrete methods that test `self.enable` and dispatch to abstract `_load`, `_save`, `_maybe_wait_for_staging`, and `_close` hooks. Subclasses implement the hooks and can assume they are only reached when checkpointing is enabled, so a manager can no longer forget the guard: forgetting now means failing to implement an abstract method, which is a construction-time error rather than a crash against uninitialized state. `TorchFTCheckpointManager` needed care. It overrides `save` and `load` and does work *before* delegating upward, so leaving those overrides on the public names would have bypassed the new guard entirely; they are renamed to `_save` and `_load` with their `super()` calls updated to match. This does change one behavior: previously, with `enable=False` and `enable_ft_dataloader_checkpoints=True`, `_ft_save` still ran, because the enable check lived further down inside `CheckpointManager.save`. It no longer does. That path was already unsound -- `TorchFTCheckpointManager.__init__` returns early at `if not self.enable` *after* assigning `enable_ft_dataloader_checkpoints`, so `_ft_save` could run against FT state that was never initialized -- but it is a real change and is called out here rather than folded in silently. `maybe_wait_for_saving` moves too, for the same reason: it is public, both managers reach it, and it opens with the same `enable` guard. It dispatches to a `_wait_for_saving` hook, called only when `save_future` is set, so each manager keeps its own wait semantics. `TorchFTCheckpointManager` overrode this one as well and is renamed with the others; its own `save_future is None` check is dropped, since the base performs it before dispatching. Two `self.enable` reads deliberately remain. `_should_save` keeps `not self.enable` as defense for internal callers that do not route through `save()`. And both `__init__`s still assign `self.enable`, which is what the base class reads. No behavior change for either manager when checkpointing is enabled, and none when disabled apart from the TorchFT case above. Test Plan: `pytest tests/unit_tests/test_checkpoint.py tests/unit_tests/test_torch_checkpointing.py`: 42 passed, 2 subtests passed. `pytest torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py`: 1 passed. Full `pytest tests/unit_tests` (excluding `test_rope.py`, which cannot be collected without the optional `fla` package): 623 passed, 18 failed -- the same 18 that fail on unmodified main in this environment. Also verified: - Constructing each of `CheckpointManager` and `TorchCheckpointingManager` with `enable=False` and calling `load()`, `save(1)`, `maybe_wait_for_staging()`, and `close()` returns `False`, `False`, `None`, and raises nothing -- identical to the previous behavior. - Both concrete managers report an empty `__abstractmethods__`, so every hook is implemented. - No `super().save(...)` / `super().load(...)` calls to the public names remain in any checkpoint manager. - `ufmt` and `flake8 --config=.flake8` clean on the four changed files.
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
acisseJZhong
pushed a commit
that referenced
this pull request
Aug 21, 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
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:
A disabled checkpoint manager returns early from
__init__without setting upany state, so none of its attributes exist. Every public method therefore had
to open with
if not self.enable: ...before touching anything, andclose()additionally needed
hasattr(self, "enable")because__del__can run on apartially constructed object. That check was repeated at six sites in
dcp.pyand three in
torch_checkpointing.py, and nothing forced a new manager toremember it.
Make
BaseCheckpointManagerown the check once.load,save,maybe_wait_for_staging, andclosebecome concrete methods that testself.enableand dispatch to abstract_load,_save,_maybe_wait_for_staging, and_closehooks. Subclasses implement the hooksand can assume they are only reached when checkpointing is enabled, so a
manager can no longer forget the guard: forgetting now means failing to
implement an abstract method, which is a construction-time error rather than a
crash against uninitialized state.
TorchFTCheckpointManagerneeded care. It overridessaveandloadand doeswork before delegating upward, so leaving those overrides on the public names
would have bypassed the new guard entirely; they are renamed to
_saveand_loadwith theirsuper()calls updated to match. This does change onebehavior: previously, with
enable=Falseandenable_ft_dataloader_checkpoints=True,_ft_savestill ran, because theenable check lived further down inside
CheckpointManager.save. It no longerdoes. That path was already unsound --
TorchFTCheckpointManager.__init__returns early at
if not self.enableafter assigningenable_ft_dataloader_checkpoints, so_ft_savecould run against FT statethat was never initialized -- but it is a real change and is called out here
rather than folded in silently.
maybe_wait_for_savingmoves too, for the same reason: it is public, bothmanagers reach it, and it opens with the same
enableguard. It dispatches toa
_wait_for_savinghook, called only whensave_futureis set, so eachmanager keeps its own wait semantics.
TorchFTCheckpointManageroverrode thisone as well and is renamed with the others; its own
save_future is Nonecheckis dropped, since the base performs it before dispatching.
Two
self.enablereads deliberately remain._should_savekeepsnot self.enableas defense forinternal callers that do not route through
save(). And both__init__s stillassign
self.enable, which is what the base class reads.No behavior change for either manager when checkpointing is enabled, and none
when disabled apart from the TorchFT case above.
Test Plan:
pytest tests/unit_tests/test_checkpoint.py tests/unit_tests/test_torch_checkpointing.py: 42 passed, 2 subtests passed.pytest torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py:1 passed.
Full
pytest tests/unit_tests(excludingtest_rope.py, which cannot becollected without the optional
flapackage): 623 passed, 18 failed -- thesame 18 that fail on unmodified main in this environment.
Also verified:
CheckpointManagerandTorchCheckpointingManagerwithenable=Falseand callingload(),save(1),maybe_wait_for_staging(),and
close()returnsFalse,False,None, and raises nothing --identical to the previous behavior.
__abstractmethods__, so every hookis implemented.
super().save(...)/super().load(...)calls to the public names remainin any checkpoint manager.
ufmtandflake8 --config=.flake8clean on the four changed files.