Skip to content

[FSDP2] Skip stale backward prefetch targets with no pending backward - #200476

Draft
weifengpy wants to merge 10 commits into
gh/weifengpy/222/basefrom
gh/weifengpy/222/head
Draft

weifengpy wants to merge 10 commits into
gh/weifengpy/222/basefrom
gh/weifengpy/222/head

Conversation

@weifengpy

@weifengpy weifengpy commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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 [FSDP2] Join pending all-gather with device stream #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-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ No Failures, 107 Pending

As of commit 07762fe with merge base 192f70c (image):
💚 Looks good so far! There are no failures yet. 💚

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category labels Oct 10, 2026
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Oct 10, 2026
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: only the last backward's
> `_end_backward_iteration` clears it. 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. That is
> a no-op while the target is unsharded. But 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.
>
> The root's post-backward final callback now clears `post_forward_order` once
> no group holds a post-forward index, that is, once every recorded forward has
> run its backward. Under pipeline schedules, groups of microbatches whose
> backward hasn't run yet still hold indices, so the order is kept for them, as
> before. Clearing after every backward instead would drop their entries.
>
> Only the implicit backward prefetch popped a group's index, so a group with
> explicit backward prefetch (`set_modules_to_backward_prefetch`) kept its
> indices and the clear never ran. torchtitan sets explicit backward prefetch on
> the transformer blocks and the output projection, leaving only the first
> module implicit. `pre_backward` now pops the index under explicit prefetch
> too.
>
> Test Plan
>
> ```
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch
> ```
>
> `test_backward_prefetch_with_gradient_accumulation` runs with and without
> explicit backward prefetch on the later modules: no backward may unshard a
> module that the last microbatch's backward resharded. The implicit variant
> fails without the clear, and the explicit variant fails without the pop in
> `pre_backward`. The prefetch tests ran with this change on 4 H100s, on a build
> of 90ef23c plus #200179. All pass except
> `test_unused_backward_prefetch_with_post_forward_mesh`, which needs #199729
> and fails the same way on that build without this change.
>
> In torchtitan, on that build with this change, a half-scale run (8 H100s, 16
> accumulated microbatches, deferred reduction, 10 steps) has 10 all-gathers per
> step instead of 11, and no backward prefetch targets a sharded group. Loss and
> grad norm are bitwise equal to a run without the change, and step time and
> peak reserved memory are unchanged. A pipeline-parallel run (2 ranks x 8
> virtual stages, Interleaved1F1B, 16 microbatches) is bitwise equal as well.

ghstack-source-id: 17aa446
Pull-Request: #200476
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Dec 1, 2026
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: only the last backward's
> `_end_backward_iteration` clears it. 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. That is
> a no-op while the target is unsharded. But 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.
>
> The root's post-backward final callback now clears `post_forward_order` once
> no group holds a post-forward index, that is, once every recorded forward has
> run its backward. Under pipeline schedules, groups of microbatches whose
> backward hasn't run yet still hold indices, so the order is kept for them, as
> before. Clearing after every backward instead would drop their entries.
>
> Only the implicit backward prefetch popped a group's index, so a group with
> explicit backward prefetch (`set_modules_to_backward_prefetch`) kept its
> indices and the clear never ran. torchtitan sets explicit backward prefetch on
> the transformer blocks and the output projection, leaving only the first
> module implicit. `pre_backward` now pops the index under explicit prefetch
> too.
>
> Test Plan
>
> ```
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch
> ```
>
> `test_backward_prefetch_with_gradient_accumulation` runs with and without
> explicit backward prefetch on the later modules: no backward may unshard a
> module that the last microbatch's backward resharded. The implicit variant
> fails without the clear, and the explicit variant fails without the pop in
> `pre_backward`. The prefetch tests ran with this change on 4 H100s, on a build
> of 90ef23c plus #200179. All pass except
> `test_unused_backward_prefetch_with_post_forward_mesh`, which needs #199729
> and fails the same way on that build without this change.
>
> In torchtitan, on that build with this change, a half-scale run (8 H100s, 16
> accumulated microbatches, deferred reduction, 10 steps) has 10 all-gathers per
> step instead of 11, and no backward prefetch targets a sharded group. Loss and
> grad norm are bitwise equal to a run without the change, and step time and
> peak reserved memory are unchanged. A pipeline-parallel run (2 ranks x 8
> virtual stages, Interleaved1F1B, 16 microbatches) is bitwise equal as well.

ghstack-source-id: 5cdf9a8
Pull-Request: #200476
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Dec 1, 2026
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: only the last backward's
> `_end_backward_iteration` clears it. 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. That is
> a no-op while the target is unsharded. But 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.
>
> The root's post-backward final callback now clears `post_forward_order` once
> no group holds a post-forward index, that is, once every recorded forward has
> run its backward. Under pipeline schedules, groups of microbatches whose
> backward hasn't run yet still hold indices, so the order is kept for them, as
> before. Clearing after every backward instead would drop their entries.
>
> Only the implicit backward prefetch popped a group's index, so a group with
> explicit backward prefetch (`set_modules_to_backward_prefetch`) kept its
> indices and the clear never ran. torchtitan sets explicit backward prefetch on
> the transformer blocks and the output projection, leaving only the first
> module implicit. `pre_backward` now pops the index under explicit prefetch
> too.
>
> Test Plan
>
> ```
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch
> ```
>
> `test_backward_prefetch_with_gradient_accumulation` runs with and without
> explicit backward prefetch on the later modules: no backward may unshard a
> module that the last microbatch's backward resharded. The implicit variant
> fails without the clear, and the explicit variant fails without the pop in
> `pre_backward`. The prefetch tests ran with this change on 4 H100s, on a build
> of 90ef23c plus #200179. All pass except
> `test_unused_backward_prefetch_with_post_forward_mesh`, which needs #199729
> and fails the same way on that build without this change.
>
> In torchtitan, on that build with this change, a half-scale run (8 H100s, 16
> accumulated microbatches, deferred reduction, 10 steps) has 10 all-gathers per
> step instead of 11, and no backward prefetch targets a sharded group. Loss and
> grad norm are bitwise equal to a run without the change, and step time and
> peak reserved memory are unchanged. A pipeline-parallel run (2 ranks x 8
> virtual stages, Interleaved1F1B, 16 microbatches) is bitwise equal as well.

ghstack-source-id: 46cd0a9
Pull-Request: #200476
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Dec 2, 2026
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: only the last backward's
> `_end_backward_iteration` clears it. 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. That is
> a no-op while the target is unsharded. But 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.
>
> The root's post-backward final callback now clears `post_forward_order` once
> no group holds a post-forward index, that is, once every recorded forward has
> run its backward. Under pipeline schedules, groups of microbatches whose
> backward hasn't run yet still hold indices, so the order is kept for them, as
> before. Clearing after every backward instead would drop their entries.
>
> Only the implicit backward prefetch popped a group's index, so a group with
> explicit backward prefetch (`set_modules_to_backward_prefetch`) kept its
> indices and the clear never ran. torchtitan sets explicit backward prefetch on
> the transformer blocks and the output projection, leaving only the first
> module implicit. `pre_backward` now pops the index under explicit prefetch
> too.
>
> Test Plan
>
> ```
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch
> ```
>
> `test_backward_prefetch_with_gradient_accumulation` runs with and without
> explicit backward prefetch on the later modules: no backward may unshard a
> module that the last microbatch's backward resharded. The implicit variant
> fails without the clear, and the explicit variant fails without the pop in
> `pre_backward`. The prefetch tests ran with this change on 4 H100s, on a build
> of 90ef23c plus #200179. All pass except
> `test_unused_backward_prefetch_with_post_forward_mesh`, which needs #199729
> and fails the same way on that build without this change.
>
> In torchtitan, on that build with this change, a half-scale run (8 H100s, 16
> accumulated microbatches, deferred reduction, 10 steps) has 10 all-gathers per
> step instead of 11, and no backward prefetch targets a sharded group. Loss and
> grad norm are bitwise equal to a run without the change, and step time and
> peak reserved memory are unchanged. A pipeline-parallel run (2 ranks x 8
> virtual stages, Interleaved1F1B, 16 microbatches) is bitwise equal as well.

ghstack-source-id: ba282f2
Pull-Request: #200476
weifengpy added a commit that referenced this pull request Dec 2, 2026
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 or no-grad forwards) and would alter
> `finalize_backward(async_op=True)`'s cross-root overlap check -- this change
> skips stale targets per group in `_backward_prefetch`:
>
> `FSDPParamGroup.pre_backward` now pops `_post_forward_indices` in a single
> place before dispatching to `_backward_prefetch(curr_index)`, so groups with
> explicit backward prefetch (`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, i.e., the target still
> has a pending backward. Under pipeline schedules (multiple forwards before
> backwards), targets with pending backwards still hold indices and keep
> cross-forward prefetch intact. In the multi-param-group walk-back loop
> (`_num_param_groups > 1`), sibling groups of `curr_modules` are now 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 index/order state consistent: `post_forward`
> records into `post_forward_order` only when `torch.is_grad_enabled()`, since
> no-grad forwards never register pre-backward hooks; and
> `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` when the second root runs its
> first forward.
>
> Behavioral note: 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.
>
> Test Plan
>
> ```
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -f -v -k TestFSDPCommContext -k test_backward_prefetch_with_gradient_accumulation -k test_backward_prefetch_shared_comm_ctx_interleaved_roots
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -f -v -k test_manual_backward_finalization_rejects_shared_context_overlap
> ```
>
> Ran on 4 B200s at base `192f70c27af`: 7/7 passed in `test_fully_shard_comm.py`
> (covering `TestFSDPCommContext.test_lazy_init_is_idempotent`,
> `test_backward_prefetch_with_gradient_accumulation` with exact per-microbatch
> prefetch assertions across implicit/explicit prefetch, deferred vs.
> per-microbatch reshard, detached/no-grad submodules, single-root F-F-B-B, and
> multi-param-group accumulation, plus
> `test_backward_prefetch_shared_comm_ctx_interleaved_roots` without manual
> `_lazy_init`), and 1/1 passed in `test_fully_shard_training.py`.

ghstack-source-id: ba282f2
Pull-Request: #200476
@weifengpy weifengpy changed the title [FSDP2] Clear the stale post-forward order once every backward has run [FSDP2] Skip stale backward prefetch targets with no pending backward Dec 2, 2026
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Dec 2, 2026
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 or no-grad forwards) and would alter
> `finalize_backward(async_op=True)`'s cross-root overlap check -- this change
> skips stale targets per group in `_backward_prefetch`:
>
> `FSDPParamGroup.pre_backward` now pops `_post_forward_indices` in a single
> place before dispatching to `_backward_prefetch(curr_index)`, so groups with
> explicit backward prefetch (`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, i.e., the target still
> has a pending backward. Under pipeline schedules (multiple forwards before
> backwards), targets with pending backwards still hold indices and keep
> cross-forward prefetch intact. In the multi-param-group walk-back loop
> (`_num_param_groups > 1`), sibling groups of `curr_modules` are now 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 index/order state consistent: `post_forward`
> records into `post_forward_order` only when `torch.is_grad_enabled()`, since
> no-grad forwards never register pre-backward hooks; and
> `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` when the second root runs its
> first forward.
>
> Behavioral note: 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.
>
> Test Plan
>
> ```
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -f -v -k TestFSDPCommContext -k test_backward_prefetch_with_gradient_accumulation -k test_backward_prefetch_shared_comm_ctx_interleaved_roots
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -f -v -k test_manual_backward_finalization_rejects_shared_context_overlap
> ```
>
> Ran on 4 B200s at base `192f70c27af`: 7/7 passed in `test_fully_shard_comm.py`
> (covering `TestFSDPCommContext.test_lazy_init_is_idempotent`,
> `test_backward_prefetch_with_gradient_accumulation` with exact per-microbatch
> prefetch assertions across implicit/explicit prefetch, deferred vs.
> per-microbatch reshard, detached/no-grad submodules, single-root F-F-B-B, and
> multi-param-group accumulation, plus
> `test_backward_prefetch_shared_comm_ctx_interleaved_roots` without manual
> `_lazy_init`), and 1/1 passed in `test_fully_shard_training.py`.

ghstack-source-id: 4cd49a8
Pull-Request: #200476
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Dec 2, 2026
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
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Dec 2, 2026
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
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Dec 2, 2026
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
weifengpy added a commit that referenced this pull request Dec 2, 2026
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
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Dec 2, 2026
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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant