Skip to content

[release/2.13] Fix remaining checkpoint filesystem races flagged in #194614 (#196591) - #3659

Merged
pragupta merged 1 commit into
release/2.13from
albmalamd/cherry-pick/2.13/fix_post_localSGD_optimizer_step_reload
Sep 21, 2026
Merged

pragupta merged 1 commit into
release/2.13from
albmalamd/cherry-pick/2.13/fix_post_localSGD_optimizer_step_reload

Conversation

@albmalamd

Copy link
Copy Markdown

Follow-up to pytorch#194614. That PR fixed a checkpoint reload race in post-local SGD tests but noted in review (comment) that the same bug shapes exist in several other places. This PR fixes those remaining sites.

Root cause

Three related races, all stemming from sharing a checkpoint through the filesystem across ranks instead of through a collective:

  1. Fixed-name collision: a checkpoint path is built from a hardcoded name under the shared temp dir (e.g. tempfile.gettempdir() + "/model.checkpoint"). Two test processes running concurrently on the same host can collide on that name, so one run's rank 0 can overwrite the file while another run's rank 1 is loading it, producing _pickle.UnpicklingError/EOFError (torch.save is not atomic).
  2. Delete-under-you: a directory or file is created by rank 0 and read by all ranks, then removed with no dist.barrier() between the last read and the removal. Whichever rank finishes first can delete the path while a peer hasn't opened it yet, producing FileNotFoundError.
  3. Recreate-under-you: rank 0 does shutil.rmtree(path) then os.makedirs(path) with no barrier before the peers enter save_state_dict. The data writes cannot interleave here: every rank's prepare_local_plan calls fs.mkdir(path, exist_ok=True), that runs inside the "plan" reduce_scatter, and the writes only happen after it. What a peer does land in that window is the fs.mkdir, recreating the directory between rank 0's rmtree and its os.makedirs. That os.makedirs has no exist_ok=True, so rank 0 raises FileExistsError.

Fix

  • test/distributed/test_c10d_gloo.py, test/distributed/test_c10d_ucc.py (test_save_load_checkpoint): variant 1. Serialize the checkpoint into an io.BytesIO buffer on rank 0 and broadcast the bytes via broadcast_object_list, removing the shared fixed-name file instead of only randomizing it.
  • torch/testing/_internal/distributed/checkpoint_utils.py (with_temp_dir): variant 2, with the widest blast radius since every DCP test uses it. DCP genuinely needs a shared on-disk directory, so this cannot be fixed by broadcasting bytes; it gets a dist.barrier() in the finally, ahead of rank 0's rmtree. The barrier has to be on the failure path too: a rank whose body raised would otherwise skip it and leave every rank that passed blocked until the process group times out, which both costs TIMEOUT_DEFAULT and replaces the real failure with a timeout.
  • test/distributed/checkpoint/test_fsspec.py: this file carried its own verbatim copy of the buggy with_temp_dir instead of importing the shared helper, so fixing the helper alone would have left this file's DCP tests still racy. Delete the local copy and import the fixed helper from checkpoint_utils instead.
  • test/distributed/checkpoint/test_file_system_checkpoint.py (test_load_rowwise_to_colwise): variant 3. Rank 0 does shutil.rmtree(path); os.makedirs(path) with no barrier before all ranks enter save_state_dict, so a peer's fs.mkdir can recreate the directory in between and rank 0's os.makedirs raises FileExistsError. Add the missing dist.barrier(), matching the sibling test test_load_with_different_shard_plan in the same file, which already has it.

Reproduction

Delete-under-you (with_temp_dir)

On main, add a 3s delay on non-zero ranks after the temp dir is broadcast and before the test body runs, standing in for real rank skew (same technique as pytorch#194614):

            self.temp_dir = object_list[0]
            os.sync()
            if dist.get_rank() != 0:
                time.sleep(3)

Then run a DCP test that uses the helper:

python test/distributed/checkpoint/test_file_system_checkpoint.py -v \
  -k test_read_write_shard_tensor

Without the changes, rank 0 removes the directory while rank 1 is still reading it:

rank 0: OK
[rank1]: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpmwz8mu28/shard_0'

With the dist.barrier() added, the same delayed run passes on both ranks.

Fixed-name collision (test_save_load_checkpoint)

On main, the test shares a hardcoded path across ranks:

checkpoint_path = tempfile.gettempdir() + "/model.checkpoint"
if self.rank == 0:
    torch.save(ddp_withload.state_dict(), checkpoint_path)
dist.barrier()
map_location = {"cuda:0": f"cuda:{self.rank:d}"}
ddp_state_dict = torch.load(checkpoint_path, map_location=map_location)

Reproduce the collision by running torch.save and torch.load against that same path concurrently from two processes, which is what two test runs on one host do:

reader: 1 clean loads, errors: {'RuntimeError': 112565, 'EOFError': 177231, 'OSError': 300, 'UnpicklingError': 295}

This matches the _pickle.UnpicklingError signature from pytorch#84886. With the io.BytesIO + broadcast_object_list change, no shared path exists for concurrent runs to collide on.

Barrier placement in with_temp_dir

On a 2-rank gloo group whose with_temp_dir body raises on rank 1 only, with the peer process kept alive after the raise so it mirrors MultiProcContinuousTest._worker_loop (with_temp_dir is applied to those bases at test_2d_composability.py:913 and test_pp_composability.py:162). At a 20s process group timeout:

variant rank 0 rank 1
main 0.0s, OK 1.0s, AssertionError: rank 1 only failure

Only the finally placement both reports the real failure and closes the delete-under-you window on the failure path, where a spurious FileNotFoundError would otherwise mask the real error.

Developed with AI assistance; I reviewed the result. Pull Request resolved: pytorch#196591 Approved by: https://github.com/jeffdaily

(cherry picked from commit b9f83ac)

…ytorch#196591)

Follow-up to pytorch#194614. That PR fixed a checkpoint reload race in post-local SGD tests but noted in review ([comment](pytorch#194614 (comment))) that the same bug shapes exist in several other places. This PR fixes those remaining sites.

## Root cause

Three related races, all stemming from sharing a checkpoint through the filesystem across ranks instead of through a collective:

1. **Fixed-name collision:** a checkpoint path is built from a hardcoded name under the shared temp dir (e.g. `tempfile.gettempdir() + "/model.checkpoint"`). Two test processes running concurrently on the same host can collide on that name, so one run's rank 0 can overwrite the file while another run's rank 1 is loading it, producing `_pickle.UnpicklingError`/`EOFError` (`torch.save` is not atomic).
2. **Delete-under-you:** a directory or file is created by rank 0 and read by all ranks, then removed with no `dist.barrier()` between the last read and the removal. Whichever rank finishes first can delete the path while a peer hasn't opened it yet, producing `FileNotFoundError`.
3. **Recreate-under-you:** rank 0 does `shutil.rmtree(path)` then `os.makedirs(path)` with no barrier before the peers enter `save_state_dict`. The data writes cannot interleave here: every rank's `prepare_local_plan` calls `fs.mkdir(path, exist_ok=True)`, that runs inside the `"plan"` reduce_scatter, and the writes only happen after it. What a peer does land in that window is the `fs.mkdir`, recreating the directory between rank 0's `rmtree` and its `os.makedirs`. That `os.makedirs` has no `exist_ok=True`, so rank 0 raises `FileExistsError`.

## Fix

- `test/distributed/test_c10d_gloo.py`, `test/distributed/test_c10d_ucc.py` (`test_save_load_checkpoint`): variant 1. Serialize the checkpoint into an `io.BytesIO` buffer on rank 0 and broadcast the bytes via `broadcast_object_list`, removing the shared fixed-name file instead of only randomizing it.
- `torch/testing/_internal/distributed/checkpoint_utils.py` (`with_temp_dir`): variant 2, with the widest blast radius since every DCP test uses it. DCP genuinely needs a shared on-disk directory, so this cannot be fixed by broadcasting bytes; it gets a `dist.barrier()` in the `finally`, ahead of rank 0's `rmtree`. The barrier has to be on the failure path too: a rank whose body raised would otherwise skip it and leave every rank that passed blocked until the process group times out, which both costs `TIMEOUT_DEFAULT` and replaces the real failure with a timeout.
- `test/distributed/checkpoint/test_fsspec.py`: this file carried its own verbatim copy of the buggy `with_temp_dir` instead of importing the shared helper, so fixing the helper alone would have left this file's DCP tests still racy. Delete the local copy and import the fixed helper from `checkpoint_utils` instead.
- `test/distributed/checkpoint/test_file_system_checkpoint.py` (`test_load_rowwise_to_colwise`): variant 3. Rank 0 does `shutil.rmtree(path); os.makedirs(path)` with no barrier before all ranks enter `save_state_dict`, so a peer's `fs.mkdir` can recreate the directory in between and rank 0's `os.makedirs` raises `FileExistsError`. Add the missing `dist.barrier()`, matching the sibling test `test_load_with_different_shard_plan` in the same file, which already has it.

## Reproduction

### Delete-under-you (`with_temp_dir`)

On `main`, add a 3s delay on non-zero ranks after the temp dir is broadcast and before the test body runs, standing in for real rank skew (same technique as pytorch#194614):

```python
            self.temp_dir = object_list[0]
            os.sync()
            if dist.get_rank() != 0:
                time.sleep(3)
```

Then run a DCP test that uses the helper:

```
python test/distributed/checkpoint/test_file_system_checkpoint.py -v \
  -k test_read_write_shard_tensor
```

Without the changes, rank 0 removes the directory while rank 1 is still reading it:

```
rank 0: OK
[rank1]: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpmwz8mu28/shard_0'
```

With the `dist.barrier()` added, the same delayed run passes on both ranks.

### Fixed-name collision (`test_save_load_checkpoint`)

On `main`, the test shares a hardcoded path across ranks:

```python
checkpoint_path = tempfile.gettempdir() + "/model.checkpoint"
if self.rank == 0:
    torch.save(ddp_withload.state_dict(), checkpoint_path)
dist.barrier()
map_location = {"cuda:0": f"cuda:{self.rank:d}"}
ddp_state_dict = torch.load(checkpoint_path, map_location=map_location)
```

Reproduce the collision by running `torch.save` and `torch.load` against that same path concurrently from two processes, which is what two test runs on one host do:

```
reader: 1 clean loads, errors: {'RuntimeError': 112565, 'EOFError': 177231, 'OSError': 300, 'UnpicklingError': 295}
```

This matches the `_pickle.UnpicklingError` signature from pytorch#84886. With the `io.BytesIO` + `broadcast_object_list` change, no shared path exists for concurrent runs to collide on.

### Barrier placement in `with_temp_dir`

On a 2-rank gloo group whose `with_temp_dir` body raises on rank 1 only, with the peer process kept alive after the raise so it mirrors `MultiProcContinuousTest._worker_loop` (`with_temp_dir` is applied to those bases at `test_2d_composability.py:913` and `test_pp_composability.py:162`). At a 20s process group timeout:

| variant | rank 0 | rank 1 |
| --- | --- | --- |
| `main` | 0.0s, OK | 1.0s, `AssertionError: rank 1 only failure` |
| barrier on success path | 20.3s, `RuntimeError: gloo connection ...` | 1.0s, `AssertionError: rank 1 only failure` |
| barrier in `finally` | 1.3s, OK | 1.3s, `AssertionError: rank 1 only failure` |

Only the `finally` placement both reports the real failure and closes the delete-under-you window on the failure path, where a spurious `FileNotFoundError` would otherwise mask the real error.

Developed with AI assistance; I reviewed the result.
Pull Request resolved: pytorch#196591
Approved by: https://github.com/jeffdaily

(cherry picked from commit b9f83ac)
@albmalamd
albmalamd requested a review from pragupta September 17, 2026 13:03
@albmalamd albmalamd changed the title Fix remaining checkpoint filesystem races flagged in #194614 (#196591) [release/2.13] Fix remaining checkpoint filesystem races flagged in #194614 (#196591) Sep 17, 2026
@pragupta
pragupta merged commit acb548c into release/2.13 Sep 21, 2026
3 checks passed
@pragupta
pragupta deleted the albmalamd/cherry-pick/2.13/fix_post_localSGD_optimizer_step_reload branch September 21, 2026 15:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants