Skip to content

Fix post-local SGD checkpoint reload race - #194614

Closed
albmalamd wants to merge 1 commit into
pytorch:mainfrom
albmalamd:fix_post_localSGD_optimizer_step_reload
Closed

albmalamd wants to merge 1 commit into
pytorch:mainfrom
albmalamd:fix_post_localSGD_optimizer_step_reload

Conversation

@albmalamd

@albmalamd albmalamd commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #84886.

There was a race in the post-local SGD checkpoint reload test. Rank 0 created the temporary checkpoint and all ranks synchronized after it was written. However, there was no synchronization after loading. Rank 0 could complete the test first, leave the temporary-file context, and delete the checkpoint before another rank opened it, causing FileNotFoundError.

Serialize the checkpoint into an in-memory buffer on rank 0 and broadcast the bytes through the process group. Each rank then loads from its own BytesIO buffer.

This removes the rank-0-owned file and its lifetime race instead of adding another barrier around temporary-file cleanup. It also removes the unnecessary shared-filesystem dependency while preserving coverage of serialization, device remapping, optimizer state restoration, and the missing-step fallback.

The same changes applied to test_ddp_hook_pickling_powerSGD and unskipped the test.

Reproduction

On main, add a 3s delay on non-zero ranks between the post-save dist.barrier() and torch.load in _test_post_localSGD_optimizer_step_reload:

            dist.barrier()
            if self.rank != 0:
                time.sleep(3)
            map_location = {"cuda:0": f"cuda:{self.rank:d}"}
            checkpoint = torch.load(chkpt_file, map_location=map_location)

And then execute the test:

BACKEND=nccl WORLD_SIZE=2 TEMP_DIR=/tmp/dist python test/distributed/test_distributed_spawn.py -v \
  TestDistBackendWithSpawn.test_post_localSGD_optimizer_step_reload

Without the changes, the test returns:

FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmptsfocehr'

@pytorch-bot

