Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/199677
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit d369f71 with merge base e91899c ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
| ) | ||
| @unittest.skipIf(device_type.type != "cuda", "CUDA graph test requires CUDA") | ||
| def test_gradient_accumulation_cudagraph_fake_pg(self): | ||
| torch.cuda.set_device(self.rank) |
There was a problem hiding this comment.
Could this test assert that it actually reaches the cleanup branch under review? Right now it only asserts capture/replay success, so a future backward-prefetch change that no longer leaves _all_gather_result pending would make the test pass without exercising finalize_backward()'s event wait. Just wrap or instrument FSDPParamGroup.finalize_backward in the test to record that at least one group enters with _all_gather_result is not None during capture, and renaming or documenting the test around pending backward-prefetch cleanup rather than generic gradient accumulation.
sanketpurandare
left a comment
There was a problem hiding this comment.
Please make the test stronger and merge
FSDPParamGroup.finalize_backward may clean up an all-gather launched by backward prefetch but never consumed. It recorded a device-specific event and waited through torch.accelerator.current_stream(), whose generic Stream.wait_event does not handle that device-specific event correctly during CUDA graph capture. The all-gather stream remained unjoined, so capture failed with cudaErrorStreamCaptureUnjoined. Use FSDP device handle for the wait, matching every other FSDP wait_event call. Add a FakePG CUDA graph gradient accumulation test that leaves a prefetched all-gather pending at finalization and replays the graph. Test Plan ```bash taskset -c 0-382 env CUDA_VISIBLE_DEVICES=0,1 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardCudaGraph ``` ```bash env UV_NO_CONFIG=1 lintrunner -a ``` Authored with an AI assistant. ghstack-source-id: d8a74c0 Pull-Request: #199677
## Motivation TorchTitan captures the complete forward/backward accumulation loop as one CUDA graph. The existing wrapper nevertheless rejects more than one outer accumulation group unless FSDP gradient reduction is deferred. That restriction predates whole-step capture and prevents valid configurations that reduce and accumulate sharded gradients after every microbatch. ## Design Pass the existing forward/backward callable directly to `wrap_fwd_bwd_with_cuda_graph`. `zero_grad(set_to_none=True)` clears Python gradient references before invocation. During capture, the first microbatch creates graph-owned parameter gradients and later microbatches accumulate into them. `_CUDAGraphGradientState` records those tensors after capture and restores each `param.grad` reference after replay, since CUDA replay does not repeat Python assignment. This changes no eager behavior, collective count, reduction dtype, or FSDP reduction timing. It removes only the stale deferred-reduction validation wrapper. ## Verification - Focused unit test exercises two accumulation groups with `fsdp_defer_gradient_reduction=False`. - Real two-GPU FSDP run completed two eager warmups, CUDA-graph capture, replay, optimizer updates, and clean process-group teardown with finite loss and gradient norms. - A full DP64/TP4/EP64, GA16 logical-topology validation completed ten steps with whole-step capture/replay and finite training state. - Repository formatting, AST, whitespace, license, flake8, pydoclint, codespell, and link checks pass. Pyrefly reports two unrelated errors already present on `main` in activation checkpointing and multimedia video typing. The Dist-MoE scale composition used for validation also requires the pending PyTorch FSDP stream-ownership fix in pytorch/pytorch#199677. --- <sub>Stack created with <a href="https://github.com/github/gh-stack">GitHub Stacks CLI</a></sub>
|
@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 |
> AI-assisted change prepared with Claude Code. It was split out of the all-gather contract draft #199726 (option 3), which inherited it from #188276, and is based on main so it can land on its own. > > With `reshard_after_forward` set to an int, a group that forward used but backward does not use is still prefetched by the next group's pre-backward. The group is in its post-forward state, so the prefetch all-gathers its post-forward shards over the smaller post-forward mesh, and since the group's own pre-backward never runs, nothing waits for that result. The last backward discards it in `finalize_backward`, but a backward that is not the last one, as in gradient accumulation with `set_is_last_backward(False)`, only reshards the group to the full mesh in `post_backward` and keeps the pending result. The next forward's `unshard` then returns early because a result is pending, and `wait_for_unshard` copies out a buffer gathered over the post-forward mesh as if the full mesh had gathered it, which fails in the copy-out (`start (0) + length (512) exceeds dimension size (256)` in the regression test). `_to_sharded` now waits for a pending all-gather result and discards it before the group returns to the sharded state, as `finalize_backward` and `_reset_iter_state` already do for mistargeted unshards. The three share the wait in `_wait_all_gather`, which waits through the FSDP device handle as #199677 made `finalize_backward` do. Only that path changes: `unshard` issues nothing while the group is unsharded, so a result is pending when `_to_sharded` runs only if an all-gather issued in the post-forward state was never waited on, such as this backward prefetch, and copying such a result out over the full mesh always failed. > > Test Plan: the local build predates main, so the tests ran with the same change on top of #199430, whose FSDP2 code paths for this bug match main's; the change differs only in the `finalize_backward` lines #199677 rewrote. `test_unused_backward_prefetch_with_post_forward_mesh` fails without the `_to_sharded` change, with the stale result still pending after the non-final backward, and passes with it. > ```bash > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch > ``` > All 8 tests pass on 4 B200 GPUs. ghstack-source-id: 9a55a31 Pull-Request: #199729
> AI-assisted change prepared with Claude Code. It was split out of the all-gather contract draft #199726 (option 3), which inherited it from #188276, and is based on main so it can land on its own. > > With `reshard_after_forward` set to an int, a group that forward used but backward does not use is still prefetched by the next group's pre-backward. The group is in its post-forward state, so the prefetch all-gathers its post-forward shards over the smaller post-forward mesh, and since the group's own pre-backward never runs, nothing waits for that result. The last backward discards it in `finalize_backward`, but a backward that is not the last one, as in gradient accumulation with `set_is_last_backward(False)`, only reshards the group to the full mesh in `post_backward` and keeps the pending result. The next forward's `unshard` then returns early because a result is pending, and `wait_for_unshard` copies out a buffer gathered over the post-forward mesh as if the full mesh had gathered it, which fails in the copy-out (`start (0) + length (512) exceeds dimension size (256)` in the regression test). `_to_sharded` now waits for a pending all-gather result and discards it before the group returns to the sharded state, as `finalize_backward` and `_reset_iter_state` already do for mistargeted unshards. The three share the wait in `_wait_all_gather`, which waits through the FSDP device handle as #199677 made `finalize_backward` do. Only that path changes: `unshard` issues nothing while the group is unsharded, so a result is pending when `_to_sharded` runs only if an all-gather issued in the post-forward state was never waited on, such as this backward prefetch, and copying such a result out over the full mesh always failed. > > Test Plan: the local build predates main, so the tests ran with the same change on top of #199430, whose FSDP2 code paths for this bug match main's; the change differs only in the `finalize_backward` lines #199677 rewrote. `test_unused_backward_prefetch_with_post_forward_mesh` fails without the `_to_sharded` change, with the stale result still pending after the non-final backward, and passes with it. > ```bash > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch > ``` > All 8 tests pass on 4 B200 GPUs. ghstack-source-id: 9a55a31 Pull-Request: #199729
> AI-assisted change prepared with Claude Code. It was split out of the all-gather contract draft #199726 (option 3), which inherited it from #188276, and is based on main so it can land on its own. > > With `reshard_after_forward` set to an int, a group that forward used but backward does not use is still prefetched by the next group's pre-backward. The group is in its post-forward state, so the prefetch all-gathers its post-forward shards over the smaller post-forward mesh, and since the group's own pre-backward never runs, nothing waits for that result. The last backward discards it in `finalize_backward`, but a backward that is not the last one, as in gradient accumulation with `set_is_last_backward(False)`, only reshards the group to the full mesh in `post_backward` and keeps the pending result. The next forward's `unshard` then returns early because a result is pending, and `wait_for_unshard` copies out a buffer gathered over the post-forward mesh as if the full mesh had gathered it, which fails in the copy-out (`start (0) + length (512) exceeds dimension size (256)` in the regression test). `_to_sharded` now waits for a pending all-gather result and discards it before the group returns to the sharded state, as `finalize_backward` and `_reset_iter_state` already do for mistargeted unshards. The three share the wait in `_wait_all_gather`, which waits through the FSDP device handle as #199677 made `finalize_backward` do. Only that path changes: `unshard` issues nothing while the group is unsharded, so a result is pending when `_to_sharded` runs only if an all-gather issued in the post-forward state was never waited on, such as this backward prefetch, and copying such a result out over the full mesh always failed. > > Test Plan: the local build predates main, so the tests ran with the same change on top of #199430, whose FSDP2 code paths for this bug match main's; the change differs only in the `finalize_backward` lines #199677 rewrote. `test_unused_backward_prefetch_with_post_forward_mesh` fails without the `_to_sharded` change, with the stale result still pending after the non-final backward, and passes with it. > ```bash > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch > ``` > All 8 tests pass on 4 B200 GPUs. Co-authored-by: wuyl1 <[email protected]> ghstack-source-id: 9a55a31 Pull-Request: #199729
> AI-assisted change prepared with Claude Code. It was split out of the all-gather contract draft #199726 (option 3), which inherited it from #188276, and is based on main so it can land on its own. > > With `reshard_after_forward` set to an int, a group that forward used but backward does not use is still prefetched by the next group's pre-backward. The group is in its post-forward state, so the prefetch all-gathers its post-forward shards over the smaller post-forward mesh, and since the group's own pre-backward never runs, nothing waits for that result. The last backward discards it in `finalize_backward`, but a backward that is not the last one, as in gradient accumulation with `set_is_last_backward(False)`, only reshards the group to the full mesh in `post_backward` and keeps the pending result. The next forward's `unshard` then returns early because a result is pending, and `wait_for_unshard` copies out a buffer gathered over the post-forward mesh as if the full mesh had gathered it, which fails in the copy-out (`start (0) + length (512) exceeds dimension size (256)` in the regression test). `_to_sharded` now waits for a pending all-gather result and discards it before the group returns to the sharded state, as `finalize_backward` and `_reset_iter_state` already do for mistargeted unshards. The three share the wait in `_wait_all_gather`, which waits through the FSDP device handle as #199677 made `finalize_backward` do. Only that path changes: `unshard` issues nothing while the group is unsharded, so a result is pending when `_to_sharded` runs only if an all-gather issued in the post-forward state was never waited on, such as this backward prefetch, and copying such a result out over the full mesh always failed. > > Test Plan: the local build predates main, so the tests ran with the same change on top of #199430, whose FSDP2 code paths for this bug match main's; the change differs only in the `finalize_backward` lines #199677 rewrote. `test_unused_backward_prefetch_with_post_forward_mesh` fails without the `_to_sharded` change, with the stale result still pending after the non-final backward, and passes with it. > ```bash > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch > ``` > All 8 tests pass on 4 B200 GPUs. Co-authored-by: wuyl1 <[email protected]> ghstack-source-id: 1209001 Pull-Request: #199729
…99729) > AI-assisted change prepared with Claude Code. It was split out of the all-gather contract draft #199726 (option 3), which inherited it from #188276, and is based on main so it can land on its own. > > With `reshard_after_forward` set to an int, a group that forward used but backward does not use is still prefetched by the next group's pre-backward. The group is in its post-forward state, so the prefetch all-gathers its post-forward shards over the smaller post-forward mesh, and since the group's own pre-backward never runs, nothing waits for that result. The last backward discards it in `finalize_backward`, but a backward that is not the last one, as in gradient accumulation with `set_is_last_backward(False)`, only reshards the group to the full mesh in `post_backward` and keeps the pending result. The next forward's `unshard` then returns early because a result is pending, and `wait_for_unshard` copies out a buffer gathered over the post-forward mesh as if the full mesh had gathered it, which fails in the copy-out (`start (0) + length (512) exceeds dimension size (256)` in the regression test). `_to_sharded` now waits for a pending all-gather result and discards it before the group returns to the sharded state, as `finalize_backward` and `_reset_iter_state` already do for mistargeted unshards. The three share the wait in `_wait_all_gather`, which waits through the FSDP device handle as #199677 made `finalize_backward` do. Only that path changes: `unshard` issues nothing while the group is unsharded, so a result is pending when `_to_sharded` runs only if an all-gather issued in the post-forward state was never waited on, such as this backward prefetch, and copying such a result out over the full mesh always failed. > > Test Plan: the local build predates main, so the tests ran with the same change on top of #199430, whose FSDP2 code paths for this bug match main's; the change differs only in the `finalize_backward` lines #199677 rewrote. `test_unused_backward_prefetch_with_post_forward_mesh` fails without the `_to_sharded` change, with the stale result still pending after the non-final backward, and passes with it. > ```bash > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch > ``` > All 8 tests pass on 4 B200 GPUs. Co-authored-by: wuyl1 <[email protected]> Pull Request resolved: #199729 Approved by: https://github.com/anshul-si ghstack dependencies: #197204
| # then we wait here and clear the unshard | ||
| if (event := self._all_gather_result.all_gather_event) is not None: | ||
| torch.accelerator.current_stream().wait_event(event) | ||
| self.device_handle.current_stream().wait_event(event) |
There was a problem hiding this comment.
this becomes a torch.accelerator -> torch.cuda renaming? is there something happened during rebase?
FSDPParamGroup.finalize_backward may clean up an all-gather launched by backward prefetch but never consumed. It recorded a device-specific event and waited through torch.accelerator.current_stream(), whose generic Stream.wait_event does not handle that device-specific event correctly during CUDA graph capture. The all-gather stream remained unjoined, so capture failed with cudaErrorStreamCaptureUnjoined. Use FSDP device handle for the wait, matching every other FSDP wait_event call. Add a FakePG CUDA graph gradient accumulation test that leaves a prefetched all-gather pending at finalization and replays the graph. Test Plan ```bash taskset -c 0-382 env CUDA_VISIBLE_DEVICES=0,1 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardCudaGraph ``` ```bash env UV_NO_CONFIG=1 lintrunner -a ``` Authored with an AI assistant. Pull Request resolved: pytorch#199677 Approved by: https://github.com/sanketpurandare
…torch#199729) > AI-assisted change prepared with Claude Code. It was split out of the all-gather contract draft pytorch#199726 (option 3), which inherited it from pytorch#188276, and is based on main so it can land on its own. > > With `reshard_after_forward` set to an int, a group that forward used but backward does not use is still prefetched by the next group's pre-backward. The group is in its post-forward state, so the prefetch all-gathers its post-forward shards over the smaller post-forward mesh, and since the group's own pre-backward never runs, nothing waits for that result. The last backward discards it in `finalize_backward`, but a backward that is not the last one, as in gradient accumulation with `set_is_last_backward(False)`, only reshards the group to the full mesh in `post_backward` and keeps the pending result. The next forward's `unshard` then returns early because a result is pending, and `wait_for_unshard` copies out a buffer gathered over the post-forward mesh as if the full mesh had gathered it, which fails in the copy-out (`start (0) + length (512) exceeds dimension size (256)` in the regression test). `_to_sharded` now waits for a pending all-gather result and discards it before the group returns to the sharded state, as `finalize_backward` and `_reset_iter_state` already do for mistargeted unshards. The three share the wait in `_wait_all_gather`, which waits through the FSDP device handle as pytorch#199677 made `finalize_backward` do. Only that path changes: `unshard` issues nothing while the group is unsharded, so a result is pending when `_to_sharded` runs only if an all-gather issued in the post-forward state was never waited on, such as this backward prefetch, and copying such a result out over the full mesh always failed. > > Test Plan: the local build predates main, so the tests ran with the same change on top of pytorch#199430, whose FSDP2 code paths for this bug match main's; the change differs only in the `finalize_backward` lines pytorch#199677 rewrote. `test_unused_backward_prefetch_with_post_forward_mesh` fails without the `_to_sharded` change, with the stale result still pending after the non-final backward, and passes with it. > ```bash > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch > ``` > All 8 tests pass on 4 B200 GPUs. Co-authored-by: wuyl1 <[email protected]> Pull Request resolved: pytorch#199729 Approved by: https://github.com/anshul-si ghstack dependencies: pytorch#197204
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review. > With gradient accumulation and `set_is_last_backward(False)`, FSDP2 keeps > `post_forward_order` across backwards until `_end_backward_iteration` on the > last backward. Each forward appends after the previous forward's entries, so > in every microbatch after the first, the first group's implicit backward > prefetch targets the previous forward's last group. When only the last > backward reshards (`set_reshard_after_backward(True)` on the last microbatch, > as torchtitan does with deferred gradient reduction), the last group reshards > after its own backward and the first group's backward all-gathers it again > for nothing. In torchtitan, with DeepSeek V3 layers and 16 accumulated > microbatches, that is one extra 1.77 GB all-gather of the output projection > per step. > > Instead of clearing `post_forward_order` early in the root's post-backward > final callback -- which would be defeated whenever any unrelated group skips > backward (e.g., unused outputs) and would alter > `finalize_backward(async_op=True)`'s cross-root overlap check -- this change > skips stale targets per group in `_backward_prefetch`: > > `FSDPCommContext` now tracks a monotonic per-forward `_forward_id` > (incremented in `FSDPState._root_pre_forward` when claiming > `iter_forward_root`) alongside a parallel `_post_forward_ids` list managed > through `record_post_forward`, `clear_post_forward_order`, and > `should_backward_prefetch`. `FSDPParamGroup.pre_backward` also pops > `_post_forward_indices` on the explicit-prefetch branch (while keeping the > 0-arg `_backward_prefetch(self)` signature unchanged for compatibility with > external monkeypatches), so groups using `set_modules_to_backward_prefetch` > (which torchtitan sets on transformer blocks and the output projection) also > consume their post-forward indices. `_backward_prefetch` then prefetches a > target only when `should_backward_prefetch` is true: either > `target._post_forward_indices` is non-empty (pending backward, preserving > cross-forward prefetch under pipeline schedules such as F-F-B-B and 1F1B), or > the target was recorded in the same forward pass (`target_forward_id == > curr_forward_id`, preserving prefetch of shared layers across multiple > `retain_graph=True` backwards while still skipping completed targets from > another root under `share_comm_ctx` in any backward order). `_post_forward_ids` > is read lazily only when `target._post_forward_indices` is empty. In the > multi-param-group walk-back loop (`_num_param_groups > 1`), sibling groups of > `curr_modules` are skipped only before `target_modules` is locked in, > preventing a two-block model under gradient accumulation from stepping past a > previous microbatch's `curr_modules` into an earlier copy of `target_modules`. > > Two supporting fixes keep the order/context state consistent: > - `FSDPStateContext.iter_forward_grad_enabled` captures > `torch.is_grad_enabled()` once in `_root_pre_forward`, and `_post_forward` / > `_force_complete_incomplete_states` invoke `_record_post_forward()` only when > `not is_bw() and iter_forward_grad_enabled` (leaving > `FSDPParamGroup.post_forward(self, module, input, output)`'s 4-arg signature > unchanged). Outer `torch.no_grad()` forwards (e.g. eval) no longer grow > `post_forward_order`, while inner FSDP modules wrapped in reentrant > activation checkpointing (`use_reentrant=True`, which runs forward under > `torch.no_grad()`) still record for backward prefetch. > - `FSDPCommContext.lazy_init` is made idempotent so sharing a comm context > across FSDP roots via `share_comm_ctx` without manual `_lazy_init()` does not > recreate streams or wipe `post_forward_order` / `_post_forward_ids` / > `reduce_scatter_states` when the second root runs its first forward. > > Behavioral notes: > - With `set_is_last_backward(False)` and default `reshard_after_backward=True`, > intermediate microbatches previously retained the stale prefetch's > `_all_gather_result` across microbatch boundaries and reused it on the next > forward's `unshard`. Skipping the stale prefetch moves that all-gather back > to the next forward (same total all-gather count on intermediate > microbatches, lower peak memory across forward, different overlap window) > while eliminating the wasted all-gather on the final microbatch. > - Outer `torch.no_grad()` forwards (e.g. eval) no longer append to > `post_forward_order`. > - `TestFullyShardCudaGraph.test_pending_backward_prefetch_cleanup_cudagraph` > previously relied on the stale backward prefetch bug to leave a pending > all-gather for `finalize_backward`; it now uses explicit backward misprefetch > (`set_modules_to_backward_prefetch`) to keep testing #199677's CUDA graph > cleanup path. > > Test Plan > > ``` > python test/distributed/_composable/fsdp/test_fully_shard_training.py -f -v \ > -k test_pending_backward_prefetch_cleanup_cudagraph \ > -k test_manual_backward_finalization_rejects_shared_context_overlap > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -f -v \ > TestFSDPCommContext \ > TestFullyShardPrefetch.test_backward_prefetch_with_gradient_accumulation \ > TestFullyShardPrefetch.test_backward_prefetch_shared_comm_ctx_interleaved_roots \ > TestFullyShardPrefetch.test_fully_shard_backward_prefetch \ > TestFullyShardPrefetch.test_set_modules_to_forward_prefetch \ > TestFullyShardPrefetch.test_set_modules_to_backward_prefetch \ > TestFullyShardPrefetch.test_set_modules_to_backward_prefetch_inside_ac \ > TestFullyShardPrefetch.test_fully_shard_multi_module_backward_prefetch \ > TestFullyShardPrefetch.test_fully_shard_multi_module_unused_module \ > TestFullyShardPrefetch.test_backward_misprefetch \ > TestFullyShardPrefetch.test_unused_backward_prefetch_with_post_forward_mesh > ``` > > Ran on 4 B200s at base `192f70c27af`: > - `test_fully_shard_training.py`: 2/2 passed (including > `test_pending_backward_prefetch_cleanup_cudagraph` and > `test_manual_backward_finalization_rejects_shared_context_overlap`). > - `test_fully_shard_comm.py`: 15/15 passed (all 5 `TestFSDPCommContext` tests > including `test_lazy_init_is_idempotent`, plus `TestFullyShardPrefetch` > covering gradient accumulation with exact per-microbatch prefetch assertions > across implicit/explicit prefetch, deferred vs. per-microbatch reshard, > detached unused submodules and outer no-grad eval forwards, 1F1B pipelining > `F0,F1,B0,F2,B1,B2`, multi-param-group accumulation, `use_reentrant=True` AC, > `share_comm_ctx` interleaved roots in both `B_b->B_a` and `B_a->B_b` orders > without manual `_lazy_init`, `_test_backward_prefetch_unused_in_backward`, > and `test_unused_backward_prefetch_with_post_forward_mesh`). ghstack-source-id: 6e276b4 Pull-Request: #200476
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review. > With gradient accumulation and `set_is_last_backward(False)`, FSDP2 keeps > `post_forward_order` across backwards until `_end_backward_iteration` on the > last backward. Each forward appends after the previous forward's entries, so > in every microbatch after the first, the first group's implicit backward > prefetch targets the previous forward's last group. When only the last > backward reshards (`set_reshard_after_backward(True)` on the last microbatch, > as torchtitan does with deferred gradient reduction), the last group reshards > after its own backward and the first group's backward all-gathers it again > for nothing. In torchtitan, with DeepSeek V3 layers and 16 accumulated > microbatches, that is one extra 1.77 GB all-gather of the output projection > per step. > > Instead of clearing `post_forward_order` early in the root's post-backward > final callback -- which would be defeated whenever any unrelated group skips > backward (e.g., unused outputs) and would alter > `finalize_backward(async_op=True)`'s cross-root overlap check -- this change > skips stale targets per group in `_backward_prefetch`: > > `FSDPCommContext` now tracks a monotonic per-forward `_forward_id` > (incremented in `FSDPState._root_pre_forward` when claiming > `iter_forward_root`) alongside a parallel `_post_forward_ids` list managed > through `record_post_forward`, `clear_post_forward_order`, and > `should_backward_prefetch`. `FSDPParamGroup.pre_backward` also pops > `_post_forward_indices` on the explicit-prefetch branch (while keeping the > 0-arg `_backward_prefetch(self)` signature unchanged for compatibility with > external monkeypatches), so groups using `set_modules_to_backward_prefetch` > (which torchtitan sets on transformer blocks and the output projection) also > consume their post-forward indices. `_backward_prefetch` then prefetches a > target only when `should_backward_prefetch` is true: either > `target._post_forward_indices` is non-empty (pending backward, preserving > cross-forward prefetch under pipeline schedules such as F-F-B-B and 1F1B), or > the target was recorded in the same forward pass (`target_forward_id == > curr_forward_id`, preserving prefetch of shared layers across multiple > `retain_graph=True` backwards while still skipping completed targets from > another root under `share_comm_ctx` in any backward order). `_post_forward_ids` > is read lazily only when `target._post_forward_indices` is empty. In the > multi-param-group walk-back loop (`_num_param_groups > 1`), sibling groups of > `curr_modules` are skipped only before `target_modules` is locked in, > preventing a two-block model under gradient accumulation from stepping past a > previous microbatch's `curr_modules` into an earlier copy of `target_modules`. > > Two supporting fixes keep the order/context state consistent: > - `FSDPStateContext.iter_forward_grad_enabled` captures > `torch.is_grad_enabled()` once in `_root_pre_forward`, and `_post_forward` / > `_force_complete_incomplete_states` invoke `_record_post_forward()` only when > `not is_bw() and iter_forward_grad_enabled` (leaving > `FSDPParamGroup.post_forward(self, module, input, output)`'s 4-arg signature > unchanged). Outer `torch.no_grad()` forwards (e.g. eval) no longer grow > `post_forward_order`, while inner FSDP modules wrapped in reentrant > activation checkpointing (`use_reentrant=True`, which runs forward under > `torch.no_grad()`) still record for backward prefetch. > - `FSDPCommContext.lazy_init` is made idempotent so sharing a comm context > across FSDP roots via `share_comm_ctx` without manual `_lazy_init()` does not > recreate streams or wipe `post_forward_order` / `_post_forward_ids` / > `reduce_scatter_states` when the second root runs its first forward. > > Behavioral notes: > - With `set_is_last_backward(False)` and default `reshard_after_backward=True`, > intermediate microbatches previously retained the stale prefetch's > `_all_gather_result` across microbatch boundaries and reused it on the next > forward's `unshard`. Skipping the stale prefetch moves that all-gather back > to the next forward (same total all-gather count on intermediate > microbatches, lower peak memory across forward, different overlap window) > while eliminating the wasted all-gather on the final microbatch. > - Outer `torch.no_grad()` forwards (e.g. eval) no longer append to > `post_forward_order`. > - `TestFullyShardCudaGraph.test_pending_backward_prefetch_cleanup_cudagraph` > previously relied on the stale backward prefetch bug to leave a pending > all-gather for `finalize_backward`; it now uses explicit backward misprefetch > (`set_modules_to_backward_prefetch`) to keep testing #199677's CUDA graph > cleanup path. > > Test Plan > > ``` > python test/distributed/_composable/fsdp/test_fully_shard_training.py -f -v \ > -k test_pending_backward_prefetch_cleanup_cudagraph \ > -k test_manual_backward_finalization_rejects_shared_context_overlap > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -f -v \ > TestFSDPCommContext \ > TestFullyShardPrefetch.test_backward_prefetch_with_gradient_accumulation \ > TestFullyShardPrefetch.test_backward_prefetch_shared_comm_ctx_interleaved_roots \ > TestFullyShardPrefetch.test_fully_shard_backward_prefetch \ > TestFullyShardPrefetch.test_set_modules_to_forward_prefetch \ > TestFullyShardPrefetch.test_set_modules_to_backward_prefetch \ > TestFullyShardPrefetch.test_set_modules_to_backward_prefetch_inside_ac \ > TestFullyShardPrefetch.test_fully_shard_multi_module_backward_prefetch \ > TestFullyShardPrefetch.test_fully_shard_multi_module_unused_module \ > TestFullyShardPrefetch.test_backward_misprefetch \ > TestFullyShardPrefetch.test_unused_backward_prefetch_with_post_forward_mesh > ``` > > Ran on 4 B200s at base `192f70c27af`: > - `test_fully_shard_training.py`: 2/2 passed (including > `test_pending_backward_prefetch_cleanup_cudagraph` and > `test_manual_backward_finalization_rejects_shared_context_overlap`). > - `test_fully_shard_comm.py`: 15/15 passed (all 5 `TestFSDPCommContext` tests > including `test_lazy_init_is_idempotent`, plus `TestFullyShardPrefetch` > covering gradient accumulation with exact per-microbatch prefetch assertions > across implicit/explicit prefetch, deferred vs. per-microbatch reshard, > detached unused submodules and outer no-grad eval forwards, 1F1B pipelining > `F0,F1,B0,F2,B1,B2`, multi-param-group accumulation, `use_reentrant=True` AC, > `share_comm_ctx` interleaved roots in both `B_b->B_a` and `B_a->B_b` orders > without manual `_lazy_init`, `_test_backward_prefetch_unused_in_backward`, > and `test_unused_backward_prefetch_with_post_forward_mesh`). ghstack-source-id: e15221f Pull-Request: #200476
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review. > With gradient accumulation and `set_is_last_backward(False)`, FSDP2 keeps > `post_forward_order` across backwards until `_end_backward_iteration` on the > last backward. Each forward appends after the previous forward's entries, so > in every microbatch after the first, the first group's implicit backward > prefetch targets the previous forward's last group. When only the last > backward reshards (`set_reshard_after_backward(True)` on the last microbatch, > as torchtitan does with deferred gradient reduction), the last group reshards > after its own backward and the first group's backward all-gathers it again > for nothing. In torchtitan, with DeepSeek V3 layers and 16 accumulated > microbatches, that is one extra 1.77 GB all-gather of the output projection > per step. > > Instead of clearing `post_forward_order` early in the root's post-backward > final callback -- which would be defeated whenever any unrelated group skips > backward (e.g., unused outputs) and would alter > `finalize_backward(async_op=True)`'s cross-root overlap check -- this change > skips stale targets per group in `_backward_prefetch`: > > `FSDPCommContext` now tracks a monotonic per-forward `_forward_id` > (incremented in `FSDPState._root_pre_forward` when claiming > `iter_forward_root`) alongside a parallel `_post_forward_ids` list managed > through `record_post_forward`, `clear_post_forward_order`, and > `should_backward_prefetch`. `FSDPParamGroup.pre_backward` also pops > `_post_forward_indices` on the explicit-prefetch branch (while keeping the > 0-arg `_backward_prefetch(self)` signature unchanged for compatibility with > external monkeypatches), so groups using `set_modules_to_backward_prefetch` > (which torchtitan sets on transformer blocks and the output projection) also > consume their post-forward indices. `_backward_prefetch` then prefetches a > target only when `should_backward_prefetch` is true: either > `target._post_forward_indices` is non-empty (pending backward, preserving > cross-forward prefetch under pipeline schedules such as F-F-B-B and 1F1B), or > the target was recorded in the same forward pass (`target_forward_id == > curr_forward_id`, preserving prefetch of shared layers across multiple > `retain_graph=True` backwards while still skipping completed targets from > another root under `share_comm_ctx` in any backward order). `_post_forward_ids` > is read lazily only when `target._post_forward_indices` is empty. In the > multi-param-group walk-back loop (`_num_param_groups > 1`), sibling groups of > `curr_modules` are skipped only before `target_modules` is locked in, > preventing a two-block model under gradient accumulation from stepping past a > previous microbatch's `curr_modules` into an earlier copy of `target_modules`. > > Two supporting fixes keep the order/context state consistent: > - `FSDPStateContext.iter_forward_grad_enabled` captures > `torch.is_grad_enabled()` once in `_root_pre_forward`, and `_post_forward` / > `_force_complete_incomplete_states` invoke `_record_post_forward()` only when > `not is_bw() and iter_forward_grad_enabled` (leaving > `FSDPParamGroup.post_forward(self, module, input, output)`'s 4-arg signature > unchanged). Outer `torch.no_grad()` forwards (e.g. eval) no longer grow > `post_forward_order`, while inner FSDP modules wrapped in reentrant > activation checkpointing (`use_reentrant=True`, which runs forward under > `torch.no_grad()`) still record for backward prefetch. > - `FSDPCommContext.lazy_init` is made idempotent so sharing a comm context > across FSDP roots via `share_comm_ctx` without manual `_lazy_init()` does not > recreate streams or wipe `post_forward_order` / `_post_forward_ids` / > `reduce_scatter_states` when the second root runs its first forward. > > Behavioral notes: > - With `set_is_last_backward(False)` and default `reshard_after_backward=True`, > intermediate microbatches previously retained the stale prefetch's > `_all_gather_result` across microbatch boundaries and reused it on the next > forward's `unshard`. Skipping the stale prefetch moves that all-gather back > to the next forward (same total all-gather count on intermediate > microbatches, lower peak memory across forward, different overlap window) > while eliminating the wasted all-gather on the final microbatch. > - Outer `torch.no_grad()` forwards (e.g. eval) no longer append to > `post_forward_order`. > - `TestFullyShardCudaGraph.test_pending_backward_prefetch_cleanup_cudagraph` > previously relied on the stale backward prefetch bug to leave a pending > all-gather for `finalize_backward`; it now uses explicit backward misprefetch > (`set_modules_to_backward_prefetch`) to keep testing #199677's CUDA graph > cleanup path. > > Test Plan > > ``` > python test/distributed/_composable/fsdp/test_fully_shard_training.py -f -v \ > -k test_pending_backward_prefetch_cleanup_cudagraph \ > -k test_manual_backward_finalization_rejects_shared_context_overlap > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -f -v \ > TestFSDPCommContext \ > TestFullyShardPrefetch.test_backward_prefetch_with_gradient_accumulation \ > TestFullyShardPrefetch.test_backward_prefetch_shared_comm_ctx_interleaved_roots \ > TestFullyShardPrefetch.test_fully_shard_backward_prefetch \ > TestFullyShardPrefetch.test_set_modules_to_forward_prefetch \ > TestFullyShardPrefetch.test_set_modules_to_backward_prefetch \ > TestFullyShardPrefetch.test_set_modules_to_backward_prefetch_inside_ac \ > TestFullyShardPrefetch.test_fully_shard_multi_module_backward_prefetch \ > TestFullyShardPrefetch.test_fully_shard_multi_module_unused_module \ > TestFullyShardPrefetch.test_backward_misprefetch \ > TestFullyShardPrefetch.test_unused_backward_prefetch_with_post_forward_mesh > ``` > > Ran on 4 B200s at base `192f70c27af`: > - `test_fully_shard_training.py`: 2/2 passed (including > `test_pending_backward_prefetch_cleanup_cudagraph` and > `test_manual_backward_finalization_rejects_shared_context_overlap`). > - `test_fully_shard_comm.py`: 15/15 passed (all 5 `TestFSDPCommContext` tests > including `test_lazy_init_is_idempotent`, plus `TestFullyShardPrefetch` > covering gradient accumulation with exact per-microbatch prefetch assertions > across implicit/explicit prefetch, deferred vs. per-microbatch reshard, > detached unused submodules and outer no-grad eval forwards, 1F1B pipelining > `F0,F1,B0,F2,B1,B2`, multi-param-group accumulation, `use_reentrant=True` AC, > `share_comm_ctx` interleaved roots in both `B_b->B_a` and `B_a->B_b` orders > without manual `_lazy_init`, `_test_backward_prefetch_unused_in_backward`, > and `test_unused_backward_prefetch_with_post_forward_mesh`). ghstack-source-id: c19abaf Pull-Request: #200476
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review. > With gradient accumulation and `set_is_last_backward(False)`, FSDP2 keeps > `post_forward_order` across backwards until `_end_backward_iteration` on the > last backward. Each forward appends after the previous forward's entries, so > in every microbatch after the first, the first group's implicit backward > prefetch targets the previous forward's last group. When only the last > backward reshards (`set_reshard_after_backward(True)` on the last microbatch, > as torchtitan does with deferred gradient reduction), the last group reshards > after its own backward and the first group's backward all-gathers it again > for nothing. In torchtitan, with DeepSeek V3 layers and 16 accumulated > microbatches, that is one extra 1.77 GB all-gather of the output projection > per step. > > Instead of clearing `post_forward_order` early in the root's post-backward > final callback -- which would be defeated whenever any unrelated group skips > backward (e.g., unused outputs) and would alter > `finalize_backward(async_op=True)`'s cross-root overlap check -- this change > skips stale targets per group in `_backward_prefetch`: > > `FSDPCommContext` tracks `_forward_start_indices: set[int]`, recording > `len(post_forward_order)` via `mark_forward_start()` when > `FSDPState._root_pre_forward` claims `iter_forward_root` with grad enabled > (and clearing it alongside `post_forward_order` in > `clear_post_forward_order()`). `FSDPParamGroup.pre_backward` also pops > `_post_forward_indices` on the explicit-prefetch branch (while keeping the > 0-arg `_backward_prefetch(self)` signature unchanged for compatibility with > external monkeypatches), so groups using `set_modules_to_backward_prefetch` > (which torchtitan sets on transformer blocks and the output projection) also > consume their post-forward indices. `_backward_prefetch` then prefetches a > target only when `target._post_forward_indices` is non-empty (pending > backward, preserving cross-forward prefetch under pipeline schedules such as > F-F-B-B and 1F1B) or the walk back from `curr_index` has not crossed a > forward start boundary (`curr_index not in _forward_start_indices` in the > single-group path; `crossed` flag in the multi-group walk-back loop), > preserving prefetch of shared layers across multiple `retain_graph=True` > backwards while skipping completed targets from prior forwards or another > root under `share_comm_ctx` in any backward order. In the multi-param-group > walk-back loop (`_num_param_groups > 1`), sibling groups of `curr_modules` > are skipped only before `target_modules` is locked in, preventing a two-block > model under gradient accumulation from stepping past a previous microbatch's > `curr_modules` into an earlier copy of `target_modules`. > > Two supporting fixes keep the order/context state consistent: > - `FSDPStateContext.iter_forward_grad_enabled` captures > `torch.is_grad_enabled()` once in `_root_pre_forward`, and `_post_forward` / > `_force_complete_incomplete_states` invoke `_record_post_forward()` only when > `not is_bw() and iter_forward_grad_enabled` (leaving > `FSDPParamGroup.post_forward(self, module, input, output)`'s 4-arg signature > unchanged). Outer `torch.no_grad()` forwards (e.g. eval) no longer grow > `post_forward_order`, while inner FSDP modules wrapped in reentrant > activation checkpointing (`use_reentrant=True`, which runs forward under > `torch.no_grad()`) still record for backward prefetch. > - `FSDPCommContext.lazy_init` is made idempotent (keyed on > `all_gather_copy_in_stream is not None`, replacing the `hasattr` checks on > `device_handle` and `all_gather_copy_in_stream`, while still initializing > streams if `unshard()` set `device_handle` beforehand) so sharing a comm > context across FSDP roots via `share_comm_ctx` without manual `_lazy_init()` > does not recreate streams or wipe `post_forward_order` / > `_forward_start_indices` / `reduce_scatter_states` when the second root runs > its first forward. > > Behavioral notes: > - With `set_is_last_backward(False)` and default `reshard_after_backward=True`, > intermediate microbatches previously retained the stale prefetch's > `_all_gather_result` across microbatch boundaries and reused it on the next > forward's `unshard`. Skipping the stale prefetch moves that all-gather back > to the next forward (same total all-gather count on intermediate > microbatches, lower peak memory across forward, different overlap window) > while eliminating the wasted all-gather on the final microbatch. > - Outer `torch.no_grad()` forwards (e.g. eval) no longer append to > `post_forward_order`. > - `TestFullyShardCudaGraph.test_pending_backward_prefetch_cleanup_cudagraph` > previously relied on the stale backward prefetch bug to leave a pending > all-gather for `finalize_backward`; it now uses explicit backward misprefetch > (`set_modules_to_backward_prefetch`) to keep testing #199677's CUDA graph > cleanup path. > > Test Plan > > ``` > python test/distributed/_composable/fsdp/test_fully_shard_training.py -f -v \ > -k test_pending_backward_prefetch_cleanup_cudagraph \ > -k test_manual_backward_finalization_rejects_shared_context_overlap \ > -k test_get_all_gather_copy_in_stream > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -f -v \ > TestFSDPCommContext \ > TestFullyShardPrefetch.test_backward_prefetch_with_gradient_accumulation \ > TestFullyShardPrefetch.test_backward_prefetch_shared_comm_ctx_interleaved_roots \ > TestFullyShardPrefetch.test_fully_shard_backward_prefetch \ > TestFullyShardPrefetch.test_backward_misprefetch \ > TestFullyShardPrefetch.test_unused_backward_prefetch_with_post_forward_mesh > ``` > > Ran on 4 B200s at base `192f70c27af`: > - `test_fully_shard_training.py`: 4/4 passed (including > `test_pending_backward_prefetch_cleanup_cudagraph`, > `test_manual_backward_finalization_rejects_shared_context_overlap`, and > `test_get_all_gather_copy_in_stream*`). > - `test_fully_shard_comm.py`: 10/10 passed on the final commit (all 5 > `TestFSDPCommContext` tests including `test_lazy_init_is_idempotent` with > pre-set `device_handle`, plus `TestFullyShardPrefetch` covering gradient > accumulation with exact per-microbatch prefetch assertions across > implicit/explicit prefetch, deferred vs. per-microbatch reshard, detached > unused submodules and outer no-grad eval forwards, 1F1B pipelining > `F0,F1,B0,F2,B1,B2`, multi-param-group accumulation, `use_reentrant=True` AC, > `share_comm_ctx` interleaved roots in both `B_b->B_a` and `B_a->B_b` orders > without manual `_lazy_init`, `_test_backward_prefetch_unused_in_backward`, > `test_backward_misprefetch`, and > `test_unused_backward_prefetch_with_post_forward_mesh`). ghstack-source-id: c19abaf Pull-Request: #200476
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review. > With gradient accumulation and `set_is_last_backward(False)`, FSDP2 keeps > `post_forward_order` across backwards until `_end_backward_iteration` on the > last backward. Each forward appends after the previous forward's entries, so > in every microbatch after the first, the first group's implicit backward > prefetch targets the previous forward's last group. When only the last > backward reshards (`set_reshard_after_backward(True)` on the last microbatch, > as torchtitan does with deferred gradient reduction), the last group reshards > after its own backward and the first group's backward all-gathers it again > for nothing. In torchtitan, with DeepSeek V3 layers and 16 accumulated > microbatches, that is one extra 1.77 GB all-gather of the output projection > per step. > > Instead of clearing `post_forward_order` early in the root's post-backward > final callback -- which would be defeated whenever any unrelated group skips > backward (e.g., unused outputs) and would alter > `finalize_backward(async_op=True)`'s cross-root overlap check -- this change > skips stale targets per group in `_backward_prefetch`: > > `FSDPCommContext` tracks `_forward_start_indices: set[int]`, recording > `len(post_forward_order)` via `mark_forward_start()` when > `FSDPState._root_pre_forward` claims `iter_forward_root` (and clearing it > alongside `post_forward_order` in `clear_post_forward_order()`). > `FSDPParamGroup.pre_backward` also pops `_post_forward_indices` on the > explicit-prefetch branch (while keeping the 0-arg `_backward_prefetch(self)` > signature unchanged for compatibility with external monkeypatches), so groups > using `set_modules_to_backward_prefetch` (which torchtitan sets on > transformer blocks and the output projection) also consume their post-forward > indices. `_backward_prefetch` then prefetches a target only when > `target._post_forward_indices` is non-empty (pending backward, preserving > cross-forward prefetch under pipeline schedules such as F-F-B-B and 1F1B) or > the walk back from `curr_index` has not crossed a forward start boundary > (`curr_index not in _forward_start_indices` in the single-group path; > `crossed` flag in the multi-group walk-back loop), preserving prefetch of > shared layers across multiple `retain_graph=True` backwards while skipping > completed targets from prior forwards. In the multi-param-group walk-back > loop (`_num_param_groups > 1`), sibling groups of `curr_modules` are skipped > only before `target_modules` is locked in, preventing a two-block model under > gradient accumulation from stepping past a previous microbatch's > `curr_modules` into an earlier copy of `target_modules`. > > Behavioral notes: > - With `set_is_last_backward(False)` and default `reshard_after_backward=True`, > intermediate microbatches previously retained the stale prefetch's > `_all_gather_result` across microbatch boundaries and reused it on the next > forward's `unshard`. Skipping the stale prefetch moves that all-gather back > to the next forward (same total all-gather count on intermediate > microbatches, lower peak memory across forward, different overlap window) > while eliminating the wasted all-gather on the final microbatch. > - `TestFullyShardCudaGraph.test_pending_backward_prefetch_cleanup_cudagraph` > previously relied on the stale backward prefetch bug to leave a pending > all-gather for `finalize_backward`; it now uses explicit backward misprefetch > (`set_modules_to_backward_prefetch`) to keep testing #199677's CUDA graph > cleanup path. > > Test Plan > > ``` > python test/distributed/_composable/fsdp/test_fully_shard_training.py -f -v \ > -k test_pending_backward_prefetch_cleanup_cudagraph \ > -k test_manual_backward_finalization_rejects_shared_context_overlap > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -f -v \ > TestFSDPCommContext \ > TestFullyShardPrefetch.test_backward_prefetch_with_gradient_accumulation \ > TestFullyShardPrefetch.test_fully_shard_backward_prefetch \ > TestFullyShardPrefetch.test_backward_misprefetch \ > TestFullyShardPrefetch.test_unused_backward_prefetch_with_post_forward_mesh > ``` > > Ran on 4 B200s at base `192f70c27af`: > - `test_fully_shard_training.py`: 2/2 passed (including > `test_pending_backward_prefetch_cleanup_cudagraph` and > `test_manual_backward_finalization_rejects_shared_context_overlap`). > - `test_fully_shard_comm.py`: 8/8 passed (all 4 `TestFSDPCommContext` tests > plus `TestFullyShardPrefetch` covering gradient accumulation with exact > per-microbatch prefetch assertions across implicit/explicit prefetch, > deferred vs. per-microbatch reshard, detached unused submodules, 1F1B > pipelining `F0,F1,B0,F2,B1,B2`, multi-param-group accumulation, > `use_reentrant=True` AC, `_test_backward_prefetch_unused_in_backward`, > `test_backward_misprefetch`, and > `test_unused_backward_prefetch_with_post_forward_mesh`). ghstack-source-id: e7ce8fd Pull-Request: #200476
Stack from ghstack (oldest at bottom):
FSDPParamGroup.finalize_backward may clean up an all-gather launched by backward prefetch but never consumed. It recorded a device-specific event and waited through torch.accelerator.current_stream(), whose generic Stream.wait_event does not handle that device-specific event correctly during CUDA graph capture. The all-gather stream remained unjoined, so capture failed with cudaErrorStreamCaptureUnjoined.
Use FSDP device handle for the wait, matching every other FSDP wait_event call. Add a FakePG CUDA graph gradient accumulation test that leaves a prefetched all-gather pending at finalization and replays the graph.
Test Plan
Authored with an AI assistant.