Skip to content

[checkpoint] Read remote checkpoint folders without fsspec's listing cache - #6061

Merged
tianyu-l merged 7 commits into
pytorch:mainfrom
zhixiangli:fsspec-fresh-listing
Nov 12, 2026
Merged

tianyu-l merged 7 commits into
pytorch:mainfrom
zhixiangli:fsspec-fresh-listing

Conversation

@zhixiangli

@zhixiangli zhixiangli commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Why

With checkpointer.folder on a remote fsspec path and async_mode="async_with_pinned_mem", keep_latest_k never deletes a checkpoint. torchtitan/tools/filesystem.py reads the folder through fsspec's listing cache, which only sees changes made through the same filesystem instance, and the save subprocess writes through its own. With fsspec older than 2026.6.0 each thread also has its own instance, so async_mode="async" is affected too. Fixes #6062.

Example. The 1-GPU run from #6062 (debug model, gs:// folder, interval=2, keep_latest_k=2, 12 steps, fsspec 2026.9.0, gcsfs 2026.10.1). Folder after the run:

Checkpoints left
main step-2, step-4, step-6, step-8, step-10, step-12
this PR step-10, step-12

What changed

  • torchtitan/tools/filesystem.py: _resolve creates the filesystem with use_listings_cache=False. Every remote helper (exists, isdir, isfile, listdir, rmtree) goes through it. One save's probes on a folder with 11 step directories take 19 object-store requests instead of 16. No config or API change.
  • Tests: new tests/unit_tests/gpu/components/test_checkpoint.py, and a check in tests/unit_tests/cpu/tools/test_filesystem.py (see Testing).

Alternatives considered

  • fs.invalidate_cache(path) before each probe: same requests and results, but every probe has to invalidate the entries it reads.
  • Fix it in fsspec or gcsfs: a client-side listing cache cannot see another process's writes without asking the server; gcsfs documents that its cache goes stale in that case.

Testing

  • New TestAsyncWithPinnedMemRetention (tests/unit_tests/gpu/components/test_checkpoint.py, 1 GPU, about 5 s): real CheckpointManager.save with async_mode="async_with_pinned_mem", so DCP saves from its subprocess, and real keep_latest_k=2 purging, into a file:// folder whose listings the trainer process caches the way gcsfs does. On main it ends with ['step-1', 'step-2', 'step-3', 'step-4'] != ['step-3', 'step-4'].
  • New test_remote_filesystem_has_no_listing_cache: catches the use_listings_cache=False argument being dropped.
  • The [checkpoint] keep_latest_k never purges remote (fsspec) checkpoint folders with async_with_pinned_mem #6062 repro on 1x A100 with torch 2.16.0.dev20261112: the table above.

…cache

fsspec keeps one filesystem instance per thread, and its directory-listing
cache has no expiry by default. keep_latest_k lists the checkpoint folder on
the main thread while the purge thread deletes and async saves write through
other instances, so on a remote folder it kept re-deleting a checkpoint that
was already gone and never deleted the next one.

Create the filesystem with use_listings_cache=False in _resolve, which every
remote helper goes through.
With fsspec >= 2026.6.0 threads share one filesystem instance for async
backends such as gcsfs, so a second thread no longer reproduces the stale
listing. A save subprocess (async_with_pinned_mem) still does on every
fsspec version: model it with a second filesystem instance.
Serve a temp directory through a local filesystem that caches listings per
instance, so a subprocess can write the new step directory the way the
async_with_pinned_mem save process does.
Replaces the subprocess.run command line with a spawned worker that calls
os.makedirs. spawn, not fork: forking the multi-threaded test process can
deadlock.
Replace the CPU listdir test with a GPU test that runs CheckpointManager.save
with async_mode="async_with_pinned_mem" (DCP saves from its subprocess) and
real keep_latest_k purging, into a file:// folder whose listings the trainer
process caches the way gcsfs does. Keep the CPU check that _resolve turns the
listing cache off.
Register a caching subclass as file:// in the trainer process instead of
patching LocalFileSystem.ls, and delete the test's temp folder.
@zhixiangli
zhixiangli marked this pull request as ready for review November 12, 2026 17:57
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 12, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

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

