Repository navigation
[checkpoint] TorchCheckpointingManager: checkpoints on fsspec URIs such as gs:// - #6169
Conversation
|
|
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The problem is real on main, the routing is in the right layer, and local folders keep their old behavior. The remaining items are small doc and test edits. This touches core checkpointer code, so a maintainer still needs to review.
What this PR does. TorchCheckpointingManager no longer rejects a URI in folder or initial_load_path. _BackendCheckpointStorage picks a torch_checkpointing Storage from each path's scheme: the folder's storage (by default FsspecStorageConfig(protocol=...)) for the folder's protocol, and that protocol's default storage for anything else. It then strips the scheme before the path reaches the backend, because the backend wraps ids in Path(). The remote-HF guards move from the base config to DCP's config, since only DCP's HF storage is local-only.
Example.
TorchCheckpointingManager.Config(folder="gs://b/run/ckpt", last_save_in_hf=True, ...)
# main: ValueError: checkpointer.folder is a remote URI (...)
# PR: folder storage = FsspecStorageConfig(protocol="gs")
# interval save -> backend.save("b/run/ckpt/step-500")
# final export -> backend.save("b/run/ckpt/exports/step-N/sharded"), consolidated via fsspec
# hf_assets_path="/data/hf" -> read with LocalFileSystemStorageConfig()
# storage_config=LocalFileSystemStorageConfig() with a gs:// folder -> ValueError at constructionMust fix
torchtitan/components/checkpointer/README.md:97-- On flat (non-HNS) buckets, a preempted commit can leave astep-Nthat looks complete; auto-resume then picks it and fails. The README needs to say so, and the description's "flat and HNS buckets" row should be corrected (inline).torchtitan/components/checkpointer/torch_checkpointing.py:82-- The URI splitting and per-protocol routing work around torch_checkpointing'sPath()wrapping. Add a TODO linking an upstream issue (inline).
Should consider
torchtitan/components/checkpointer/torch_checkpointing.py:326--_storageand_backend_storageare the same object; keep one (inline).tests/.../test_torch_checkpointing.py:257-- This mocked probe test duplicates thememory://load-latest test; delete it (inline).tests/.../test_torch_checkpointing.py:477-- Reuse_memory_bucket()instead of the inline bucket setup in two tests (inline).
Questions
.ci/docker/requirements.txt:20-- The comment names torch_checkpointing commit5bda153, but the pin is5c45dc3. Is5bda153the commit that adds the fsspec backend? If so, a few words saying that would avoid confusion.
Details
- Gate. The problem reproduces on
main:TorchCheckpointingManager.__init__raises on any URI folder. DCP already supportsgs://throughtorchtitan/tools/filesystem.py, so this brings the two managers to parity rather than adding a new capability. No overlapping open PR. - Local path unchanged. With a local folder and
storage_config=None,folder_storage_configstaysNone. The async manager, the HF load (storage_config_forreturnsNonefor the folder's protocol), and the HF export (LocalFileSystemStorageConfig(use_direct_io=False)) all get the same configs as onmain. - Routing. Purge,
listdir, and_is_resumable_checkpointall receive full URIs joined offself.folderand go through the folder's storage. The_storagescache is pre-populated for the folder's protocol, so the purge thread never mutates the dict. - Initial-load manager. The
initial_load_pathloader on another storage uses the same item specs and default as the main manager (items=None,_DEFAULT_ITEM_SPEC). - Test value. The mock-based tests are what catch a scheme leaking into backend ids. The real
file://round trip would still pass ifPath()mangledfile:///tmp/xinto a relativefile:/tmp/x, because the save and the load would be mangled the same way. So keep the save-id mock test and drop only the redundant probe one.
Not verified: real GCS behavior (async saves in the subprocess, gcsfs credentials, flat-bucket rename semantics). I could not run the CPU unit tests in this environment.
| Interval saves, the final save, resume, `keep_latest_k` retention, Hugging Face export | ||
| (`last_save_in_hf`), and Hugging Face load (`initial_load_in_hf`) all go through the | ||
| remote store. `initial_load_path` may be on other storage than `folder`, and a local | ||
| `hf_assets_path` works with a remote `folder`, e.g. HF weights on local disk with | ||
| checkpoints on `gs://`. |
There was a problem hiding this comment.
This says resume works on gs:// with no caveat. But the PR's own follow-up says that on a flat (non-HNS) bucket, a commit preempted mid-rename can leave a step-N that already has metadata.pkl but not all of its shards. _is_resumable_checkpoint accepts that directory, so auto-resume picks it as the latest checkpoint and the load fails. Retention also treats it as valid and keeps it, so the run can't resume until someone deletes it by hand.
The PR description's table ("flat and HNS buckets") has the same problem. Please state the limitation here, e.g. "On flat (non-HNS) GCS buckets the commit rename is not atomic; a preempted commit can leave a step-N that looks complete. Prefer HNS buckets." Add a TODO pointing at the checkpoint-writer-metadata-staging fix, and correct the table to match.
There was a problem hiding this comment.
Thanks, good catch! I'd see this more as failure handling to make more robust than as a limitation: saves, resume and retention work on both flat and HNS buckets, and this case needs a preemption in the middle of the commit rename. A few other failure cases can be improved too (see Follow-ups).
Would it be OK to land the functionality first and do these as follow-ups? I added a TODO at _is_resumable_checkpoint pointing at the planned fix. Happy to add a README note too if you prefer.
There was a problem hiding this comment.
Added to the README and the description. The upstream fix is tracked in meta-pytorch/torch_checkpointing#17.
| CHECKPOINTING_LOGGER_NAME = "torch_checkpointing" | ||
|
|
||
|
|
||
| def _split_uri(path: str) -> tuple[str | None, str]: |
There was a problem hiding this comment.
All of this (_split_uri, _backend_path, _can_hold, and the per-protocol routing in _BackendCheckpointStorage) works around an upstream gap: torch_checkpointing wraps every checkpoint id in Path(), and it has no way to build a StorageConfig from a URI. That is about 70 lines that torchtitan (and every other torch_checkpointing user) has to carry.
Per the repo's "upstream first" rule, please add a TODO here linking a torch_checkpointing issue. The upstream fix would be either accepting URI ids directly or adding a StorageConfig.from_uri(path), so this can be deleted once it lands.
There was a problem hiding this comment.
Thanks, makes sense! I added a TODO linking meta-pytorch/torch_checkpointing#12, where the URI and Storage design is still being discussed. Happy to rework this once the direction there is clear.
| self._backend_storage = _BackendCheckpointStorage(self.folder, storage_config) | ||
| self._storage = self._backend_storage |
There was a problem hiding this comment.
There are now two attributes for the same object, so readers have to check that _storage and _backend_storage never diverge. Keep one: annotate _storage: _BackendCheckpointStorage on the class (narrowing the base's CheckpointStorage annotation) and use self._storage.storage_config_for(...) / .folder_storage_config / .is_on_folder_storage(...) directly.
There was a problem hiding this comment.
Done, thanks! There's now just one _storage, narrowed on the class.
| storage.rmdir.assert_called_once_with(Path("bucket/run/checkpoint/step-3")) | ||
| manager.close() | ||
|
|
||
| def test_remote_folder_is_probed_and_loaded_by_scheme_less_path(self) -> None: |
There was a problem hiding this comment.
This duplicates test_load_latest_on_remote_folder_ignores_incomplete_checkpoint_directories. That test probes a real memory:// folder through the real FsspecStorage, and it asserts that the selected step-5 id reaches the backend without its scheme (_BackendManager.load also asserts "://" not in checkpoint_id). The mocked ls/isdir here adds no coverage beyond that. Suggest deleting this test.
There was a problem hiding this comment.
Agreed, removed. Thanks!
|
|
||
| torch.testing.assert_close(restored.weight, saved.weight) | ||
|
|
||
| def test_remote_folder_hf_round_trip(self) -> None: |
There was a problem hiding this comment.
This test and test_load_latest_on_remote_folder_ignores_incomplete_checkpoint_directories each re-implement the bucket setup and cleanup that _memory_bucket() already provides, and the second one drops the leading /. Use _memory_bucket() in both so the memory-fs setup lives in one place.
There was a problem hiding this comment.
Done, both now use _memory_bucket(). Thanks!
…anExecutor Pin torch_checkpointing to meta-pytorch/torch_checkpointing 5c45dc3, the same commit #6169 pins; PyPI 0.1.1 has no `DefaultLoadPlanExecutor`. Reject `file_read_workers < 1` when the config is built, say when to raise it, and replace the test that re-read the config with one for the validation.
|
Thanks for the review! Yes, |
b564954 to
0d2c5c3
Compare
There was a problem hiding this comment.
The main thing I'm thinking about with this is that we should probably drop this parameter if we're moving to something like torchtitan.filesystem where we probe based on the path given whether that call should go to local or remote storage. So what that might buy us is that we can just create the loading storage and the saving storage for torch_checkpointing based on the path and what makes sense, and then all of the path probing that happens manually for checkpoint purging or whatever can just go through torchtitan.filesystem, similar to the DCP side. What do you think about this?
There was a problem hiding this comment.
Done:
- The
storage_configinit parameter is gone; storage comes from each path's scheme. - Probing and retention use
torchtitan.tools.filesystem, sharing DCP's adapter (nowFilesystemCheckpointStorageinbase.py).
One consequence: the backend's Path() drops // and /./ while probes keep them, so a remote path with such a segment now raises, as does a remote folder with a glob character. Open to alternatives.
| ) | ||
| hf_manager = hf_config.build() | ||
| try: | ||
| with self._sync_loader( |
There was a problem hiding this comment.
Ideally we don't use this _sync_loader? I think this is used for creating a storage but IMO we can just inline this, the context manager is a bit more abstraction than we need here.
There was a problem hiding this comment.
_sync_loader is removed; both load sites are inline.
|
@claude review |
There was a problem hiding this comment.
Verdict: Request changes -- ivy-zhou's design comment hasn't been addressed yet, and I think it's right. If the storage is picked from the path instead of the storage_config init parameter, most of the new routing code goes away. A maintainer still needs to review.
What this PR does. TorchCheckpointingManager now accepts a URI folder or initial_load_path. _BackendCheckpointStorage defaults the folder's storage to FsspecStorageConfig(protocol=...). It rejects a caller-supplied storage_config that can't hold the folder, and it sends each probed path to the storage its scheme names. Paths reach the backend without their scheme. Loads from a path on other storage than the folder go through a temporary sync manager (_sync_loader).
Example.
TorchCheckpointingManager.Config(folder="gs://b/run/ckpt", ...)
# main: ValueError: checkpointer.folder is a remote URI
# PR: backend storage = FsspecStorageConfig(protocol="gs"), save id "b/run/ckpt/step-500"
# probes/purge via _BackendCheckpointStorage -> FsspecStorage
# proposed: same backend storage, derived from the path alone;
# probes/purge via torchtitan.tools.filesystem, as DCP does on gs:// todayMust fix
torch_checkpointing.py:338-- ivy-zhou (unaddressed): dropstorage_configand derive storage from the path. I agree, with evidence:- No in-repo caller passes
storage_config. Only the tests do. - Once storage comes from the path, os/fsspec and the backend's Local/Fsspec storage address the same location. That was the only reason probes had to go through the backend
Storage(the class docstring at L123-125). - Two things then become deletable:
_can_hold, the mismatchValueError,folder_storage_config, and the_storagescache.- All of
_BackendCheckpointStorage. Move DCP's_FilesystemCheckpointStorage(dcp.py:~75-87) tobase.pynow that there are two consumers. It already handles object-store directory markers and turns off the fsspec listing cache, which matters for the purge thread and for other ranks.
- What stays is roughly:
plus
def _storage_config_for(path: str) -> StorageConfig | None: protocol, _ = _split_uri(path) # None keeps the backend's local default return None if protocol is None else FsspecStorageConfig(protocol=protocol)
_backend_pathand a protocol comparison in_load_checkpoint. - The tests
test_caller_supplied_storage_config_wins_for_a_remote_folder,test_storage_reads_each_path_from_the_storage_its_scheme_namesandtest_storage_config_is_an_init_parameter_not_a_config_fieldgo with it. - Rough size: about 150 lines fewer than this PR, and the local path stays the same as
main.
- No in-repo caller passes
README.md:97-101-- still open from the earlier review. The flat-bucket caveat is now a code TODO only. Users read the README, not_is_resumable_checkpoint, and on a flat bucket a preempted commit blocks auto-resume until someone deletes the step by hand. You offered a README note; please add the one sentence ("on flat (non-HNS) GCS buckets, prefer HNS; a preempted commit can leave astep-Nthat looks complete"). Also fix the description's "flat and HNS buckets" row to match.torch_checkpointing.py:560-- the TODO links a personal fork branch, not an upstream issue or PR (inline).
Should consider
torch_checkpointing.py:483-- ivy-zhou: inline_sync_loader. I partly agree. It has two callers, so it isn't single-use, but@contextmanagerplus thenullcontext(self._manager)switch at L501-505 is more machinery than the job needs. Inlining_default_backend_config(...).build()withtry/finally: close()would match_save_last_step(L694-707). It also gets simpler once item 1 lands.
Earlier review items
Resolved: the upstream TODO at L82, a single _storage, the redundant mocked probe test removed, _memory_bucket() reused, and the pin comment. Still open: item 2.
Details
- Gate. The problem is real on
main:__init__raises on any URI folder. DCP already supportsgs://, so this brings the two managers to parity. Right layer. The upstream gap (the backend wraps ids inPath()) has a TODO linkingtorch_checkpointing#12. - Why the redesign is safe. The backend storage depends only on the path's protocol (Local or
Fsspec(protocol)), andtorchtitan.tools.filesystemresolves the same protocol with fsspec's default credentials. That is the setup DCP already runs ongs://. KeepNonefor a local folder so the backend's local default is the same as onmain. The HF export'sLocalFileSystemStorageConfig(use_direct_io=False)fallback stays as is. - Open question for ivy-zhou / maintainers: whether any out-of-repo caller depends on a custom
storage_config(credentials, a non-fsspec store). No in-repo caller does, and torchtitan promises no BC, so it shouldn't block the change. - Rest of the diff. The HF guards move from
base.pytodcp.pyunchanged, with a TODO pointing at pytorch/pytorch#205015. The CI pin has a TODO. The purge thread only touches folder-protocol paths, which are pre-populated, so the_storagesdict isn't mutated concurrently at HEAD.
Not verified: real GCS behavior, and the CPU unit tests (I didn't run them).
| # TODO: On a flat (non-HNS) GCS bucket the commit rename copies each | ||
| # object and is not atomic, so a preempted commit can leave a step-N that | ||
| # has metadata.pkl but not all of its shards, and this accepts it. Fixed | ||
| # once torch_checkpointing publishes metadata.pkl after the rename | ||
| # (zhixiangli/torch_checkpointing:checkpoint-writer-metadata-staging). |
There was a problem hiding this comment.
This TODO points at a branch on a personal fork (zhixiangli/torch_checkpointing:checkpoint-writer-metadata-staging). That reference stops meaning anything once the branch is renamed or deleted, and nobody can track it from the main repo. Please link an issue or PR on meta-pytorch/torch_checkpointing instead, the same way the TODO at line 82 links torch_checkpointing#12.
There was a problem hiding this comment.
The TODO now links meta-pytorch/torch_checkpointing#17.
…fig to DCP's CheckpointManager.Config The guards rejecting last_save_in_hf with a remote folder and initial_load_in_hf with a remote initial_load_path exist because DCP's Hugging Face storage only handles local paths (pytorch/pytorch#205015). They lived in the shared BaseCheckpointManager.Config, so they also applied to TorchCheckpointingManager, whose HF export and load go through torch_checkpointing's Storage instead. Move them into CheckpointManager.Config, with a TODO to drop them once #205015 reaches nightly. No behavior change: the DCP backend raises the same errors, and TorchCheckpointingManager still rejects every remote URI.
…ch as gs:// TorchCheckpointingManager rejected any remote checkpointer.folder or initial_load_path, so checkpoints needed a mounted bucket. With torch_checkpointing's FsspecStorage (meta-pytorch/torch_checkpointing#12), the storage now follows the folder: a URI folder, or a relative folder under a remote dump folder (--output-dir gs://...), selects FsspecStorageConfig for its protocol, and a local folder keeps local storage. The backend wraps every path in Path, which collapses the double slash of gs://bucket/x, so checkpoint ids reach it without their scheme (_backend_path) while the protocol (_protocol) selects the storage. Interval saves, the final save, resume, keep_latest_k retention, and Hugging Face export and load all go through that one storage. torch_checkpointing's HF export and load do all their I/O through its Storage, so HF needs no guard here; DCP keeps its own (previous commit). Never write elsewhere: - A caller-supplied storage_config that cannot hold the folder (LocalFileSystemStorageConfig for gs://, an fsspec config of another protocol, or a remote one for a local folder) is rejected at construction. - A manager has one storage, so an initial_load_path, or the hf_assets_path an HF initial load reads, on other storage is rejected at construction, and the storage adapter rejects any path on other storage instead of dropping its scheme. Tests: remote-folder saves, final save, retention deletes and resume by scheme-less path; a real-backend round trip on a file:// folder and an HF export and reload on a memory:// folder relative to a remote dump folder; listing a remote folder with incomplete step directories; the storage_config and same-storage rejections. Verified on real GCS (flat and hierarchical-namespace buckets).
…own storage Fine-tuning from Hugging Face weights downloaded to local disk while checkpointing to gs:// failed at startup: folder, initial_load_path and hf_assets_path had to be on one storage. The DCP backend accepts that config, since it resolves every path on its own. Writes stay on the folder's storage. Reads route by path: _BackendCheckpointStorage uses the folder's storage config for the folder's protocol, and the default config for any other protocol (local, or fsspec). Every path is still read from the storage its scheme names, never rewritten onto another one. _load builds its HF manager on the source's storage, and a native initial_load_path on other storage gets a temporary synchronous manager. The two same-storage rejections go away. A caller-supplied storage_config applies to the folder's protocol only; a load path on another protocol gets that protocol's default storage. Tests: real-backend loads of local HF assets and of a local native checkpoint with a memory:// folder, and per-path routing in the adapter; the same-storage rejection tests are removed. Verified on real GCS: HF initial load from local assets with a gs:// folder, HF export to gs://, and reload from that export.
…er and one load helper _BackendCheckpointStorage now parses the folder, defaults and validates its storage config, and routes each path by its own scheme, replacing the split between __init__ and the adapter and the four overlapping storage attributes. Temporary load-only managers (HF loads and initial_load_path on other storage) are built by one _sync_loader context manager instead of two hand-rolled build/try/finally blocks, one of which copied the async manager config with dataclasses.replace. No behavior change: checkpointer tests and a real flat/HNS GCS run match the previous commit.
…rage supports today The README promised any fsspec store and named s3fs for s3://, which was never tested; torch_checkpointing's own fsspec note says s3fs directory commits fail on the fsspec >= 2026.6 that CI installs. Name gs:// via gcsfs instead. It also implied a remote hf_assets_path works, but the tokenizer and safetensors index read it locally; say that a local hf_assets_path works next to a remote folder. The HF round-trip test now reloads through initial_load_path, the workflow the README describes, and no longer cites --output-dir gs://, which is not a supported workflow.
TorchCheckpointingManager imports torch_checkpointing.storage.fsspec_storage, which no PyPI release has yet (latest is 0.1.1). Pin the main commit that has it, as torch_remat is pinned, until a release is published. The [fsspec] extra is left out: it caps fsspec below 2026.6 and would undo pytorch#6095.
- Add TODOs for the upstream URI/Storage gap (meta-pytorch/torch_checkpointing#12) and for flat-bucket commits. - Keep a single _storage attribute, narrowed to _BackendCheckpointStorage. - Remove a redundant mocked probe test; reuse _memory_bucket() in two tests. - Point the requirements.txt pin comment at torch_checkpointing#13.
…e _sync_loader - Drop the storage_config init parameter and derive backend storage from each path's scheme via _storage_config. - Move DCP's _FilesystemCheckpointStorage to base.py as FilesystemCheckpointStorage and share it for path probing and purging instead of _BackendCheckpointStorage. - Inline _sync_loader at the HF and cross-storage native load sites. - Remove the four unit tests covering the deleted storage_config parameter.
…ument remote setup
- Reject a remote folder or initial_load_path with an empty or "." segment
("//", "/./"). The backend wraps paths in Path(), which drops those
segments, while probes and retention use the URI as written, so a save
landed where the next resume did not look and training restarted from
step 0. A trailing slash stays accepted.
- README: keep hf_assets_path local and include model.safetensors.index.json
(download_hf_assets.py --assets tokenizer index); adapters read it for the
export's shard layout and, for Qwen3.5, the HF key prefix. Recommend HNS
buckets on GCS, since a flat bucket commits by copying each object.
- Say "local hf_assets_path" in the class docstring, and drop the
_is_resumable_checkpoint docstring that said HF loading has not landed.
- Link full upstream URLs in the TODOs (pytorch/pytorch issue 205015,
meta-pytorch/torch_checkpointing issue 12) so the TODO tracker finds them.
- Tests: cover the rejection, keep_latest_k retention with an abandoned
staging directory in the real-backend URI round trip, and assert the HF
loader keeps local storage while the folder uses fsspec storage.
…emote folder - Reject a remote checkpointer.folder that contains '*', '?' or '['. Retention deletes through torchtitan.tools.filesystem.rmtree, and fsspec expands glob characters in the path of a recursive delete, so it removed what the pattern matched (e.g. another run's tmp_step-N) and left the stale directory in place. The backend also refuses to commit a save to such a path, so the folder could never hold a checkpoint. - A local folder and initial_load_path stay unrestricted: neither is globbed. - Tests: cover the rejection and both accepted cases.
…its upstream issue - Point the _is_resumable_checkpoint TODO at meta-pytorch/torch_checkpointing issue 17, which tracks the interrupted commit on a flat bucket. Issue 12 is about adding the fsspec backend. - Describe the fix as that issue proposes it: the fsspec backend moves metadata.pkl last.
…sh, scope the README to gs:// - Reject a remote folder or initial_load_path that ends in "//". The check stripped every trailing slash, so "gs://bucket/run/checkpoint//" passed; probes then joined step directories onto the URI as written while the backend dropped the empty segment, so retention never ran and the next resume found nothing and restarted from step 0. One trailing slash stays accepted. - README: say only gs:// is verified and that a URI carrying a host or port (e.g. hdfs://host:8020/path) is not supported, since the host would be read as part of the path. - Name the path-segment check in the TODO listing what to delete once torch_checkpointing keeps URI schemes.
- For a local path rmtree called shutil.rmtree(ignore_errors=True), so a failed retention delete raised nothing and the purge thread logged "Checkpointer deleted ..." for a directory that was still there. Ignore only a missing path, as the remote branch already does; the purge thread catches anything else and logs "Checkpointer failed to delete ...". - TorchCheckpointingManager logged these failures on main, through the backend Storage. Sharing FilesystemCheckpointStorage with DCP had dropped that; this restores it, and DCP now logs them too. - Test: a local delete that fails reaches the caller.
…need - Restore the _is_resumable_checkpoint docstring as it is on main; removing it was unrelated to this change. - README: keep the instruction to include the safetensors index and why, and drop the adapter details (export shard layout, Qwen3.5 key prefix). - Remove test_load_latest_on_remote_folder_ignores_incomplete_checkpoint_directories. Remote discovery now runs through FilesystemCheckpointStorage, which TestFindLoadStepRemote covers on memory://; test_remote_folder_round_trip covers resuming a URI folder with the real backend, and test_load_latest_ignores_incomplete_checkpoint_directories covers the metadata.pkl marker and the decoy directories. - Put test_hf_load_uses_temporary_model_only_manager_and_restores_model back on a local folder and drop its storage assertions; test_hf_initial_load_reads_local_assets_with_a_remote_folder covers local HF assets next to a remote folder with the real backend.
0d2c5c3 to
7625d5e
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- every must-fix item from the last review is resolved at 7625d5e, and the new commits don't add any blocking problem. This touches core checkpointer code, so a maintainer still needs to review.
What changed since the last review. storage_config and _BackendCheckpointStorage are gone. Each path's backend storage now comes from its scheme alone (_storage_config(path): None for local, FsspecStorageConfig(protocol) for a URI). Probes and retention go through the shared FilesystemCheckpointStorage, as on DCP. The manager also now rejects a remote path with // or /./ segments, and a remote folder with glob characters. filesystem.rmtree stops swallowing local delete errors other than a missing path.
Example.
TorchCheckpointingManager.Config(folder="gs://b/run/ckpt", keep_latest_k=2, ...)
# backend storage = FsspecStorageConfig(protocol="gs"), save id "b/run/ckpt/step-500"
# resume / retention -> torchtitan.tools.filesystem on "gs://b/run/ckpt/..."
# initial_load_path="/local/step-5" -> temporary sync manager on the backend's local default
# folder="gs://b/run//ckpt" or "gs://b/run*/ckpt" -> ValueError at constructionEarlier review items
- ivy-zhou: drop
storage_configand derive storage from the path -- resolved (torch_checkpointing.py:107-113,:316). - ivy-zhou: inline
_sync_loader-- resolved (:398-404,:424-435, sametry/finally: close()shape as_save_last_step). - README flat-bucket caveat -- resolved (
README.md:620-622), and the description's table row now matches. - The flat-bucket TODO linked a personal fork branch -- now links meta-pytorch/torch_checkpointing#17 (
:487-491).
Should consider
base.py:226-243-- Now that both managers use the singleFilesystemCheckpointStorage, theCheckpointStorageprotocol has one implementation. Folding it into directfilesystem.*calls inBaseCheckpointManagerwould delete the protocol, the class and the_storageattribute. It's already listed as a follow-up, and a separate PR is fine.
Details
- Local path is the same as on
main. For a local folder,_storage_configreturnsNone, so the async manager, the HF load manager, and the HF export fallback (LocalFileSystemStorageConfig(use_direct_io=False)) get the same configs as before. Local probes switch from the backendLocalFileSystemStoragetoos. That gives the same answers forisfile(exists and not isdirvs.os.path.isfile) andlistdir, and_find_load_stepdoesn't depend on listing order. rmtreechange.FilesystemCheckpointStorage.removeis the only caller offilesystem.rmtree, and it only runs insidepurge_thread, which catches the exception and logs it (base.py:68-74). So a failed local delete can't crash training. It just becomes visible, the same wayTorchCheckpointingManageralready reported it onmain.- Segment check. For a local path,
Path()andosboth normalize//, so the check rightly applies to URIs only. A single trailing slash is stripped before the comparison, and the backend'sPath()drops it too. - Glob check. torch_checkpointing refuses to commit to such a path anyway, so this turns a late failure into an early one. DCP's exposure in
filesystem.rmtreeis listed as a follow-up. - Load routing.
_load_checkpointreusesself._manageronly when the load path's protocol matches the folder's. In that case the storage config is the same, e.g.gs://in another bucket still reads throughFsspecStorageConfig("gs"). - Dependencies. The torch_checkpointing module isn't imported from
checkpointer/__init__.py, anddatasetsalready brings in fsspec, so the new top-levelFsspecStorageConfigimport adds no requirement to the default path.
Not verified: real GCS behavior and the CPU unit tests (I didn't run them).
ivy-zhou
left a comment
There was a problem hiding this comment.
LGTM, thank you for the fix! Sorry about the grossness with the checkpoint IDs in torch_checkpointing, this is definitely something we should cleanup upstream
…er override; agent self-review; rl/transport (#6407) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it approved, 30 then got a formal "request changes" from a maintainer, and about 20 more got substantive inline asks. In nearly all of them the bot either saw the problem and approved anyway, or never asked the questions maintainers ask most ("does the repo already do this?", "who should own this?"). The opposite failure, the bot blocking something a maintainer was fine with, is rare: in the PRs we sampled, 2 of its 81 must-fix items were wrong and about a third were minor (the empty human-written summary was the biggest source). **Example** (#6112, controller sizes the rollout worker pool): ``` before: bot approved 10 times; tianyu-l then blocked: "the controller reads rollouter.rollouts_per_worker to compute a count it hands back to the Rollouter -- violates encapsulation" after: same commit, new skill -> Request changes, must-fix #1: "controller.py:589 -- wrong owner for the worker count ..." ``` There was also no way for a code owner to overrule the bot except dismissing its review in the GitHub UI, and a later `@claude review again` would block again. ## What changed **Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`): - Verdict rules: Approve only when every remaining item is an edit the bot could write itself. Anything the author still owes (a design change, an unexplained golden change, evidence the PR rests on) is Request changes; anything only a maintainer can decide is Needs discussion. A hedge like "a maintainer should decide" can't come with Approve. - Always must-fix: a violated written rule, a silent wrong result, a second definition of an existing concept, a gate finding. - Design gate: new questions for the existing counterpart, in-repo ownership, and the design behind a bug; "ban only what doesn't work on main"; read the numbers behind a claim. The overlapping-PR search is mandatory and reported. - Re-review covers every commit since the last full review, including code taken from the bot's own suggestions. A scoped question gets a `COMMENT`, not a whole-PR verdict. - The bot fact-checks its own proposed fixes, and cites a source for claims about external tools or marks them unverified (never must-fix). - An empty "Summary (human-written)" is a one-line "Before merge" note that never affects the verdict. - Checklist: config ownership direction, general shared wrappers, dead code the PR creates, model variants as flavors, a mechanical pass over every new or changed function. **Code owner override** (`SKILL.md`, `claude-code.yml`, `CONTRIBUTING.md`): a code owner comments `@claude override` (optionally `@claude override 2,3: <reason>`); the bot approves if nothing else is open and doesn't re-raise the overridden items. A code owner's GitHub approval or "LGTM" is not an override, so a teammate can approve without the bot dropping its findings. Dismissing the bot's review still unblocks the PR, but isn't an override: the bot can't tell who dismissed it. **Agent self-review** (`CLAUDE.md`, `pr-description`): an agent preparing a PR runs `pr-review` in branch mode first and records unaddressed items in an optional "Self-review" section. PRs written without an agent are unaffected; a missing section is never a finding. Where each new rule comes from (maintainer asks the bot missed): | Change | PRs | | --- | --- | | No Approve with open design/evidence items or a "maintainer should decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 | | Author waiver can't clear a must-fix | #6201, #6202, #6203 | | Existing counterpart; one source of truth | #5228, #6169, #5881, #5823, #5824, #6059, #5812 | | Responsibility owner; config ownership direction | #6112, #6332, #5802, #5803, #6325 | | Fix the design behind the bug; a TODO doesn't justify a workaround | #5572, #5689, #5657 | | Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819, #5543 | | Re-review covers all new commits; scoped asks don't approve | #5824, #5842 | | Mandatory overlap search | #5885, #6248 | | Ban only what doesn't work on main | #5543 | | Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868 | **Rules**: `design.md` gets the one-general-wrapper rule (moved from `models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the consumer owning its values; `config.md` gets ownership direction and "a Config doesn't read runtime state"; `direction.md` calls all-to-all the MoE reference implementation, so a new vendor-specific dispatch path (e.g. #6242) needs a reason the existing backends can't serve. **Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/` -> d4l3k. **Mechanical, skim**: `torchtitan/rl/transport/` holds data movement between RL actors. - `rl/model_state_dict_transport.py` -> `rl/transport/model_state_dict.py` - `rl/MODEL_STATE_DICT_TRANSPORT.md` -> `rl/transport/MODEL_STATE_DICT_TRANSPORT.md` - `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py` - tests: `tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py` -> `tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py` - imports, READMEs and `scripts/install_rl_env.sh` updated; no code changes. ## User-facing changes | Before | After | | --- | --- | | Overrule the bot: dismiss its review in the UI, and it blocks again on the next run | `@claude override [items]: <reason>`; the bot approves and doesn't re-raise them | | Empty human-written summary: bot must-fix | One "Before merge" line, no effect on the verdict | | `from torchtitan.rl.model_state_dict_transport import ...` | `from torchtitan.rl.transport.model_state_dict import ...` | | `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from torchtitan.rl.transport.rdma_microbatch import ...` | ## Testing Backtest: the new skill run locally (nothing posted) on each PR at the commit and thread state the bot originally saw. | PR | Bot then | New skill | What the maintainer asked | | --- | --- | --- | --- | | #6112 | Approve | Request changes | worker-count ownership (caught) | | #5837 | Approve | Request changes | apply to `dp_shard` too (caught) | | #5572 | Approve | Request changes | delete the injection design (caught) | | #6201 | Approve after author waived pins | Request changes, waiver ignored | pins broke GPU tests after merge (caught) | | #6007 | Approve | Request changes | fold K3.1 into K3 (caught) | | #5543 | Request changes: "ban it" | Request changes: keep main's path | don't break gpt-oss + DeepEP (fixed) | | #6144, #5905 (controls) | Approve | Approve | -- | | #6137 (control) | Approve | Needs discussion | -- (merge gate on an upstream API) | Code owner override, simulated on #6201: override by a code owner lifts the named item; `@claude override` from the author changes nothing; a code owner's "LGTM" approval followed by "review again" keeps Request changes. Transport move: 83 RL CPU unit tests pass locally (`transport/test_model_state_dict.py`, `test_trainer.py`, `test_engine_loop.py`). `transport/test_rdma_microbatch.py`, `test_generator.py` and `test_batcher_actor.py` fail to collect in my env on `origin/main` too (stale attention-gym / Monarch), so CI is the check for those. ## Known issues / follow-ups - Open PRs that edit the moved files rebase cleanly (git follows the renames), but new imports of the old module paths will break: #6309 (adds a delta transport that should live in `rl/transport/`), #6237, #6176, #6177, #5862, and drafts #6127, #6393, #6163, #5764. - The Actions bot can't read dependency source (e.g. SGLang); follow-up for the workflow. ## Self-review pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch mode diffs against `origin/main` and skips description findings before a description exists; the "Config doesn't read runtime state" rule no longer contradicts hardware validation; dismissal dropped as an override form (the bot can't tell who dismissed); `test_rdma_microbatch.py` added to the transport area. Not addressed: - One concern per PR -- the five changes ship together at the maintainer's request. - Open PRs touching the moved files -- listed above; the maintainer will coordinate.
Summary (human-written)
TorchCheckpointingManagerrejects any remotecheckpointer.folderorinitial_load_path, so it needs the bucket mounted, which containers without FUSE and managed platforms can't do. meta-pytorch/torch_checkpointing#13 adds an fsspecStorage; this PR wires it in, as DCP already has (#3887, #6061).On
mainthis raisesValueError: checkpointer.folder is a remote URI (...).Rejected: mounting the bucket (not available everywhere); copying the HF weights into the bucket (DCP doesn't require it).
Why
TorchCheckpointingManager.__init__raises on any URI incheckpointer.folderorcheckpointer.initial_load_path, so its checkpoints can only live on a mounted filesystem. DCP's manager already acceptsgs://.Example.
What changed
9 files, +443 / -214.
base.py->dcp.py: the two remote-HF config guards (last_save_in_hfwith a remotefolder,initial_load_in_hfwith a remoteinitial_load_path) move unchanged to DCP'sCheckpointManager.Config, with a TODO for [DCP] Support fsspec URIs (gs://,s3://) in Hugging Face safetensors storage pytorch#205015. Only DCP's HF storage is local-only.dcp.py->base.py:_FilesystemCheckpointStoragemoves unchanged and becomesFilesystemCheckpointStorage, shared by both managers.test_checkpoint.pyonly follows the rename.torch_checkpointing.py, +83 / -63):folderandinitial_load_path.storage_configinit parameter (added in Route saves through the torch_checkpointing backend #4188; no in-repo caller)._storage_config(path)derives the backend storage from each path's scheme: the backend's local default for a local path,FsspecStorageConfig(protocol=...)for a URI._split_uri/_backend_pathhand paths to the backend without their scheme, because it wraps ids inPath(), which turnsgs://b/xintogs:/b/x. A TODO links Add an fsspecStoragebackend for remote stores (gs://,s3://) meta-pytorch/torch_checkpointing#12.FilesystemCheckpointStorage(torchtitan.tools.filesystem), replacing_BackendCheckpointStorage.folder(initial_load_path, or the localhf_assets_pathof an HF initial load) builds a temporary synchronous manager on that path's storage.torchtitan/tools/filesystem.py, +9 / -10): for a local path,rmtreenow ignores only a missing path instead of every error, as its remote branch already did. A failed retention delete then reaches the purge thread, which logs it.TorchCheckpointingManagerlogged these onmainthrough the backendStorage; without this, moving to the shared adapter would have silenced them.TorchCheckpointingManager", scoped to what was verified (gs://viagcsfs). Tests are listed under Testing..ci/docker/requirements.txt): pintorch_checkpointingtomaincommit5c45dc3(see "Depends on"). The[fsspec]extra is left out: it capsfsspec < 2026.6and would undo [CI deps] Require datasets >= 5.2.0 so fsspec can move to the latest #6095.Alternatives considered
storage_configand route probes through the backendStorage(the previous revision of this PR): about 170 more net lines (_BackendCheckpointStorage,_can_hold, a storage cache) for a parameter no in-repo caller passes. Dropped on review.//and/./in a URI instead of rejecting them: it would silently rewrite the path the user gave.User-facing changes
folderorinitial_load_pathonTorchCheckpointingManager->ValueErrorgs://viagcsfs, flat and HNS buckets. On a flat bucket a preempted commit can leave astep-Nthat looks complete (see README; meta-pytorch/torch_checkpointing#17)last_save_in_hfwith a remotefolder, orinitial_load_in_hfwith a remoteinitial_load_path->ValueErrorinBaseCheckpointManager.ConfigTorchCheckpointingManager; DCP'sCheckpointManager.Configkeeps the same guards until pytorch/pytorch#205015TorchCheckpointingManager(..., storage_config=...)folderorinitial_load_pathwith an empty or.segment (//,/./) ->ValueErrorat construction. One trailing slash is acceptedfoldercontaining*,?or[->ValueErrorat constructionTorchCheckpointingManageralready didLocal folders and DCP otherwise behave as before.
Numerics
No training computation changes. llama3 debugmodel, FSDP over 8x A100 80GB,
seed=42, deterministic,lr_scheduler.total_steps=20in every run. Head7625d5e45, base168567471. torch2.16.0.dev20261116+cu132, torch_checkpointing5c45dc3, gcsfs2026.10.1, fsspec2026.9.0. Local runs use a plain local folder;gs://runs use a flat bucket and a hierarchical-namespace (HNS) bucket in us-central1.loss_metrics/global_avg_loss,loss_metrics/global_max_lossandgrad_normwere compared at full precision from TensorBoard, with exact equality.gs://vs. local (interval 5,keep_latest_k=2)step-10ongs://vs. local (retention deletesstep-5,step-10;step-15,step-20remain)async_mode="async_with_pinned_mem"hf_assets_path,gs://folder vs. local folderinitial_load_path(model only,step-20):gs://-> local folder, and local ->gs://folder, vs. local -> localexports/step-10),gs://vs. local, sha256"Identical HF files": the 8
model-0000N-of-00008.safetensors,model.safetensors.index.jsonand the 8 per-ranksharded/model_N.safetensorsare byte-identical. The bytes ofsharded/metadata.pkldiffer, but it unpickles to the same content once dict order is ignored.Local folder, base
168567471vs. this PR: save steps 1-10 and resume steps 11-20 are bitwise identical. Local folder, async vs. sync saves on this PR: also bitwise identical.Testing
pytest tests/unit_tests/cpu/components/checkpointer/: 128 passed, andpytest tests/unit_tests/cpu/tools/test_filesystem.py: 14 passed (CPU, torch_checkpointing5c45dc3). New tests and the regression each catches:test_remote_folder_uses_fsspec_storage_and_scheme_less_save_ids: ags://id reaching the backend with its scheme; a remote path with//,/./or a doubled trailing slash, or a remote folder with a glob character, being accepted.test_remote_folder_round_trip(file://, real backend): broken save -> retention -> resume on a URI folder, including an abandoned staging directory.test_remote_folder_hf_round_trip(memory://, real backend): broken HF export -> HF load on a URI folder.test_hf_initial_load_reads_local_assets_with_a_remote_folderandtest_initial_load_path_on_other_storage_than_the_folder: a load path on other storage being read through the folder's storage.test_rmtree_propagates_a_failed_local_delete: a failed local delete being swallowed, so the purge thread reports a deletion that did not happen.On real flat and HNS GCS buckets, the 8x A100 runs under Numerics cover interval saves,
keep_latest_k, resume, both initial-load directions and HF export, in sync and async mode.A simulated interrupted commit on a flat bucket (single process, CPU, at
4477ebb38) reproduces the README caveat:step-1holds onlymetadata.pkl, resume selects it, and the load raisesFileNotFoundError. On the HNS bucket the commit is a single folder rename.Depends on meta-pytorch/torch_checkpointing#13, which landed on
mainas5bda153but is not in a release yet (latest is0.1.1)..ci/docker/requirements.txtpinsmainat5c45dc3(one commit after5bda153, a test type-check fix) until a release is published.Known issues / follow-ups
CheckpointWriter: recover cleanly from interrupted commits on non-atomic stores meta-pytorch/torch_checkpointing#17. Until it is fixed, prefer HNS buckets forgs://.torchtitan.tools.filesystem.rmtreelets fsspec expand*,?and[. This PR rejects such folders forTorchCheckpointingManageronly; DCP onmainhas the same exposure.CheckpointStorageprotocol: both managers now use the oneFilesystemCheckpointStorage, so the protocol can be folded intoBaseCheckpointManager.hdfs://host:8020/path) are not supported: the host would be read as part of the path.step-N/tmp_step-N/exports/step-Nand drain in-flight purges.hf_assets_path(tokenizer, safetensors index): [checkpoint] Hugging Face on fsspec URIs (gs://): DCP HF checkpoints and hf_assets_path #6102.torch_checkpointinggit pin with the first release that includes5bda153.write_to_temp_dirwarning:_writer_config(use_barrier=False)should setwrite_to_temp_dir=False; torch_checkpointing warns this will become an error._is_resumable_checkpointruns three times for the selected checkpoint (_find_load_step,BaseCheckpointManager.load(),TorchCheckpointingManager._load_checkpoint()).Fixes #6103