pytorch-bot Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit 6af1bcd with merge base a0edfca (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@jithunnair-amd jithunnair-amd added 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 Aug 24, 2026
@pytorch-bot

This comment was marked as resolved.

@albmalamd

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Aug 24, 2026
@soulitzer

Copy link
Copy Markdown
Contributor

@janeyx99 any idea who should look at this?

@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 26, 2026
@pragupta pragupta added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 26, 2026
@janeyx99

Copy link
Copy Markdown
Contributor

@pragupta why did you add ciflow/trunk?

@janeyx99
janeyx99 requested a review from wconstab August 26, 2026 15:57

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

LGTM. I reproduced the race locally before approving: on main, injecting a 3s delay on non-zero ranks between the dist.barrier() and the torch.load gives exactly the reported failure, and the same injected delay on this branch passes, so this closes the window rather than narrowing it.

# main + injected delay on ranks != 0
BACKEND=nccl WORLD_SIZE=2 TEMP_DIR=/tmp/dist python test/distributed/test_distributed_spawn.py -v \
  TestDistBackendWithSpawn.test_post_localSGD_optimizer_step_reload
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmptsfocehr'

# this branch, unmodified, 4x gfx90a / NCCL
BACKEND=nccl WORLD_SIZE=2 TEMP_DIR=/tmp/dist python test/distributed/test_distributed_spawn.py -v -k post_localSGD
Ran 6 tests ... OK (skipped=2)
BACKEND=nccl WORLD_SIZE=4 TEMP_DIR=/tmp/dist python test/distributed/test_distributed_spawn.py -v -k post_localSGD
Ran 6 tests ... OK

Two non-blocking asks:

  1. Worth adding the reproduction and these commands to the PR description, since a flaky-test fix is hard to review without them.

  2. _test_hook_pickling in the same file still shares a checkpoint through tempfile.gettempdir() + "/checkpoint.pt" with the same rank-0-save / barrier / all-ranks-load shape, and the fixed name is the original complaint in #84886. _rank_temp_file was added in 54e03cd to fix that class of bug but only ever got applied to the test you are touching (and that same commit dropped the trailing barrier, which is how the race here got introduced). Deleting the helper leaves the fixed-name version as the only remaining idiom in the file. The io.BytesIO + broadcast_object_list change applies there verbatim if you want to fold it in.

Drafted with AI assistance and reviewed by me before posting.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@janeyx99

why did you add ciflow/trunk?

I can answer the why since it is our CI. On a ROCm change the reason to reach for ciflow/trunk is MI350 coverage: linux-jammy-rocm-py3.10-mi350 (gfx950) is defined directly in trunk.yml, and that is the only place it exists, so ciflow/trunk is currently the only way to get default + inductor + distributed on that arch from a PR.

There is no narrower label to use instead. rocm-mi350.yml, inductor-rocm-mi350.yml, and periodic-rocm-mi350.yml are all still in the tree but every auto-trigger in them is commented out, with the header:

# Unneeded for CI: trunk.yml covers the same ROCm testing.
# Kept in-repo for metrics; auto-triggers below are commented out.
# workflow_dispatch remains for manual runs.

So this was trunk-or-nothing for MI350, not a deliberate ask for the full trunk matrix.

To be clear though, we do not want a dedicated pre-trunk MI350 label either. MI350 capacity is limited, and a label that runs the gfx950 matrix before merge followed by ciflow/trunk running the identical matrix again would consume that scarce capacity twice for no extra signal. That overlap is presumably why the standalone MI350 workflows were folded into trunk in the first place. Paying for the rest of the trunk matrix to get MI350 once is the better trade.

Drafted with AI assistance and reviewed by me before posting.

@jeffdaily jeffdaily removed the ciflow/periodic-rocm-mi350 Trigger "distributed_4gpu" config (only runs distributed tests that need >2GPUs) CI on ROCm MI350 label Aug 26, 2026
@janeyx99

Copy link
Copy Markdown
Contributor

Oh I see, it would be good to define the problem and where it was hit. I see this is ROCm CI related which I couldn't tell before from the PR description.

@albmalamd
albmalamd force-pushed the fix_post_localSGD_optimizer_step_reload branch from 5bfff91 to e37dcaa Compare August 27, 2026 14:57
@pytorch-bot

pytorch-bot Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

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

There was a race in the post-local SGD checkpoint reload test. Rank 0 created the temporary checkpoint and all ranks synchronized after it was written. However, there was no synchronization after loading. Rank 0 could complete the test first, leave the temporary-file context, and delete the checkpoint before another rank opened it, causing FileNotFoundError.

Serialize the checkpoint into an in-memory buffer on rank 0 and broadcast the bytes through the process group. Each rank then loads from its own BytesIO buffer.

This removes the rank-0-owned file and its lifetime race instead of adding another barrier around temporary-file cleanup. It also removes the unnecessary shared-filesystem dependency while preserving coverage of serialization, device remapping, optimizer state restoration, and the missing-step fallback.
@albmalamd
albmalamd force-pushed the fix_post_localSGD_optimizer_step_reload branch from e37dcaa to 6af1bcd Compare August 27, 2026 14:58
@jithunnair-amd jithunnair-amd added the ciflow/periodic-rocm-mi350 Trigger "distributed_4gpu" config (only runs distributed tests that need >2GPUs) CI on ROCm MI350 label Aug 27, 2026
@pytorch-bot

This comment was marked as resolved.

@jeffdaily jeffdaily removed the ciflow/periodic-rocm-mi350 Trigger "distributed_4gpu" config (only runs distributed tests that need >2GPUs) CI on ROCm MI350 label Aug 27, 2026
@jeffdaily

Copy link
Copy Markdown
Collaborator

@janeyx99

Oh I see, it would be good to define the problem and where it was hit. I see this is ROCm CI related which I couldn't tell before from the PR description.

To be clear on scope: the sightings are on ROCm CI, but the bug is not ROCm-specific. It is a plain lifetime race in _rank_temp_file + _test_post_localSGD_optimizer_step_reload: rank 0 removes the checkpoint on context-manager exit with no barrier after the load, so it can delete the file while a peer has not opened it yet. torch.save/torch.load/os.remove are host-side and barrier is the same c10d path on either backend.

I reproduced it with no GPU at all -- gloo, CPU tensors, a verbatim copy of _rank_temp_file, and a 3s delay on rank 1 standing in for real rank skew:

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

Provenance also points away from ROCm. #84886 was originally filed with Platforms: linux in 2022 with the same FileNotFoundError; rocm was only appended by pytorch-bot on 2026-07-21. The fix for it, #84952, randomized the filename but in the same commit deleted the trailing dist.barrier() before the rank-0 os.remove, which is what opened the current window. And the sibling test with the identical save/barrier/load/remove shape, test_ddp_hook_pickling_powerSGD, was blanket-skipped as flaky by #117804, a CUDA-side c10d change.

The test also runs on NVIDIA in this same workflow (linux-jammy-cuda13.0-py3.10-gcc11 / test (distributed, 1..10, linux.g4dn.12xlarge.nvidia.gpu)), so this is shared code, not a ROCm path. My read on why ROCm sees it more is window width, not mechanism: the mi350 distributed shards are 2-GPU containers on shared hosts and produce more post-barrier skew.

One merge note: pytorch-bot reopened #84886 earlier today with Platforms: linux, rocm. Because check_if_enable maps linux to IS_LINUX, that disables the test on all Linux right now, so PR CI will skip it rather than exercise the fix. #84886 should be closed once this lands.

Drafted with AI assistance and reviewed by me before posting.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@albmalamd Two more instances of this same shape exist outside the file you are touching. Noting them here for the record rather than asking you to expand the PR.

test_save_load_checkpoint in test/distributed/test_c10d_gloo.py and test/distributed/test_c10d_ucc.py still share a fixed 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)

The file is never removed, so this is not the delete-under-you race you fixed. It is the other half of the original #84886 complaint: a fixed name under the shared temp dir means two test processes on the same host collide, and one run's rank 0 can overwrite the checkpoint while another run's rank 1 is loading it. That is the _pickle.UnpicklingError signature in that issue. The io.BytesIO + broadcast_object_list change applies here verbatim too.

with_temp_dir in torch/testing/_internal/distributed/checkpoint_utils.py is structurally the same bug as _rank_temp_file, with a wider blast radius since the DCP tests all use it:

finally:
    if dist.is_initialized() and dist.get_rank() == 0:
        shutil.rmtree(self.temp_dir, ignore_errors=True)
    else:
        shutil.rmtree(self.temp_dir, ignore_errors=True)

Both branches are identical, so every rank removes the broadcast directory with no barrier first, and whichever rank leaves the test body first deletes it out from under the others. ignore_errors=True swallows the rmtree failure but not the peers' subsequent read failures. This one cannot be fixed by broadcasting bytes since DCP genuinely needs a shared directory on disk; it needs a barrier ahead of the cleanup.

Drafted with AI assistance and reviewed by me before posting.

@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

jeffdaily pushed a commit to ROCm/pytorch that referenced this pull request Aug 28, 2026
) (#3600)

## Summary

Fixes pytorch#84886.

There was a race in the post-local SGD checkpoint reload test. Rank 0
created the temporary checkpoint and all ranks synchronized after it was
written. However, there was no synchronization after loading. Rank 0
could complete the test first, leave the temporary-file context, and
delete the checkpoint before another rank opened it, causing
FileNotFoundError.

Serialize the checkpoint into an in-memory buffer on rank 0 and
broadcast the bytes through the process group. Each rank then loads from
its own BytesIO buffer.

This removes the rank-0-owned file and its lifetime race instead of
adding another barrier around temporary-file cleanup. It also removes
the unnecessary shared-filesystem dependency while preserving coverage
of serialization, device remapping, optimizer state restoration, and the
missing-step fallback.

The same changes applied to test_ddp_hook_pickling_powerSGD and
unskipped the test.

## Reproduction
On `main`, add a 3s delay on non-zero ranks between the post-save
`dist.barrier()` and `torch.load` in
`_test_post_localSGD_optimizer_step_reload`:
```python
            dist.barrier()
            if self.rank != 0:
                time.sleep(3)
            map_location = {"cuda:0": f"cuda:{self.rank:d}"}
            checkpoint = torch.load(chkpt_file, map_location=map_location)
```
And then execute the test:
```
BACKEND=nccl WORLD_SIZE=2 TEMP_DIR=/tmp/dist python test/distributed/test_distributed_spawn.py -v \
  TestDistBackendWithSpawn.test_post_localSGD_optimizer_step_reload
```
Without the changes, the test returns:
```
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmptsfocehr'
```
Pull Request resolved: pytorch#194614
Approved by: https://github.com/jeffdaily

(cherry picked from commit 7658834)

## Motivation

<!-- Explain the purpose of this PR and the goals it aims to achieve.
-->

## Technical Details

<!-- Explain the changes along with any relevant GitHub links. -->

## Test Plan

<!-- Explain any relevant testing done to verify this PR. -->

## Test Result

<!-- Briefly summarize test outcomes. -->

## Submission Checklist

- [ ] Look over the contributing guidelines at
https://github.com/ROCm/ROCm/blob/develop/CONTRIBUTING.md#pull-requests.
rocm-repo-management-api-6 Bot added a commit to ROCm/pytorch that referenced this pull request Aug 29, 2026
rocm-repo-management-api-6 Bot added a commit to ROCm/pytorch that referenced this pull request Aug 29, 2026
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
## Summary

Fixes pytorch#84886.

There was a race in the post-local SGD checkpoint reload test. Rank 0 created the temporary checkpoint and all ranks synchronized after it was written. However, there was no synchronization after loading. Rank 0 could complete the test first, leave the temporary-file context, and delete the checkpoint before another rank opened it, causing FileNotFoundError.

Serialize the checkpoint into an in-memory buffer on rank 0 and broadcast the bytes through the process group. Each rank then loads from its own BytesIO buffer.

This removes the rank-0-owned file and its lifetime race instead of adding another barrier around temporary-file cleanup. It also removes the unnecessary shared-filesystem dependency while preserving coverage of serialization, device remapping, optimizer state restoration, and the missing-step fallback.

The same changes applied to test_ddp_hook_pickling_powerSGD and unskipped the test.

## Reproduction
On `main`, add a 3s delay on non-zero ranks between the post-save `dist.barrier()` and `torch.load` in `_test_post_localSGD_optimizer_step_reload`:
```python
            dist.barrier()
            if self.rank != 0:
                time.sleep(3)
            map_location = {"cuda:0": f"cuda:{self.rank:d}"}
            checkpoint = torch.load(chkpt_file, map_location=map_location)
```
And then execute the test:
```
BACKEND=nccl WORLD_SIZE=2 TEMP_DIR=/tmp/dist python test/distributed/test_distributed_spawn.py -v \
  TestDistBackendWithSpawn.test_post_localSGD_optimizer_step_reload
```
Without the changes, the test returns:
```
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmptsfocehr'
```
Pull Request resolved: pytorch#194614
Approved by: https://github.com/jeffdaily
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
## Summary

Fixes pytorch#84886.

There was a race in the post-local SGD checkpoint reload test. Rank 0 created the temporary checkpoint and all ranks synchronized after it was written. However, there was no synchronization after loading. Rank 0 could complete the test first, leave the temporary-file context, and delete the checkpoint before another rank opened it, causing FileNotFoundError.

Serialize the checkpoint into an in-memory buffer on rank 0 and broadcast the bytes through the process group. Each rank then loads from its own BytesIO buffer.

This removes the rank-0-owned file and its lifetime race instead of adding another barrier around temporary-file cleanup. It also removes the unnecessary shared-filesystem dependency while preserving coverage of serialization, device remapping, optimizer state restoration, and the missing-step fallback.

The same changes applied to test_ddp_hook_pickling_powerSGD and unskipped the test.

## Reproduction
On `main`, add a 3s delay on non-zero ranks between the post-save `dist.barrier()` and `torch.load` in `_test_post_localSGD_optimizer_step_reload`:
```python
            dist.barrier()
            if self.rank != 0:
                time.sleep(3)
            map_location = {"cuda:0": f"cuda:{self.rank:d}"}
            checkpoint = torch.load(chkpt_file, map_location=map_location)
```
And then execute the test:
```
BACKEND=nccl WORLD_SIZE=2 TEMP_DIR=/tmp/dist python test/distributed/test_distributed_spawn.py -v \
  TestDistBackendWithSpawn.test_post_localSGD_optimizer_step_reload
```
Without the changes, the test returns:
```
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmptsfocehr'
```
Pull Request resolved: pytorch#194614
Approved by: https://github.com/jeffdaily
albmalamd added a commit to ROCm/pytorch that referenced this pull request Sep 11, 2026
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 added a commit to ROCm/pytorch that referenced this pull request Sep 16, 2026
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.
pytorchmergebot pushed a commit that referenced this pull request Sep 17, 2026
Follow-up to #194614. That PR fixed a checkpoint reload race in post-local SGD tests but noted in review ([comment](#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 #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 #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: #196591
Approved by: https://github.com/jeffdaily
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)
jeffdaily pushed a commit to ROCm/pytorch that referenced this pull request Nov 23, 2026
) (#4061)

## Summary

Fixes pytorch#84886.

There was a race in the post-local SGD checkpoint reload test. Rank 0 created the temporary checkpoint and all ranks synchronized after it was written. However, there was no synchronization after loading. Rank 0 could complete the test first, leave the temporary-file context, and delete the checkpoint before another rank opened it, causing FileNotFoundError.

Serialize the checkpoint into an in-memory buffer on rank 0 and broadcast the bytes through the process group. Each rank then loads from its own BytesIO buffer.

This removes the rank-0-owned file and its lifetime race instead of adding another barrier around temporary-file cleanup. It also removes the unnecessary shared-filesystem dependency while preserving coverage of serialization, device remapping, optimizer state restoration, and the missing-step fallback.

The same changes applied to test_ddp_hook_pickling_powerSGD and unskipped the test.

## Reproduction
On `main`, add a 3s delay on non-zero ranks between the post-save `dist.barrier()` and `torch.load` in `_test_post_localSGD_optimizer_step_reload`:
```python
            dist.barrier()
            if self.rank != 0:
                time.sleep(3)
            map_location = {"cuda:0": f"cuda:{self.rank:d}"}
            checkpoint = torch.load(chkpt_file, map_location=map_location)
```
And then execute the test:
```
BACKEND=nccl WORLD_SIZE=2 TEMP_DIR=/tmp/dist python test/distributed/test_distributed_spawn.py -v \
  TestDistBackendWithSpawn.test_post_localSGD_optimizer_step_reload
```
Without the changes, the test returns:
```
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmptsfocehr'
```
Pull Request resolved: pytorch#194614
Approved by: https://github.com/jeffdaily

(cherry picked from commit 7658834)
Co-authored-by: Cursor <[email protected]>
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/trunk Trigger trunk jobs on your pull request Merged open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DISABLED test_post_localSGD_optimizer_step_reload (__main__.TestDistBackendWithSpawn)

8 participants