Repository navigation
Conversation
3e0ef72 to
baf12e5
Compare
63c7386 to
462f63c
Compare
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.
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with
[ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4190).
* #4457
* #4277
* #4279
* #4278
* #4191
* __->__ #4190
Summary: `TorchCheckpointingManager` could save but not load: `_load` raised `NotImplementedError`, so a run configured for this backend could write checkpoints and never resume from them. Implement the native load path, completing the round trip. Resolution mirrors the DCP manager. With no explicit step, the latest valid step in the checkpoint folder is used; with an explicit step, a missing folder or missing checkpoint is an error rather than a silent fresh start. When no step is found, `initial_load_path` is used if configured, and otherwise the run starts fresh. Step 0 is treated as a seed checkpoint and loads model state only. Step discovery only accepts directories that actually contain the backend's `metadata.pkl`. A crashed save leaves a `step-N` directory with no metadata, and without this check that partial directory would win the `max()` and be loaded as the resume point. Directory listing, existence checks, and the load itself all go through the configured `Storage`, so remote checkpoint folders work the same as local ones. The backend returns a plain dict rather than writing through the live objects, so `_restore_state_dict` puts values back: `Stateful` entries get `load_state_dict`, plain dicts are updated in place so callers holding a reference see the result, and anything else that is not already the same object raises rather than being silently skipped. Keys in `exclude_from_loading` are dropped before the load, and an excluded key that is not in the state dict is an error, matching the DCP manager. Hugging Face loads are explicitly rejected for now; they land separately. Ported from an internal change. Besides the path and naming translation, the internal version defines `load()` with its own `if not self.enable` guard; here the body moves to the `_load` hook and the guard is dropped, since `BaseCheckpointManager` owns it. Test Plan: `pytest tests/unit_tests/test_torch_checkpointing.py`: 24 passed. Four new tests: an explicit-step load restores both model weights and optimizer state from the backend payload and passes the full state dict as the load target; a latest-step load of `step-0` requests model state only; discovery and load go through a configured non-local `Storage` rather than the filesystem; and a folder containing valid `step-2` and `step-5`, a metadata-less `step-8`, and a `tmp_step-9` resolves to `step-5`, so an interrupted save is not mistaken for the newest checkpoint. `pytest tests/unit_tests/test_checkpoint.py tests/unit_tests/observability/ torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py` alongside the above: 147 passed, 2 subtests passed. Also verified: - `TorchCheckpointingManager.__abstractmethods__` is empty; with `_load` implemented the manager now satisfies the full `BaseCheckpointManager` contract. - `METADATA_FILE_NAME` and `CheckpointManager.load(checkpoint_id, into=...)` exist in `torch_checkpointing` 0.1.0. - `ufmt` and `flake8 --config=.flake8` clean 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/4191). * #4457 * #4277 * #4279 * #4278 * __->__ #4191
Summary: Move `checkpoint_save` and `checkpoint_load` tracing to the guarded public methods on `BaseCheckpointManager`. This gives every checkpoint backend one consistent trainer-facing timing boundary while keeping disabled managers silent and avoiding duplicate backend spans. Test Plan: `PYTHONPATH=/tmp/torchtitan-additional-packages.iGrJ91/checkpointing /home/ivyzhou/local/torchtitan-venv/bin/python -m pytest tests/unit_tests/test_checkpoint.py -q` (55 passed) `PYTHONPATH=/tmp/torchtitan-additional-packages.iGrJ91/checkpointing /home/ivyzhou/local/torchtitan-venv/bin/python -m pytest tests/unit_tests/test_torch_checkpointing.py -q` (36 passed) `PYTHONPATH=/tmp/torchtitan-additional-packages.iGrJ91/checkpointing /home/ivyzhou/local/torchtitan-venv/bin/python -m pytest torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py -q` (2 passed) `PATH=/home/ivyzhou/local/torchtitan-venv/bin:$PATH PYTHONPATH=/tmp/torchtitan-additional-packages.iGrJ91/checkpointing /home/ivyzhou/local/torchtitan-venv/bin/pre-commit run --all-files` (passed) --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4278). * #4457 * #4277 * #4279 * __->__ #4278
Summary: Record native DCP asynchronous save latency from entry into dcp_save until the returned save future completes. Capture one monotonic timestamp at submission and attach a completion callback that subtracts it from the completion timestamp and emits the structured metric. The metric measures the save future lifetime, not filesystem-only write time. The existing wait path remains responsible for surfacing save failures. Test Plan: env TORCH_DISABLE_ADDR2LINE=1 PYTHONPATH=/data/users/ivyzhou/torchtitan:/tmp/torchtitan_additional_packages_3e4a.nRk7S7/checkpointing:/tmp/torchtitan_additional_packages_3e4a.nRk7S7/ao:/tmp/torchtitan_additional_packages_3e4a.nRk7S7/torchtitan_runtime_deps /home/ivyzhou/local/torchtitan-venv/bin/python -m pytest tests/unit_tests/observability/test_structured_logging.py tests/unit_tests/test_checkpoint.py -q 138 passed. Changed-file pre-commit hooks passed, including ufmt, flake8, pydoclint, codespell, and Pyrefly. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/4279). * #4457 * #4277 * __->__ #4279
| @@ -71,10 +75,12 @@ | |||
| DEFAULT_TORCH_CHECKPOINTING_BARRIER_TCPSTORE_PORT = 43001 | |||
There was a problem hiding this comment.
Curious, do we need to hard code this value?
There was a problem hiding this comment.
No, we don't. @ivy-zhou can you move titan over to use DefaultStoreBarrier instead of TCPStoreBarrier? In prod jobs, the default store is a TCPStore so it have equivalent performance without the overhead of setting up and connecting to a second store. Might need to modify tests if any are running in a situation where a default store hasn't been configured.
There was a problem hiding this comment.
Sounds good, I wrote this before you wrote DefaultStoreBarrier. Let's do this in a separate PR, added here: #5170
| @@ -71,10 +75,12 @@ | |||
| DEFAULT_TORCH_CHECKPOINTING_BARRIER_TCPSTORE_PORT = 43001 | |||
| _DEFAULT_BARRIER_INIT_TIMEOUT_SEC = 60 | |||
| _DEFAULT_BARRIER_TIMEOUT_SEC = 600 | |||
There was a problem hiding this comment.
Is this for saving and loading timeout?
There was a problem hiding this comment.
This is for saving -- it's how long the background write is allowed to go before it errors.
On the load side there is no collectives/coordination, so no barrier use.
| _HF_INDEX_FILE_NAME = f"{MODEL}.safetensors.index.json" | ||
| _HF_SINGLE_FILE_NAME = f"{MODEL}.safetensors" |
There was a problem hiding this comment.
The probe only accepts model.safetensors*, while FluxStateDictAdapter supports diffusion_pytorch_model.safetensors.index.json. Flux loading fails before the metadata reader runs. Detect supported safetensors files without hard-coding only the model prefix.
Let's add a TODO for Flux.
There was a problem hiding this comment.
This is currently a limitation in in the current impl of torch_checkpointing -- it's hard-coded to model there.
There was a problem hiding this comment.
I was looking into this this morning, basically DCPv1 doesn't read the index atm, it just reads every .safetensors file and builds the header information from there. I added a way (in a separate PR) to get this information of "diffusion_pytorch_model.safetensors.index.json" into the torch_checkpointing side by inferring it from the model key, i.e. Titan can pass us {"diffusion_pytorch_model": model_state} and we can load into it. What do folks think?
| hf_state = self.sd_adapter.to_hf(state_dict[MODEL]) | ||
| model_spec = self._manager_config.items[MODEL] | ||
| hf_model_spec = ItemSpec( | ||
| requires_copy=model_spec.requires_copy, |
There was a problem hiding this comment.
Curious, who define this model_spec? Are users ever going to change the spec?
There was a problem hiding this comment.
Trainer defines the ItemSpec of each item, and it has to do with the nature of the item itself. For example item_spec.requires_copy is for requiring staging copy of the optimizer and model, because the model is going to mutate those and we don't want the checkpoint write and the model writes to race.
1169ccc to
96d3dbe
Compare
fegin
left a comment
There was a problem hiding this comment.
Thanks, we need to wait for torch_checkpointing diffs landed first before landing this PR, is this correct? Or did you land all the depended diffs?
Summary:
Load an initial Hugging Face safetensors checkpoint (`checkpoint.initial_load_in_hf`) through a temporary, model-only `torch_checkpointing` manager.
The model state is converted with the state-dict adapter (`to_hf`), loaded in place, and restored with `from_hf`. The load names the export's format with `metadata_format=HuggingFaceSafetensorsDistributedMetadataFormat`: an export has no native metadata, and `torch_checkpointing` only reads a non-native format the caller names. The model item keeps its `DefaultResharder`, which reshards every safetensors source into the model's DTensors. The temporary manager loads the export as the `model` item, so `torch_checkpointing` reads `model.safetensors.index.json` or `model.safetensors`, and the probe checks those two names, with no directory listing. Exports named after another item, such as diffusers' `diffusion_pytorch_model.safetensors.index.json` for Flux, are left as a TODO for a follow-up. Retention's validity check uses `model`, the name this checkpointer writes its own exports under. The load is `strict`, but only over the weights `to_hf` maps, so parameters an export does not carry, such as new LoRA adapters, keep their initialized values. A native base checkpoint cannot yet initialize a LoRA model, since its strict load requires the adapter parameters; a TODO marks that. Quantized Hugging Face loads are rejected for now.
It also imports `METADATA_FILE_NAME` from `torch_checkpointing.metadata_serialization`, where it now lives.
Every `torch_checkpointing` API it uses, including `metadata_format`, `torch_checkpointing.hf.metadata` and `METADATA_FILE_NAME` in `metadata_serialization`, is on `torch_checkpointing` main. The probe spells the single-file name, `{item_key}.safetensors`, itself.
Test Plan:
Against `torch_checkpointing` main:
```
pytest -q tests/unit_tests/cpu/test_torch_checkpointing.py tests/unit_tests/cpu/test_state_dict_adapter.py
pre-commit run --files torchtitan/components/checkpointer/torch_checkpointing.py tests/unit_tests/cpu/test_torch_checkpointing.py
```
55 passed, 24 subtests passed. `test_hf_load_reads_a_real_safetensors_export` loads a real indexed `model` export into an `nn.Linear` with no mocks, and `test_hf_load_leaves_parameters_the_export_does_not_carry` loads one into a model with an extra LoRA-like parameter, which keeps its value; loading the export by plain path instead fails with "Missing files for checkpoint items ['model']". pre-commit: clean. Repo-wide pyrefly reports no `torch_checkpointing` errors.
Summary:
Load an initial Hugging Face safetensors checkpoint (
checkpoint.initial_load_in_hf) through a temporary, model-onlytorch_checkpointingmanager.The model state is converted with the state-dict adapter (
to_hf), loaded in place, and restored withfrom_hf. The load names the export's format withmetadata_format=HuggingFaceSafetensorsDistributedMetadataFormat: an export has no native metadata, andtorch_checkpointingonly reads a non-native format the caller names. The model item keeps itsDefaultResharder, which reshards every safetensors source into the model's DTensors. The temporary manager loads the export as themodelitem, sotorch_checkpointingreadsmodel.safetensors.index.jsonormodel.safetensors, and the probe checks those two names, with no directory listing. Exports named after another item, such as diffusers'diffusion_pytorch_model.safetensors.index.jsonfor Flux, are left as a TODO for a follow-up. Retention's validity check usesmodel, the name this checkpointer writes its own exports under. The load isstrict, but only over the weightsto_hfmaps, so parameters an export does not carry, such as new LoRA adapters, keep their initialized values. A native base checkpoint cannot yet initialize a LoRA model, since its strict load requires the adapter parameters; a TODO marks that. Quantized Hugging Face loads are rejected for now.It also imports
METADATA_FILE_NAMEfromtorch_checkpointing.metadata_serialization, where it now lives.Every
torch_checkpointingAPI it uses, includingmetadata_format,torch_checkpointing.hf.metadataandMETADATA_FILE_NAMEinmetadata_serialization, is ontorch_checkpointingmain. The probe spells the single-file name,{item_key}.safetensors, itself.Test Plan:
Against
torch_checkpointingmain:55 passed, 24 subtests passed.
test_hf_load_reads_a_real_safetensors_exportloads a real indexedmodelexport into annn.Linearwith no mocks, andtest_hf_load_leaves_parameters_the_export_does_not_carryloads one into a model with an extra LoRA-like parameter, which keeps its value; loading the export by plain path instead fails with "Missing files for checkpoint items ['model']". pre-commit: clean. Repo-wide pyrefly reports notorch_checkpointingerrors.