The GPU test's caching filesystem never invalidates its listings, so it
failed on main even with synchronous saves: the save subprocess, CUDA and
NCCL played no part. Replace it, and the check that read the private
use_listings_cache flag, with one CPU test: list a folder through a
listing-caching file:// filesystem, create a step directory outside the
filesystem instance (as DCP's save process does), and list again.
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 27s —— View job


Approve -- please update the PR description to match HEAD before merging (it still describes tests that were removed). See the review.

@claude claude Bot 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.

Verdict: Approve -- please address the items below before merging. The fix is a one-argument change at the right place: the only url_to_fs call in torchtitan. A maintainer still needs to review, because this touches core checkpoint IO.

What this PR does. _resolve in torchtitan/tools/filesystem.py now builds the fsspec filesystem with use_listings_cache=False. Every remote helper (exists, isdir, isfile, listdir, rmtree) goes through _resolve, so the trainer no longer reads a checkpoint folder from a stale listing. One new CPU test guards this.

Example. folder="gs://b/ckpt", interval=2, keep_latest_k=2, async_mode="async_with_pinned_mem":

step 2: DCP subprocess writes step-2; trainer listdir -> fills dircache["b/ckpt"]
step 4: subprocess writes step-4 through its own fs instance; the trainer's cache isn't invalidated
        _purge_stale_checkpoints -> listdir returns the cached [step-2] -> nothing to purge
...
main:    step-2 ... step-12 all kept
this PR: each listdir asks the object store -> step-10, step-12 kept

Must fix

  1. The PR description doesn't match HEAD. The last commit (d8fc78f) deleted tests/unit_tests/gpu/components/test_checkpoint.py / TestAsyncWithPinnedMemRetention and test_remote_filesystem_has_no_listing_cache. The description still lists both under "What changed" and "Testing". The only test now is TestRemoteListingCache.test_listdir_sees_a_directory_created_by_another_process. Please update both sections to describe it, and say that it fails on main (second listdir returns ['step-1']). The "Summary (human-written)" section is also empty and needs the author's own summary.
Details
  • Necessity gate. The issue is real and reproduced in #6062 with a concrete recipe. Root cause: fsspec's DirCache only invalidates on writes made through the same instance, and listings_expiry_time defaults to None, so the cache never expires. The save subprocess (and, before fsspec 2026.6.0, other threads) write through their own instances. A client-side cache can't see another process's writes, so fixing this in fsspec or gcsfs doesn't fit. Turning the cache off where torchtitan creates the fs is the smallest correct fix. I found no overlapping open PR, and nothing in direction.md conflicts.
  • Side effects. use_listings_cache is a DirCache kwarg that AbstractFileSystem.__init__ forwards. The memory:// backend in the existing TestRemoteOps tests exercises the same path. The changed kwargs give a separate cached fsspec instance from the one DCP's FsspecWriter uses, which is fine because the two never share listings anyway. The cost is a few extra listing requests per save (the description measured 16 -> 19), outside the training step.
  • Test value. Retention silently breaking on remote folders is a real, otherwise-unguarded invariant, and the test is CPU-only and fast. The _ListingCachingLocalFileSystem stores into self.dircache, which drops writes when use_listings_cache=False. So the test guards the actual argument, not a mocked one.

Not verified: I didn't run the new test locally, and I couldn't check the GCS repro (it needs a GPU and a bucket).

@tianyu-l
tianyu-l merged commit 240d6bf into pytorch:main Nov 12, 2026
@zhixiangli
zhixiangli deleted the fsspec-fresh-listing branch November 13, 2026 04:44
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/fake-pg Run 1-GPU Fake PG integration tests 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.

[checkpoint] keep_latest_k never purges remote (fsspec) checkpoint folders with async_with_pinned_mem

2 participants