Skip to content

Support remote fsspec checkpoint paths (e.g. gs://) via filesystem helpers - #3887

Merged
fegin merged 4 commits into
pytorch:mainfrom
zhixiangli:gcs-fsspec-checkpoint
Jul 15, 2026
Merged

fegin merged 4 commits into
pytorch:mainfrom
zhixiangli:gcs-fsspec-checkpoint

Conversation

@zhixiangli

@zhixiangli zhixiangli commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Fix #3884

Add torchtitan/tools/filesystem.py to transparently dispatch path ops to os/shutil for local paths and fsspec for remote URIs, then route checkpoint.py's directory listing/existence/cleanup through it so checkpoints can be written to and read from remote storage like GCS.

  • Fresh run passes
NGPU=4 CONFIG=llama3_debugmodel ./run_train.sh --training.steps 20 --checkpoint.enable --checkpoint.interval 10 --checkpoint.folder gs://...
  • Resume run passes
NGPU=4 CONFIG=llama3_debugmodel ./run_train.sh --training.steps 40 --checkpoint.enable --checkpoint.folder gs://...

co-authored-by: @YassineYousfi

…lpers

Add torchtitan/tools/filesystem.py to transparently dispatch path ops to
os/shutil for local paths and fsspec for remote URIs, then route
checkpoint.py's directory listing/existence/cleanup through it so
checkpoints can be written to and read from remote storage like GCS.
@meta-cla

meta-cla Bot commented Jul 8, 2026

Copy link
Copy Markdown

Hi @zhixiangli!

Thank you for your pull request.

We require contributors to sign our Contributor License Agreement, and yours needs attention.

You currently have a record in our system, but the CLA is no longer valid, and will need to be resubmitted.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@pytorch-bot

pytorch-bot Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 8, 2026
@meta-cla

meta-cla Bot commented Jul 8, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

Object stores (GCS, S3) can list a directory-marker entry for the
listed directory itself, which os.listdir never returns. Filter it
out by full normalized path so a legitimate child sharing the
parent's basename is still kept.
Keeps the module-level docstring focused on the public contract and
moves implementation-detail explanations (DCP heuristic match, listdir
directory-marker handling) into the relevant function docstrings.
@fegin

fegin commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Hi @zhixiangli, the PR looks clean. It does mostly the same thing as #3730, but I would like to land this one because it handles the HF safetensors format (errors out on remote paths) and falls back to os for local paths by default. I will also mark @YassineYousfi as a co-author, since #3730 came earlier and we spent time discussing there. Let me know if you have any concerns.

Comment thread torchtitan/components/checkpoint.py Resolved
Comment thread torchtitan/tools/filesystem.py Resolved
Comment thread torchtitan/components/checkpoint.py Resolved
os.path.join uses the platform separator and won't correctly join a
local base with a fsspec remote path; route checkpoint path
construction through filesystem.join instead.
@zhixiangli
zhixiangli requested a review from fegin July 14, 2026 03:42

@fegin fegin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR.

@fegin
fegin merged commit fec3e19 into pytorch:main Jul 15, 2026
18 of 22 checks passed
@zhixiangli
zhixiangli deleted the gcs-fsspec-checkpoint branch July 15, 2026 11:53
rcloyd pushed a commit to rcloyd/torchtitan that referenced this pull request Jul 24, 2026
Resolved conflicts in torchtitan/experiments/torchft/checkpoint.py:
- imports: keep our 'import functools' (used by functools.partial); drop
  'import os' (no longer needed after adopting upstream's filesystem.join)
- _ft_folder(): adopt upstream's filesystem.join (remote fsspec path
  support, pytorch#3887) while keeping our 'ft-replica' folder-name typo fix
tianyu-l pushed a commit that referenced this pull request Nov 24, 2026
…ch as gs:// (#6169)

## Summary (human-written)
`TorchCheckpointingManager` rejects any remote `checkpointer.folder` or
`initial_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 fsspec `Storage`; this PR
wires it in, as DCP already has (#3887, #6061).

```python
checkpointer=TorchCheckpointingManager.Config(
    folder="gs://my-bucket/run-1/checkpoint",
    initial_load_in_hf=True,  # hf_assets_path stays on local disk
    last_save_in_hf=True,
)
```

On `main` this raises `ValueError: 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 in
`checkpointer.folder` or `checkpointer.initial_load_path`, so its
checkpoints can only live on a mounted filesystem. DCP's manager already
accepts `gs://`.

**Example.**
```python
checkpointer=TorchCheckpointingManager.Config(
    folder="gs://my-bucket/run-1/checkpoint",
    interval=500,
    keep_latest_k=2,
    initial_load_in_hf=True,  # hf_assets_path stays on local disk
    last_save_in_hf=True,
)
# main: ValueError: checkpointer.folder is a remote URI (...)
# PR:   backend storage   = FsspecStorageConfig(protocol="gs"), from the folder's scheme
#       interval save     -> backend id "my-bucket/run-1/checkpoint/step-500" (no scheme)
#       resume, retention -> torchtitan.tools.filesystem, as DCP does on gs://
#       HF initial load   -> the local hf_assets_path, read with local storage
#       HF final export   -> gs://my-bucket/run-1/checkpoint/exports/step-N
```

## What changed
9 files, +443 / -214.

- **Mechanical (can skim):**
- `base.py` -> `dcp.py`: the two remote-HF config guards
(`last_save_in_hf` with a remote `folder`, `initial_load_in_hf` with a
remote `initial_load_path`) move unchanged to DCP's
`CheckpointManager.Config`, with a TODO for pytorch/pytorch#205015. Only
DCP's HF storage is local-only.
- `dcp.py` -> `base.py`: `_FilesystemCheckpointStorage` moves unchanged
and becomes `FilesystemCheckpointStorage`, shared by both managers.
`test_checkpoint.py` only follows the rename.
- **Logic (`torch_checkpointing.py`, +83 / -63):**
- Remove the construction-time rejection of a remote `folder` and
`initial_load_path`.
- Remove the `storage_config` init parameter (added in #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_path` hand paths to the backend without their
scheme, because it wraps ids in `Path()`, which turns `gs://b/x` into
`gs:/b/x`. A TODO links meta-pytorch/torch_checkpointing#12.
- Probing and retention go through `FilesystemCheckpointStorage`
(`torchtitan.tools.filesystem`), replacing `_BackendCheckpointStorage`.
- A load from another protocol than `folder` (`initial_load_path`, or
the local `hf_assets_path` of an HF initial load) builds a temporary
synchronous manager on that path's storage.
  - Two checks at construction, listed under User-facing changes.
- **Logic (`torchtitan/tools/filesystem.py`, +9 / -10):** for a local
path, `rmtree` now 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. `TorchCheckpointingManager` logged
these on `main` through the backend `Storage`; without this, moving to
the shared adapter would have silenced them.
- **Docs and tests:** a README section, "Remote storage with
`TorchCheckpointingManager`", scoped to what was verified (`gs://` via
`gcsfs`). Tests are listed under Testing.
- **CI deps (`.ci/docker/requirements.txt`):** pin `torch_checkpointing`
to `main` commit `5c45dc3` (see "Depends on"). The `[fsspec]` extra is
left out: it caps `fsspec < 2026.6` and would undo #6095.

## Alternatives considered
- Keep `storage_config` and route probes through the backend `Storage`
(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.
- Normalize `//` and `/./` in a URI instead of rejecting them: it would
silently rewrite the path the user gave.

## User-facing changes

| Before | After |
| --- | --- |
| Remote `folder` or `initial_load_path` on `TorchCheckpointingManager`
-> `ValueError` | Accepted and routed by scheme. Verified on `gs://` via
`gcsfs`, flat and HNS buckets. On a flat bucket a preempted commit can
leave a `step-N` that looks complete (see README;
meta-pytorch/torch_checkpointing#17) |
| `last_save_in_hf` with a remote `folder`, or `initial_load_in_hf` with
a remote `initial_load_path` -> `ValueError` in
`BaseCheckpointManager.Config` | Supported on
`TorchCheckpointingManager`; DCP's `CheckpointManager.Config` keeps the
same guards until pytorch/pytorch#205015 |
| `TorchCheckpointingManager(..., storage_config=...)` | Parameter
removed; storage comes from each path's scheme |
| -- | A remote `folder` or `initial_load_path` with an empty or `.`
segment (`//`, `/./`) -> `ValueError` at construction. One trailing
slash is accepted |
| -- | A remote `folder` containing `*`, `?` or `[` -> `ValueError` at
construction |
| DCP, local folder: a failed retention delete is ignored silently |
Logged as a warning by the purge thread, as `TorchCheckpointingManager`
already did |

Local 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=20` in every
run. Head `7625d5e45`, base `168567471`. torch
`2.16.0.dev20261116+cu132`, torch_checkpointing `5c45dc3`, gcsfs
`2026.10.1`, fsspec `2026.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_loss` and `grad_norm` were compared at full
precision from TensorBoard, with exact equality.

| Comparison (same commit, storage is the only difference) | Steps |
Flat | HNS |
| --- | --- | --- | --- |
| Save to `gs://` vs. local (interval 5, `keep_latest_k=2`) | 1-10 |
Bitwise identical | Bitwise identical |
| Resume from `step-10` on `gs://` vs. local (retention deletes
`step-5`, `step-10`; `step-15`, `step-20` remain) | 11-20 | Bitwise
identical | Bitwise identical |
| The same save and resume with `async_mode="async_with_pinned_mem"` |
1-20 | Bitwise identical | Bitwise identical |
| HF initial load from a local `hf_assets_path`, `gs://` folder vs.
local folder | 1-10 | Bitwise identical | Bitwise identical |
| Native `initial_load_path` (model only, `step-20`): `gs://` -> local
folder, and local -> `gs://` folder, vs. local -> local | 1-10 | Bitwise
identical | Bitwise identical |
| Final HF export (`exports/step-10`), `gs://` vs. local, sha256 | -- |
Identical HF files | Identical HF files |

"Identical HF files": the 8 `model-0000N-of-00008.safetensors`,
`model.safetensors.index.json` and the 8 per-rank
`sharded/model_N.safetensors` are byte-identical. The bytes of
`sharded/metadata.pkl` differ, but it unpickles to the same content once
dict order is ignored.

Local folder, base `168567471` vs. 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, and
`pytest tests/unit_tests/cpu/tools/test_filesystem.py`: 14 passed (CPU,
torch_checkpointing `5c45dc3`). New tests and the regression each
catches:

- `test_remote_folder_uses_fsspec_storage_and_scheme_less_save_ids`: a
`gs://` 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_folder` and
`test_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-1` holds only
`metadata.pkl`, resume selects it, and the load raises
`FileNotFoundError`. On the HNS bucket the commit is a single folder
rename.

**Depends on** meta-pytorch/torch_checkpointing#13, which landed on
`main` as `5bda153` but is not in a release yet (latest is `0.1.1`).
`.ci/docker/requirements.txt` pins `main` at `5c45dc3` (one commit after
`5bda153`, a test type-check fix) until a release is published.

## Known issues / follow-ups

- **Flat-bucket commits:** meta-pytorch/torch_checkpointing#17. Until it
is fixed, prefer HNS buckets for `gs://`.
- **Glob characters in remote deletes:**
`torchtitan.tools.filesystem.rmtree` lets fsspec expand `*`, `?` and
`[`. This PR rejects such folders for `TorchCheckpointingManager` only;
DCP on `main` has the same exposure.
- **`CheckpointStorage` protocol:** both managers now use the one
`FilesystemCheckpointStorage`, so the protocol can be folded into
`BaseCheckpointManager`.
- **URIs that carry a host or port** (e.g. `hdfs://host:8020/path`) are
not supported: the host would be read as part of the path.
- **Re-saving an existing step or export:** replace stale `step-N` /
`tmp_step-N` / `exports/step-N` and drain in-flight purges.
- **Remote `hf_assets_path`** (tokenizer, safetensors index): #6102.
- **Release pin:** replace the `torch_checkpointing` git pin with the
first release that includes `5bda153`.
- **`write_to_temp_dir` warning:** `_writer_config(use_barrier=False)`
should set `write_to_temp_dir=False`; torch_checkpointing warns this
will become an error.
- **Repeated resume checks:** `_is_resumable_checkpoint` runs three
times for the selected checkpoint (`_find_load_step`,
`BaseCheckpointManager.load()`,
`TorchCheckpointingManager._load_checkpoint()`).

Fixes #6103
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support saving/loading checkpoints to fsspec URIs (e.g. gs://, s3://)

2 participants