Repository navigation
Conversation
🔗 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 ( 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. |
This comment was marked as resolved.
This comment was marked as resolved.
|
@pytorchbot label "topic: not user facing" |
|
@janeyx99 any idea who should look at this? |
|
@pragupta why did you add ciflow/trunk? |
jeffdaily
left a comment
There was a problem hiding this comment.
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:
-
Worth adding the reproduction and these commands to the PR description, since a flaky-test fix is hard to review without them.
-
_test_hook_picklingin the same file still shares a checkpoint throughtempfile.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_filewas 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. Theio.BytesIO+broadcast_object_listchange applies there verbatim if you want to fold it in.
Drafted with AI assistance and reviewed by me before posting.
I can answer the why since it is our CI. On a ROCm change the reason to reach for There is no narrower label to use instead. 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 Drafted with AI assistance and reviewed by me before posting. |
|
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. |
5bfff91 to
e37dcaa
Compare
|
|
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.
e37dcaa to
6af1bcd
Compare
This comment was marked as resolved.
This comment was marked as resolved.
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 I reproduced it with no GPU at all -- gloo, CPU tensors, a verbatim copy of Provenance also points away from ROCm. #84886 was originally filed with The test also runs on NVIDIA in this same workflow ( One merge note: pytorch-bot reopened #84886 earlier today with Drafted with AI assistance and reviewed by me before posting. |
|
@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.
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
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. Drafted with AI assistance and reviewed by me before posting. |
|
@pytorchbot merge |
Merge startedYour 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 |
) (#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.
Cherry-pick of #3600 Co-authored-by: albmalamd <[email protected]>
Cherry-pick of #3600 Co-authored-by: albmalamd <[email protected]>
## 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
## 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
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.
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.
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
…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)
…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)
…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)
) (#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]>
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-savedist.barrier()andtorch.loadin_test_post_localSGD_optimizer_step_reload:And then execute the test:
Without the changes, the test returns: