Repository navigation
Add a common checkpoint manager bridge - #4141
Conversation
|
cc: @tianyu-l I think this PR would be a lot smaller if it was instead inside components/checkpoint so I didn't have to rename the other files? But not sure of the naming conventions you want for titan components, please let me know what would be preferable 🙏 |
tianyu-l
left a comment
There was a problem hiding this comment.
Either way is fine, up to you. Eventually we need to make them organized. I would prefer doing it early than later as long as we agree it's the right structure, so that there won't be much back-and-forth changes.
There was a problem hiding this comment.
maybe checkpointer/dcp.py to be succinct
There was a problem hiding this comment.
checkpointer/base.py or checkpointer/common.py
There was a problem hiding this comment.
https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/checkpoint_utils.py#L43 is used not only in optimizer, so maybe worth putting under checkpointer folder
bd0daa1 to
a09ec78
Compare
20494d3 to
d56a72a
Compare
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
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`.
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 checkpointpolicy as its nested
Config, the runtime contract as@abstractmethods, thecheckpoint item names, and the model-state wrapper shared by concrete managers.
Keeping the config nested matches how every other Configurable works:
Configurable.__init_subclass__setsConfig._owneron the class that declaresit 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
Protocolmeans a managerthat 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_ownerauto-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__.pyre-exports the public names andcomponents/checkpoint.pystays as a forwarding module, so call sites outsidethis folder are untouched.
That re-export is only possible because
dcp.pynow importsOptimizersContainer,LRSchedulersContainer,BaseDataLoader, andnnunderTYPE_CHECKING. Theyappear 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 noway to re-export the managers while that runtime edge exists.
Keep the existing DCP
CheckpointManageras the default implementation while itsconfig defines only the DCP-specific
async_mode; all shared fields andvalidation live in the base config.
Trainer.checkpointeris typed asBaseCheckpointManagerand its config field asBaseCheckpointManager.Configwith
CheckpointManager.Configas the default factory, so an independent managercan 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:
torch.distributed.checkpointfunctions directly withmock.patch.object, avoiding relocation-sensitive paths through the localdcpalias, including the TorchFT async-save test.torchtitan/components/checkpoint.py, sothey 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.pypasses (73 tests) at this commit, in a venv matching the CPU CI job.
torchtitan.trainerandtorchtitan.components.optimizerimport standalone atthis commit, confirming the cycle is gone.
flake8andufmtare clean on thechanged files.
Also verified:
BaseCheckpointManager.__abstractmethods__is{load, save, maybe_wait_for_staging, close}; the base cannot be instantiated.CheckpointManagersubclasses the base andConfig._ownerresolves to it;async_modestays on the DCP config only.Config(...).build()and returns that subclass; inherited validation still raises on
keep_latest_k=1.Stack created with Sapling. Best reviewed with ReviewStack.