Repository navigation
[release/2.12] Fix remaining checkpoint filesystem races flagged in #194614 (#196591) - #3660
Merged
pragupta merged 1 commit intoSep 21, 2026
Conversation
…ytorch#196591) Follow-up to pytorch#194614. That PR fixed a checkpoint reload race in post-local SGD tests but noted in review ([comment](pytorch#194614 (comment))) that the same bug shapes exist in several other places. This PR fixes those remaining sites. ## Root cause Three related races, all stemming from sharing a checkpoint through the filesystem across ranks instead of through a collective: 1. **Fixed-name collision:** a checkpoint path is built from a hardcoded name under the shared temp dir (e.g. `tempfile.gettempdir() + "/model.checkpoint"`). Two test processes running concurrently on the same host can collide on that name, so one run's rank 0 can overwrite the file while another run's rank 1 is loading it, producing `_pickle.UnpicklingError`/`EOFError` (`torch.save` is not atomic). 2. **Delete-under-you:** a directory or file is created by rank 0 and read by all ranks, then removed with no `dist.barrier()` between the last read and the removal. Whichever rank finishes first can delete the path while a peer hasn't opened it yet, producing `FileNotFoundError`. 3. **Recreate-under-you:** rank 0 does `shutil.rmtree(path)` then `os.makedirs(path)` with no barrier before the peers enter `save_state_dict`. The data writes cannot interleave here: every rank's `prepare_local_plan` calls `fs.mkdir(path, exist_ok=True)`, that runs inside the `"plan"` reduce_scatter, and the writes only happen after it. What a peer does land in that window is the `fs.mkdir`, recreating the directory between rank 0's `rmtree` and its `os.makedirs`. That `os.makedirs` has no `exist_ok=True`, so rank 0 raises `FileExistsError`. ## Fix - `test/distributed/test_c10d_gloo.py`, `test/distributed/test_c10d_ucc.py` (`test_save_load_checkpoint`): variant 1. Serialize the checkpoint into an `io.BytesIO` buffer on rank 0 and broadcast the bytes via `broadcast_object_list`, removing the shared fixed-name file instead of only randomizing it. - `torch/testing/_internal/distributed/checkpoint_utils.py` (`with_temp_dir`): variant 2, with the widest blast radius since every DCP test uses it. DCP genuinely needs a shared on-disk directory, so this cannot be fixed by broadcasting bytes; it gets a `dist.barrier()` in the `finally`, ahead of rank 0's `rmtree`. The barrier has to be on the failure path too: a rank whose body raised would otherwise skip it and leave every rank that passed blocked until the process group times out, which both costs `TIMEOUT_DEFAULT` and replaces the real failure with a timeout. - `test/distributed/checkpoint/test_fsspec.py`: this file carried its own verbatim copy of the buggy `with_temp_dir` instead of importing the shared helper, so fixing the helper alone would have left this file's DCP tests still racy. Delete the local copy and import the fixed helper from `checkpoint_utils` instead. - `test/distributed/checkpoint/test_file_system_checkpoint.py` (`test_load_rowwise_to_colwise`): variant 3. Rank 0 does `shutil.rmtree(path); os.makedirs(path)` with no barrier before all ranks enter `save_state_dict`, so a peer's `fs.mkdir` can recreate the directory in between and rank 0's `os.makedirs` raises `FileExistsError`. Add the missing `dist.barrier()`, matching the sibling test `test_load_with_different_shard_plan` in the same file, which already has it. ## Reproduction ### Delete-under-you (`with_temp_dir`) On `main`, add a 3s delay on non-zero ranks after the temp dir is broadcast and before the test body runs, standing in for real rank skew (same technique as pytorch#194614): ```python self.temp_dir = object_list[0] os.sync() if dist.get_rank() != 0: time.sleep(3) ``` Then run a DCP test that uses the helper: ``` python test/distributed/checkpoint/test_file_system_checkpoint.py -v \ -k test_read_write_shard_tensor ``` Without the changes, rank 0 removes the directory while rank 1 is still reading it: ``` rank 0: OK [rank1]: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpmwz8mu28/shard_0' ``` With the `dist.barrier()` added, the same delayed run passes on both ranks. ### Fixed-name collision (`test_save_load_checkpoint`) On `main`, the test shares a hardcoded path across ranks: ```python checkpoint_path = tempfile.gettempdir() + "/model.checkpoint" if self.rank == 0: torch.save(ddp_withload.state_dict(), checkpoint_path) dist.barrier() map_location = {"cuda:0": f"cuda:{self.rank:d}"} ddp_state_dict = torch.load(checkpoint_path, map_location=map_location) ``` Reproduce the collision by running `torch.save` and `torch.load` against that same path concurrently from two processes, which is what two test runs on one host do: ``` reader: 1 clean loads, errors: {'RuntimeError': 112565, 'EOFError': 177231, 'OSError': 300, 'UnpicklingError': 295} ``` This matches the `_pickle.UnpicklingError` signature from pytorch#84886. With the `io.BytesIO` + `broadcast_object_list` change, no shared path exists for concurrent runs to collide on. ### Barrier placement in `with_temp_dir` On a 2-rank gloo group whose `with_temp_dir` body raises on rank 1 only, with the peer process kept alive after the raise so it mirrors `MultiProcContinuousTest._worker_loop` (`with_temp_dir` is applied to those bases at `test_2d_composability.py:913` and `test_pp_composability.py:162`). At a 20s process group timeout: | variant | rank 0 | rank 1 | | --- | --- | --- | | `main` | 0.0s, OK | 1.0s, `AssertionError: rank 1 only failure` | | barrier on success path | 20.3s, `RuntimeError: gloo connection ...` | 1.0s, `AssertionError: rank 1 only failure` | | barrier in `finally` | 1.3s, OK | 1.3s, `AssertionError: rank 1 only failure` | Only the `finally` placement both reports the real failure and closes the delete-under-you window on the failure path, where a spurious `FileNotFoundError` would otherwise mask the real error. Developed with AI assistance; I reviewed the result. Pull Request resolved: pytorch#196591 Approved by: https://github.com/jeffdaily (cherry picked from commit b9f83ac)
pragupta
deleted the
albmalamd/cherry-pick/2.12/fix_post_localSGD_optimizer_step_reload
branch
September 21, 2026 15:14
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Follow-up to pytorch#194614. That PR fixed a checkpoint reload race in post-local SGD tests but noted in review (comment) that the same bug shapes exist in several other places. This PR fixes those remaining sites.
Root cause
Three related races, all stemming from sharing a checkpoint through the filesystem across ranks instead of through a collective:
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 pytorch#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 pytorch#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 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. Pull Request resolved: pytorch#196591 Approved by: https://github.com/jeffdaily
(cherry picked from commit b9f83ac)