Repository navigation
Conversation
…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
| if match is None: | ||
| return None | ||
| return int(match.group("step")) | ||
| return int(match.group("step")), bool(match.group("tmp")) |
There was a problem hiding this comment.
why? tmp would mean the checkpoint isn't complete yet?
There was a problem hiding this comment.
It's just returning the step from the file name and whether or not the checkpoint file is a temporary one.
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
…4185) Summary: `components/checkpoint_utils.py` became a re-export shim when the optimizer and checkpointer components were grouped into packages. Unlike the lr_scheduler shim removed in #4172, this one forwarded to two different destinations at once, which is what made it worth deleting rather than keeping: reading an import of `checkpoint_utils` told you nothing about whether the symbol was optimizer plumbing or checkpointer plumbing. Route each of the four importers to the module that actually defines the symbol. `canonical_fqn` lives in `checkpointer/utils.py`; `init_optim_state`, `get_flat_optim_state_dict`, and `load_flat_optim_state_dict` live in `optimizer/utils.py`. This also settles the naming objection fegin raised on #4140, that `canonical_fqn` does not belong under an optimizer-shaped name -- its importer in the rl trainer now names the checkpointer package directly. The three state-dict helpers are imported from `optimizer.utils` rather than re-exported through `optimizer/__init__.py`. They are low-level DCP plumbing with two callers between them, not part of the package's public surface, which stays `OptimizersContainer`, `LRSchedulersContainer`, `ParamGroupConfig`, and `default_adamw`. This is an import-path change only; no runtime behavior changes. Test Plan: `pytest tests/unit_tests/test_state_dict_keys.py tests/unit_tests/test_checkpoint.py tests/unit_tests/test_lr_scheduler.py tests/unit_tests/test_optimizer_param_groups.py tests/unit_tests/test_torch_checkpointing.py`: 77 passed, 4 subtests passed. `test_legacy_checkpoint_utils_imports`, which asserted the shim's symbols were identical to the submodule's, is dropped -- it cannot outlive the shim. `test_legacy_checkpoint_utils_can_be_imported_first` is kept but retargeted, as `test_state_dict_helpers_can_be_imported_first`. It guards a real property rather than the shim: the `optimizer` and `checkpointer` package `__init__` files import from each other, so importing either leaf `utils` module first in a fresh interpreter must not close an import cycle. It now subtests both leaf modules instead of the single shim. Also verified: - No `checkpoint_utils` references remain anywhere in the repo, across all file types, not only Python. - `import torchtitan.components.checkpoint_utils` now raises `ModuleNotFoundError`. - `ufmt` and `flake8 --config=.flake8` clean on the four changed files. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4185). * #4240 * #4230 * #4191 * #4190 * #4189 * #4188 * #4197 * #4187 * #4186 * __->__ #4185 * #4184
…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
beb2353 to
d8f04ce
Compare
fegin
left a comment
There was a problem hiding this comment.
_purge_stale_checkpoints now demands more CPU time and rank synchronization. We should review if this is necessary.
| for checkpoint_dir in abandoned: | ||
| logger.info( | ||
| "Checkpointer is deleting the abandoned %s.", checkpoint_dir | ||
| ) | ||
| try: | ||
| self._storage.remove(checkpoint_dir) | ||
| except Exception as error: | ||
| logger.warning( | ||
| "Checkpointer failed to delete %s: %s. Skipping.", | ||
| checkpoint_dir, | ||
| error, | ||
| ) |
There was a problem hiding this comment.
Why can't we let purge_queue do the work?
| and dist.is_initialized() | ||
| and dist.get_world_size() > 1 | ||
| ): | ||
| dist.barrier() |
There was a problem hiding this comment.
Is this required? This basically means that for keep_latest_k > 1 case, we will have a global synchronization every step, which is something we currently trying to remove.
There was a problem hiding this comment.
That's my bad should be removed now
…4187) Summary: Checkpoint discovery and retention share the same published directory grammar across backends. Move their common implementation into BaseCheckpointManager. BaseCheckpointManager now parses only canonical `step-N` directory names through the concrete `_parse_step(dirname)` helper. Backends implement only `_is_valid_checkpoint(checkpoint_dir)` to identify their completion marker. Names outside the canonical grammar remain untouched. DCP accepts either `.metadata` or a Hugging Face safetensors index. The initial torch_checkpointing manager implementation accepts its native metadata marker. Later changes extend that backend's supported checkpoint formats and retention handling without widening the parser API. Test Plan: `pytest tests/unit_tests/cpu/test_checkpoint.py tests/unit_tests/cpu/test_torch_checkpointing.py -q` 60 passed. Formatting, flake8, pydoclint, and codespell passed. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4187). * #4189 * #4188 * #4197 * __->__ #4187
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.
Surveyed, not merged -- two 80B captures are mid-flight and folding in 64 commits would make any new failure ambiguous. This records the analysis so the merge is cheap later. Diverged at 6ee6d5d (2026-08-30), upstream tip 966befc. ZERO upstream commits touch experiments/ezpz, so there are no conflicts in our own code. The risk is entirely in core files we import from. Of those, components/loss.py matters most: we import BaseLoss, CrossEntropyLoss, ChunkedLossWrapper and IGNORE_INDEX, all four still present, with one method renamed (typecheck_forward -> spmd_typecheck). zloss.py overrides only __init__ and __call__, so it does not inherit that rename -- checked rather than assumed, since a preserved name with a changed contract is the dangerous case, not a deleted one. Corrects my earlier risk ranking. I called pytorch#4328 (refactor max_context_length) the highest risk; that was wrong. max_context_length is UNCHANGED upstream -- same field, same default, plus a validation guard. The PR changes seq_len in model specs and registries, not the --training.max-context-length flag we pass. The single seam is agpt/config_registry.py:291, where our own agpt(seq_len=...) assigns cfg.training.max_context_length. The real risks, ordered: pytorch#4398 (valid-token counts move into collation -- that is the gradient-accumulation path), then the checkpoint cluster (pytorch#4187/pytorch#4188/pytorch#4197/pytorch#4270/pytorch#4474, which we subclass and where pinned clones have already broken on optim-statedict changes), then pytorch#4382 (Adam first-step state). Includes a merge order: smoke at 2N, then a resume from a real checkpoint, a seeded loss/grad_norm comparison, and config_registry.py:291 by inspection.
Summary:
Run retention only after the previous save has completed and before the next save starts.
_purge_stale_checkpointsreceives 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_stepabout backend-specific temporary names. Valid published checkpoints alone participate in retention, and the manager keepskeep_latest_k - 1of 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 -q64 passed.
Tests cover DCP purge ordering, current-save protection, retention slot reservation, incomplete checkpoint cleanup through the purge thread, and canonical parsing.
Stack created with Sapling. Best reviewed with ReviewStack.