Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196591
Note: Links to docs will display an error until the docs builds have been completed. ⏳ No Failures, 1 PendingAs of commit 2964d98 with merge base 0899f1f ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
98c5978 to
5221b1d
Compare
|
|
jeffdaily
left a comment
There was a problem hiding this comment.
The with_temp_dir change needs its barrier in the finally, not after a successful body. The comment argues the success-path placement avoids turning a single-rank failure into a hang, but it produces exactly that: the rank that raises skips the barrier and exits, leaving every rank that passed blocked in a barrier no one will ever join. A finally is reached by every rank that unwinds normally, so a one-rank assertion still rendezvouses there.
Measured with a 2-rank gloo MultiProcContinuousTest whose with_temp_dir body raises on rank 1 only, at DISTRIBUTED_TESTS_DEFAULT_TIMEOUT=45:
| variant | wall | reported error |
|---|---|---|
| main | 11.0s | AssertionError: rank 1 only failure |
| this PR | 58.7s | RuntimeError: Process timed out after 55.05s |
barrier in finally |
6.3s | AssertionError: rank 1 only failure |
TIMEOUT_DEFAULT is 300s in CI, so each occurrence costs that and replaces the real failure with a timeout. It bites hardest on the MultiProcContinuousTest bases, where _worker_loop keeps the worker and the process group alive after a test raises, so nothing reaps the blocked peers; with_temp_dir is applied on those at test_2d_composability.py:913 (TestNew2dParallelStateDict) and test_pp_composability.py:162. The plain MultiProcessTestCase sites escape only because _join_processes polls at 100ms and terminates the peers on TEST_ERROR_EXIT_CODE.
The success-path placement also leaves the delete-under-you race open on the failure path, where rank 0 can rmtree while a peer is still mid-read, which is exactly where a spurious FileNotFoundError would mask the real error.
try:
func(self, *args, **kwargs)
- # Every rank reads from the directory rank 0 created, so it must not be
- # removed until all of them are done. Only synchronize on the success
- # path: if the body raised, a peer may never reach this point and
- # blocking here would turn a single-rank failure into a hang.
+ finally:
+ # Every rank reads the directory rank 0 created, so rank 0 must not
+ # remove it until the others are done. This has to run on the failure
+ # path too, or a rank whose body raised leaves its peers blocked here
+ # until the process group times out.
if dist.is_initialized():
dist.barrier()
- finally:
if not dist.is_initialized() or dist.get_rank() == 0:
shutil.rmtree(self.temp_dir, ignore_errors=True)No try/except is needed around the barrier: if it fails while an exception is propagating, Python attaches the original as __context__ and the traceback still prints it. With that change test/distributed/checkpoint/test_fsspec.py and test_file_system_checkpoint.py pass for me on 2 GPUs (4 tests in 18.0s, 9 tests in 61.2s).
Second, the root cause given for test_load_rowwise_to_colwise is not what happens. Writes cannot interleave there: every rank's prepare_local_plan calls fs.mkdir(path, exist_ok=True) before the "plan" reduce_scatter, and the data writes happen after it. What a peer does in that window is recreate the directory between rank 0's shutil.rmtree and its os.makedirs(path), and that os.makedirs has no exist_ok=True, so rank 0 raises FileExistsError. The barrier is still the right fix; please correct the description.
Minor: the commit message has no blank line after the subject, so the entire body is one 3500-character subject line.
Drafted with AI assistance and reviewed by me before posting.
Follow-up to pytorch#194614. That PR fixed a checkpoint reload race in post-local SGD tests but noted in review (pytorch#194614 (comment)) that the same two bug shapes exist in several other places. This PR fixes those remaining sites. Two related races, both stemming from sharing a checkpoint through the filesystem across ranks instead of through a collective: 1. Fixed-name collision: a checkpoint path is built from a hardcoded name under the shared temp dir (e.g. `tempfile.gettempdir() + "/model.checkpoint"`). Two test processes running concurrently on the same host can collide on that name, so one run's rank 0 can overwrite the file while another run's rank 1 is loading it, producing `_pickle.UnpicklingError`/`EOFError` (torch.save is not atomic). 2. Delete-under-you: a directory or file is created by rank 0 and read by all ranks, then removed with no `dist.barrier()` between the last read and the removal. Whichever rank finishes first can delete the path while a peer hasn't opened it yet, producing `FileNotFoundError`. - `test/distributed/test_c10d_gloo.py`, `test/distributed/test_c10d_ucc.py` (`test_save_load_checkpoint`): serialize the checkpoint into an `io.BytesIO` buffer on rank 0 and broadcast the bytes via `broadcast_object_list`, removing the shared fixed-name file instead of only randomizing it. - `torch/testing/_internal/distributed/checkpoint_utils.py` (`with_temp_dir`): DCP genuinely needs a shared on-disk directory, so this can't be fixed by broadcasting bytes. Add a `dist.barrier()` after the test body succeeds and before rank 0 removes the directory, so no rank can delete out from under a peer still reading. The barrier is only on the success path (not in `finally`), so a raise on one rank doesn't hang the others waiting on a barrier that will never be reached. - `test/distributed/checkpoint/test_fsspec.py`: this file carried its own verbatim copy of the buggy `with_temp_dir` instead of importing the shared helper, so fixing the helper alone would have left this file's DCP tests still racy. Delete the local copy and import the fixed helper from `checkpoint_utils` instead. - `test/distributed/checkpoint/test_file_system_checkpoint.py` (`test_load_rowwise_to_colwise`): rank 0 does `shutil.rmtree(path); os.makedirs(path)` with no barrier before all ranks enter `save_state_dict`, so a peer can start writing into a directory rank 0 is mid-recreation of. Add the missing `dist.barrier()`, matching the sibling test `test_load_with_different_shard_plan` in the same file, which already has it. `with_temp_dir` delete-under-you race, reproduced with gloo/CPU and a 3s delay on the non-zero rank standing in for real rank skew (same technique as pytorch#194614): rank 0: OK [rank1]: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpmwz8mu28/shard_0' With the `dist.barrier()` added, the same delayed run passes on both ranks. Fixed-name collision, reproduced by concurrently running `torch.save` and `torch.load` against the same hardcoded path from two processes: reader: 1 clean loads, errors: {'RuntimeError': 112565, 'EOFError': 177231, 'OSError': 300, 'UnpicklingError': 295} matching the `_pickle.UnpicklingError` signature from pytorch#84886. With the `io.BytesIO` + `broadcast_object_list` change, no shared path exists for concurrent runs to collide on. Developed with AI assistance, I reviewed the result.
5221b1d to
2964d98
Compare
|
@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 |
…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)
Follow-up to #194614. That PR fixed a checkpoint reload race in post-local SGD tests but noted in review (comment) that the same bug shapes exist in several other places. This PR fixes those remaining sites.
Root cause
Three related races, all stemming from sharing a checkpoint through the filesystem across ranks instead of through a collective:
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.saveis not atomic).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, producingFileNotFoundError.shutil.rmtree(path)thenos.makedirs(path)with no barrier before the peers entersave_state_dict. The data writes cannot interleave here: every rank'sprepare_local_plancallsfs.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 thefs.mkdir, recreating the directory between rank 0'srmtreeand itsos.makedirs. Thatos.makedirshas noexist_ok=True, so rank 0 raisesFileExistsError.Fix
test/distributed/test_c10d_gloo.py,test/distributed/test_c10d_ucc.py(test_save_load_checkpoint): variant 1. Serialize the checkpoint into anio.BytesIObuffer on rank 0 and broadcast the bytes viabroadcast_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 adist.barrier()in thefinally, ahead of rank 0'srmtree. 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 costsTIMEOUT_DEFAULTand replaces the real failure with a timeout.test/distributed/checkpoint/test_fsspec.py: this file carried its own verbatim copy of the buggywith_temp_dirinstead 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 fromcheckpoint_utilsinstead.test/distributed/checkpoint/test_file_system_checkpoint.py(test_load_rowwise_to_colwise): variant 3. Rank 0 doesshutil.rmtree(path); os.makedirs(path)with no barrier before all ranks entersave_state_dict, so a peer'sfs.mkdircan recreate the directory in between and rank 0'sos.makedirsraisesFileExistsError. Add the missingdist.barrier(), matching the sibling testtest_load_with_different_shard_planin 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):Then run a DCP test that uses the helper:
Without the changes, rank 0 removes the directory while rank 1 is still reading it:
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:Reproduce the collision by running
torch.saveandtorch.loadagainst that same path concurrently from two processes, which is what two test runs on one host do:This matches the
_pickle.UnpicklingErrorsignature from #84886. With theio.BytesIO+broadcast_object_listchange, no shared path exists for concurrent runs to collide on.Barrier placement in
with_temp_dirOn a 2-rank gloo group whose
with_temp_dirbody raises on rank 1 only, with the peer process kept alive after the raise so it mirrorsMultiProcContinuousTest._worker_loop(with_temp_diris applied to those bases attest_2d_composability.py:913andtest_pp_composability.py:162). At a 20s process group timeout:mainAssertionError: rank 1 only failureRuntimeError: gloo connection ...AssertionError: rank 1 only failurefinallyAssertionError: rank 1 only failureOnly the
finallyplacement both reports the real failure and closes the delete-under-you window on the failure path, where a spuriousFileNotFoundErrorwould otherwise mask the real error.Developed with AI assistance; I reviewed the result.