Skip to content

Fix remaining checkpoint filesystem races flagged in #194614 - #196591

Closed
albmalamd wants to merge 2 commits into
pytorch:mainfrom
ROCm:albmalamd/fix_post_localSGD_optimizer_step_reload
Closed

albmalamd wants to merge 2 commits into
pytorch:mainfrom
ROCm:albmalamd/fix_post_localSGD_optimizer_step_reload

Conversation

@albmalamd

@albmalamd albmalamd commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #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 #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 #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.

@pytorch-bot

pytorch-bot Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196591

Note: Links to docs will display an error until the docs builds have been completed.

⏳ No Failures, 1 Pending

As of commit 2964d98 with merge base 0899f1f (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@linux-foundation-easycla

linux-foundation-easycla Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: albmalamd / name: Albert Malewski (5221b1d)

@jithunnair-amd jithunnair-amd added ciflow/trunk Trigger trunk jobs on your pull request ciflow/periodic-rocm-mi350 Trigger "distributed_4gpu" config (only runs distributed tests that need >2GPUs) CI on ROCm MI350 ciflow/periodic-rocm-mi300 Trigger "distributed" config CI on ROCm MI300/MI325 ciflow/periodic-rocm-mi200 Trigger "distributed" config CI on ROCm MI200 labels Sep 10, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 10, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/periodic-rocm-mi350.
Currently recognized labels are

  • ciflow/b200
  • ciflow/b200-distributed
  • ciflow/b200-symm-mem
  • ciflow/binaries
  • ciflow/binaries_libtorch
  • ciflow/binaries_wheel
  • ciflow/docker
  • ciflow/dtensor
  • ciflow/h100
  • ciflow/h100-cutlass-backend
  • ciflow/h100-distributed
  • ciflow/h100-symm-mem
  • ciflow/inductor
  • ciflow/inductor-cu126
  • ciflow/inductor-micro-benchmark
  • ciflow/inductor-micro-benchmark-cpu-x86
  • ciflow/inductor-pallas
  • ciflow/inductor-perf-compare
  • ciflow/inductor-perf-test-nightly-rocm-mi300
  • ciflow/inductor-perf-test-nightly-rocm-mi350
  • ciflow/inductor-perf-test-nightly-x86-zen
  • ciflow/inductor-perf-test-nightly-xpu
  • ciflow/inductor-periodic
  • ciflow/inductor-rocm-mi200
  • ciflow/inductor-rocm-mi300
  • ciflow/mps
  • ciflow/native-aot
  • ciflow/nightly
  • ciflow/op-benchmark
  • ciflow/periodic
  • ciflow/periodic-rocm-mi200
  • ciflow/periodic-rocm-mi300
  • ciflow/periodic-strict
  • ciflow/pull
  • ciflow/riscv64
  • ciflow/rocm-mi200
  • ciflow/rocm-mi300
  • ciflow/rocm-navi31
  • ciflow/rocm-nightly
  • ciflow/rocm-preview
  • ciflow/s390
  • ciflow/slow
  • ciflow/slow-rocm-mi200
  • ciflow/torchtitan
  • ciflow/triton_binaries
  • ciflow/trunk
  • ciflow/tsan
  • ciflow/unstable
  • ciflow/win-arm64
  • ciflow/xpu

Please add the new label to .github/pytorch-probot.yml

@albmalamd
albmalamd force-pushed the albmalamd/fix_post_localSGD_optimizer_step_reload branch from 98c5978 to 5221b1d Compare September 11, 2026 13:23
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

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

@albmalamd
albmalamd marked this pull request as ready for review September 14, 2026 17:03

@jeffdaily jeffdaily left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The with_temp_dir change needs its barrier in the finally, not after a successful body. The comment argues the success-path placement avoids turning a single-rank failure into a hang, but it produces exactly that: the rank that raises skips the barrier and exits, leaving every rank that passed blocked in a barrier no one will ever join. A finally is reached by every rank that unwinds normally, so a one-rank assertion still rendezvouses there.

Measured with a 2-rank gloo MultiProcContinuousTest whose with_temp_dir body raises on rank 1 only, at DISTRIBUTED_TESTS_DEFAULT_TIMEOUT=45:

variant wall reported error
main 11.0s AssertionError: rank 1 only failure
this PR 58.7s RuntimeError: Process timed out after 55.05s
barrier in finally 6.3s AssertionError: rank 1 only failure

TIMEOUT_DEFAULT is 300s in CI, so each occurrence costs that and replaces the real failure with a timeout. It bites hardest on the MultiProcContinuousTest bases, where _worker_loop keeps the worker and the process group alive after a test raises, so nothing reaps the blocked peers; with_temp_dir is applied on those at test_2d_composability.py:913 (TestNew2dParallelStateDict) and test_pp_composability.py:162. The plain MultiProcessTestCase sites escape only because _join_processes polls at 100ms and terminates the peers on TEST_ERROR_EXIT_CODE.

The success-path placement also leaves the delete-under-you race open on the failure path, where rank 0 can rmtree while a peer is still mid-read, which is exactly where a spurious FileNotFoundError would mask the real error.

         try:
             func(self, *args, **kwargs)
-            # Every rank reads from the directory rank 0 created, so it must not be
-            # removed until all of them are done. Only synchronize on the success
-            # path: if the body raised, a peer may never reach this point and
-            # blocking here would turn a single-rank failure into a hang.
+        finally:
+            # Every rank reads the directory rank 0 created, so rank 0 must not
+            # remove it until the others are done. This has to run on the failure
+            # path too, or a rank whose body raised leaves its peers blocked here
+            # until the process group times out.
             if dist.is_initialized():
                 dist.barrier()
-        finally:
             if not dist.is_initialized() or dist.get_rank() == 0:
                 shutil.rmtree(self.temp_dir, ignore_errors=True)

No try/except is needed around the barrier: if it fails while an exception is propagating, Python attaches the original as __context__ and the traceback still prints it. With that change test/distributed/checkpoint/test_fsspec.py and test_file_system_checkpoint.py pass for me on 2 GPUs (4 tests in 18.0s, 9 tests in 61.2s).

Second, the root cause given for test_load_rowwise_to_colwise is not what happens. Writes cannot interleave there: every rank's prepare_local_plan calls fs.mkdir(path, exist_ok=True) before the "plan" reduce_scatter, and the data writes happen after it. What a peer does in that window is recreate the directory between rank 0's shutil.rmtree and its os.makedirs(path), and that os.makedirs has no exist_ok=True, so rank 0 raises FileExistsError. The barrier is still the right fix; please correct the description.

Minor: the commit message has no blank line after the subject, so the entire body is one 3500-character subject line.

Drafted with AI assistance and reviewed by me before posting.

Follow-up to pytorch#194614. That PR fixed a checkpoint reload race in
post-local SGD tests but noted in review
(pytorch#194614 (comment))
that the same two bug shapes exist in several other places. This PR
fixes those remaining sites.
Two related races, both 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`.
- `test/distributed/test_c10d_gloo.py`,
  `test/distributed/test_c10d_ucc.py` (`test_save_load_checkpoint`):
  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`): DCP genuinely needs a shared on-disk directory, so
  this can't be fixed by broadcasting bytes. Add a `dist.barrier()`
  after the test body succeeds and before rank 0 removes the directory,
  so no rank can delete out from under a peer still reading. The
  barrier is only on the success path (not in `finally`), so a raise on
  one rank doesn't hang the others waiting on a barrier that will never
  be reached.
- `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`): rank 0 does
  `shutil.rmtree(path); os.makedirs(path)` with no barrier before all
  ranks enter `save_state_dict`, so a peer can start writing into a
  directory rank 0 is mid-recreation of. Add the missing
  `dist.barrier()`, matching the sibling test
  `test_load_with_different_shard_plan` in the same file, which already
  has it.
`with_temp_dir` delete-under-you race, reproduced with gloo/CPU and a
3s delay on the non-zero rank standing in for real rank skew (same
technique as pytorch#194614):
    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, reproduced by concurrently running `torch.save`
and `torch.load` against the same hardcoded path from two processes:
    reader: 1 clean loads, errors: {'RuntimeError': 112565, 'EOFError': 177231, 'OSError': 300, 'UnpicklingError': 295}
matching 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.

Developed with AI assistance, I reviewed the result.
@albmalamd
albmalamd force-pushed the albmalamd/fix_post_localSGD_optimizer_step_reload branch from 5221b1d to 2964d98 Compare September 16, 2026 21:00
@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

pragupta pushed a commit to ROCm/pytorch that referenced this pull request Sep 21, 2026
…ytorch#194614 (pytorch#196591) (#3660)

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)
pragupta pushed a commit to ROCm/pytorch that referenced this pull request Sep 21, 2026
…ytorch#194614 (pytorch#196591) (#3659)

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)
pragupta pushed a commit to ROCm/pytorch that referenced this pull request Sep 21, 2026
…ytorch#194614 (pytorch#196591) (#3658)

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/periodic-rocm-mi200 Trigger "distributed" config CI on ROCm MI200 ciflow/periodic-rocm-mi300 Trigger "distributed" config CI on ROCm MI300/MI325 ciflow/periodic-rocm-mi350 Trigger "distributed_4gpu" config (only runs distributed tests that need >2GPUs) CI on ROCm MI350 ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: distributed (c10d) release notes category release notes: distributed (checkpoint)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants