Skip to content

[FSDP2] Support partial forward of [norm, head] for chunked loss - #180428

Closed
weifengpy wants to merge 27 commits into
gh/weifengpy/123/basefrom
gh/weifengpy/123/head
Closed

weifengpy wants to merge 27 commits into
gh/weifengpy/123/basefrom
gh/weifengpy/123/head

Conversation

@weifengpy

@weifengpy weifengpy commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

torchtitan wraps fully_shard([norm, lm_head]). Two execution patterns:

  • Full forward (no chunked loss): norm and lm_head run together
  • Chunked loss: the model forward runs norm-only. Then lm_head(chunk) is called standalone per chunk with per-chunk backward

Depending on _modules_to_run_forward to drive unshard/reshard is wrong
for the chunked-loss pattern

Changes

  1. Unshard gated on is_unsharded, not _modules_to_run_forward.
    The pre-hook unshards whenever the group isn't already unsharded,
    independent of _modules_to_run_forward

  2. Root post-forward cleanup for incomplete groups.
    _force_complete_incomplete_states runs at the root's
    post_forward

  3. Clear iter_forward_root in post-backward unconditionally.
    When model.lm_head(chunk) claims iter_forward_root via its
    pre_forward, the group's _post_forward never fires to clear it
    (partial group)

Why this design

Any call pattern that runs some submodule of the wrapped tree
leaves correctly reduced sharded grads after .backward() — across:

  • Normal model(x).backward().
  • Unused-param cases (some modules don't run).
  • Chunked-loss (standalone per-chunk calls).
  • Grad accumulation (set_requires_gradient_sync(False)).
  • Multiple forward passes before one backward.

chunked-loss fires N+1 reduce-scatters (one per chunk + one for
h.backward) instead of 1.

Users who know their pattern can reclaim the
single-RS behavior explicitly via set_requires_gradient_sync(False): see torchtitan pytorch/torchtitan#2937

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Apr 15, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ You can merge normally! (14 Unrelated Failures)

As of commit 773254b with merge base 12c7b75 (image):

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:

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

weifengpy added a commit that referenced this pull request Apr 15, 2026
We have `fully_shard([norm, head])` in torchtitan. Without chunked
loss, norm and head execute together — FSDP2 uses `_modules_to_run`
to unshard once before norm and reshard once after head.

With chunked loss, the model forward runs norm but skips head. Then
head is called standalone per chunk. It's wrong to depend on
`_modules_to_run` to trigger unshard/reshard.

Three changes:

1. Trigger unshard based on `is_unsharded`, regardless of
   `_modules_to_run`. `modules_to_run` is only used by the post-hook
   for reshard.

2. Root post-forward cleanup — force reshard and register backward
   hooks for incomplete `_modules_to_run_forward`.

3. Clear stale `iter_forward_root` in post-backward —
   `model.head(chunk)` claims forward root but never clears it because
   the group's `_post_forward` doesn't fire. Without this, iteration
   2+ skips root init.


ghstack-source-id: 98b413f
Pull-Request: #180428
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category labels Apr 15, 2026
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Apr 15, 2026
We have `fully_shard([norm, head])` in torchtitan. Without chunked
loss, norm and head execute together — FSDP2 uses `_modules_to_run`
to unshard once before norm and reshard once after head.

With chunked loss, the model forward runs norm but skips head. Then
head is called standalone per chunk. It's wrong to depend on
`_modules_to_run` to trigger unshard/reshard.

Three changes:

1. Trigger unshard based on `is_unsharded`, regardless of
   `_modules_to_run`. `modules_to_run` is only used by the post-hook
   for reshard.

2. Root post-forward cleanup — force reshard and register backward
   hooks for incomplete `_modules_to_run_forward`.

3. Clear stale `iter_forward_root` in post-backward —
   `model.head(chunk)` claims forward root but never clears it because
   the group's `_post_forward` doesn't fire. Without this, iteration
   2+ skips root init.

ghstack-source-id: d2eb4b8
Pull-Request: #180428
@weifengpy weifengpy changed the title Fix FSDP2 grouped module hooks for partial group forward (chunked loss) [FSDP2] Support partial group forward for chunked loss Apr 15, 2026
@weifengpy weifengpy changed the title [FSDP2] Support partial group forward for chunked loss [FSDP2] Support partial forward of [norm, head] for chunked loss Apr 15, 2026
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Apr 15, 2026
We have `fully_shard([norm, head])` in torchtitan. Without chunked
loss, norm and head execute together — FSDP2 uses `_modules_to_run`
to unshard once before norm and reshard once after head.

With chunked loss, the model forward runs norm but skips head. Then
head is called standalone per chunk. It's wrong to depend on
`_modules_to_run` to trigger unshard/reshard.

Three changes:

1. Trigger unshard based on `is_unsharded`, regardless of
   `_modules_to_run`. `modules_to_run` is only used by the post-hook
   for reshard.

2. Root post-forward cleanup — force reshard and register backward
   hooks for incomplete `_modules_to_run_forward`.

3. Clear stale `iter_forward_root` in post-backward —
   `model.head(chunk)` claims forward root but never clears it because
   the group's `_post_forward` doesn't fire. Without this, iteration
   2+ skips root init.

ghstack-source-id: 5ace01f
Pull-Request: #180428
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Apr 15, 2026
We have `fully_shard([norm, head])` in torchtitan. Without chunked
loss, norm and head execute together — FSDP2 uses `_modules_to_run`
to unshard once before norm and reshard once after head.

With chunked loss, the model forward runs norm but skips head. Then
head is called standalone per chunk. It's wrong to depend on
`_modules_to_run` to trigger unshard/reshard.

Three changes:

1. Trigger unshard based on `is_unsharded`, regardless of
   `_modules_to_run`. `modules_to_run` is only used by the post-hook
   for reshard.

2. Root post-forward cleanup — force reshard and register backward
   hooks for incomplete `_modules_to_run_forward`.

3. Clear stale `iter_forward_root` in post-backward —
   `model.head(chunk)` claims forward root but never clears it because
   the group's `_post_forward` doesn't fire. Without this, iteration
   2+ skips root init.

ghstack-source-id: 951552b
Pull-Request: #180428
@weifengpy
weifengpy requested review from tianyu-l and wwwjn April 15, 2026 04:57
@weifengpy
weifengpy marked this pull request as draft April 15, 2026 16:58
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Apr 17, 2026
We have `fully_shard([norm, head])` in torchtitan. Without chunked
loss, norm and head execute together — FSDP2 uses `_modules_to_run`
to unshard once before norm and reshard once after head.

With chunked loss, the model forward runs norm but skips head. Then
head is called standalone per chunk. It's wrong to depend on
`_modules_to_run` to trigger unshard/reshard.

Three changes:

1. Trigger unshard based on `is_unsharded`, regardless of
   `_modules_to_run`. `modules_to_run` is only used by the post-hook
   for reshard.

2. Root post-forward cleanup — force reshard and register backward
   hooks for incomplete `_modules_to_run_forward`. Extracted into
   `_force_complete_incomplete_states` helper.

3. Clear stale `iter_forward_root` in post-backward —
   `model.head(chunk)` claims forward root but never clears it because
   the group's `_post_forward` doesn't fire. Without this, iteration
   2+ skips root init. Cleared unconditionally (not gated on
   `is_last_backward`) so gradient-accumulation between micro-batches
   also recovers.

4. (Latent bug fix) `cast_forward_inputs` now applies to every module
   in a group. Previously the group pre-hook only fired on the first
   module, so non-first modules in `fully_shard([...])` skipped input
   mp_policy casting.

Co-authored-by: Claude <[email protected]>

ghstack-source-id: 9bd832f
Pull-Request: #180428
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Apr 17, 2026
We have `fully_shard([norm, head])` in torchtitan. Without chunked
loss, norm and head execute together — FSDP2 uses `_modules_to_run`
to unshard once before norm and reshard once after head.

With chunked loss, the model forward runs norm but skips head. Then
head is called standalone per chunk. It's wrong to depend on
`_modules_to_run` to trigger unshard/reshard.

Three changes:

1. Trigger unshard based on `is_unsharded`, regardless of
   `_modules_to_run`. `modules_to_run` is only used by the post-hook
   for reshard.

2. Root post-forward cleanup — force reshard and register backward
   hooks for incomplete `_modules_to_run_forward`. Extracted into
   `_force_complete_incomplete_states` helper.

3. Clear stale `iter_forward_root` in post-backward —
   `model.head(chunk)` claims forward root but never clears it because
   the group's `_post_forward` doesn't fire. Without this, iteration
   2+ skips root init. Cleared unconditionally (not gated on
   `is_last_backward`) so gradient-accumulation between micro-batches
   also recovers.

4. (Latent bug fix) `cast_forward_inputs` now applies to every module
   in a group. Previously the group pre-hook only fired on the first
   module, so non-first modules in `fully_shard([...])` skipped input
   mp_policy casting.

Co-authored-by: Claude <[email protected]>

ghstack-source-id: b7f1bf4
Pull-Request: #180428
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Apr 17, 2026
We have `fully_shard([norm, head])` in torchtitan. Without chunked
loss, norm and head execute together — FSDP2 uses `_modules_to_run`
to unshard once before norm and reshard once after head.

With chunked loss, the model forward runs norm but skips head. Then
head is called standalone per chunk. It's wrong to depend on
`_modules_to_run` to trigger unshard/reshard.

Changes:

1. Trigger unshard based on `is_unsharded`, regardless of
   `_modules_to_run`. `modules_to_run` is only used by the post-hook
   for reshard.

2. Root post-forward cleanup — force reshard, register backward
   hooks, and apply the inner state's ``mp_policy.output_dtype``
   cast for any incomplete `_modules_to_run_forward`. Extracted into
   `_force_complete_incomplete_states` helper (decorated
   `@_dynamo_disable`).

3. Clear stale `iter_forward_root` in post-backward —
   `model.head(chunk)` claims forward root but never clears it because
   the group's `_post_forward` doesn't fire. Without this, iteration
   2+ skips root init. Cleared unconditionally (not gated on
   `is_last_backward`) so gradient-accumulation between micro-batches
   also recovers.

4. (Latent bug fix) `cast_forward_inputs` now applies to every module
   in a group. Previously the group pre-hook only fired on the first
   module, so non-first modules in `fully_shard([...])` skipped input
   mp_policy casting.

5. Gate state-level one-shot work (``_root_pre_forward`` and
   ``_states_to_forward_prefetch``) on ``state_first_in_pass`` so
   per-module pre-hook firing (needed for #4) doesn't multiply
   forward-prefetch cost by group size. ``cast_forward_inputs`` and
   ``fsdp_param_group.pre_forward`` still fire per module as intended.

Co-authored-by: Claude <[email protected]>

ghstack-source-id: 592276e
Pull-Request: #180428
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Apr 17, 2026
We have `fully_shard([norm, head])` in torchtitan. Without chunked
loss, norm and head execute together — FSDP2 uses `_modules_to_run`
to unshard once before norm and reshard once after head.

With chunked loss, the model forward runs norm but skips head. Then
head is called standalone per chunk. It's wrong to depend on
`_modules_to_run` to trigger unshard/reshard.

Changes:

1. Trigger unshard based on `is_unsharded`, regardless of
   `_modules_to_run`. `modules_to_run` is only used by the post-hook
   for reshard.

2. Root post-forward cleanup — force reshard, register backward
   hooks, and apply the inner state's ``mp_policy.output_dtype``
   cast for any incomplete `_modules_to_run_forward`. Extracted into
   `_force_complete_incomplete_states` helper (decorated
   `@_dynamo_disable`).

3. Clear stale `iter_forward_root` in post-backward —
   `model.head(chunk)` claims forward root but never clears it because
   the group's `_post_forward` doesn't fire. Without this, iteration
   2+ skips root init. Cleared unconditionally (not gated on
   `is_last_backward`) so gradient-accumulation between micro-batches
   also recovers.

4. (Latent bug fix) `cast_forward_inputs` now applies to every module
   in a group. Previously the group pre-hook only fired on the first
   module, so non-first modules in `fully_shard([...])` skipped input
   mp_policy casting.

5. Gate state-level one-shot work (``_root_pre_forward`` and
   ``_states_to_forward_prefetch``) on ``state_first_in_pass`` so
   per-module pre-hook firing (needed for #4) doesn't multiply
   forward-prefetch cost by group size. ``cast_forward_inputs`` and
   ``fsdp_param_group.pre_forward`` still fire per module as intended.

Co-authored-by: Claude <[email protected]>

ghstack-source-id: 551b104
Pull-Request: #180428
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Apr 17, 2026
We have `fully_shard([norm, head])` in torchtitan. Without chunked
loss, norm and head execute together — FSDP2 uses `_modules_to_run`
to unshard once before norm and reshard once after head.

With chunked loss, the model forward runs norm but skips head. Then
head is called standalone per chunk. It's wrong to depend on
`_modules_to_run` to trigger unshard/reshard.

Changes:

1. Trigger unshard based on `is_unsharded`, regardless of
   `_modules_to_run`. `modules_to_run` is only used by the post-hook
   for reshard.

2. Root post-forward cleanup — force reshard, register backward
   hooks, and apply the inner state's ``mp_policy.output_dtype``
   cast for any incomplete `_modules_to_run_forward`. Extracted into
   `_force_complete_incomplete_states` helper (decorated
   `@_dynamo_disable`).

3. Clear stale `iter_forward_root` in post-backward —
   `model.head(chunk)` claims forward root but never clears it because
   the group's `_post_forward` doesn't fire. Without this, iteration
   2+ skips root init. Cleared unconditionally (not gated on
   `is_last_backward`) so gradient-accumulation between micro-batches
   also recovers.

4. (Latent bug fix) `cast_forward_inputs` now applies to every module
   in a group. Previously the group pre-hook only fired on the first
   module, so non-first modules in `fully_shard([...])` skipped input
   mp_policy casting.

5. Gate state-level one-shot work (``_root_pre_forward`` and
   ``_states_to_forward_prefetch``) on ``state_first_in_pass`` so
   per-module pre-hook firing (needed for #4) doesn't multiply
   forward-prefetch cost by group size. ``cast_forward_inputs`` and
   ``fsdp_param_group.pre_forward`` still fire per module as intended.

Co-authored-by: Claude <[email protected]>

ghstack-source-id: 7222048
Pull-Request: #180428
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Apr 17, 2026
We have `fully_shard([norm, head])` in torchtitan. Without chunked
loss, norm and head execute together — FSDP2 uses `_modules_to_run`
to unshard once before norm and reshard once after head.

With chunked loss, the model forward runs norm but skips head. Then
head is called standalone per chunk. It's wrong to depend on
`_modules_to_run` to trigger unshard/reshard.

Changes:

1. Trigger unshard based on `is_unsharded`, regardless of
   `_modules_to_run`. `modules_to_run` is only used by the post-hook
   for reshard.

2. Root post-forward cleanup — force reshard, register backward
   hooks, and apply the inner state's ``mp_policy.output_dtype``
   cast for any incomplete `_modules_to_run_forward`. Extracted into
   `_force_complete_incomplete_states` helper (decorated
   `@_dynamo_disable`).

3. Clear stale `iter_forward_root` in post-backward —
   `model.head(chunk)` claims forward root but never clears it because
   the group's `_post_forward` doesn't fire. Without this, iteration
   2+ skips root init. Cleared unconditionally (not gated on
   `is_last_backward`) so gradient-accumulation between micro-batches
   also recovers.

4. (Latent bug fix) `cast_forward_inputs` now applies to every module
   in a group. Previously the group pre-hook only fired on the first
   module, so non-first modules in `fully_shard([...])` skipped input
   mp_policy casting.

5. Gate state-level one-shot work (``_root_pre_forward`` and
   ``_states_to_forward_prefetch``) on ``state_first_in_pass`` so
   per-module pre-hook firing (needed for #4) doesn't multiply
   forward-prefetch cost by group size. ``cast_forward_inputs`` and
   ``fsdp_param_group.pre_forward`` still fire per module as intended.

Co-authored-by: Claude <[email protected]>

ghstack-source-id: 718ea74
Pull-Request: #180428
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

@weifengpy

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@weifengpy

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge -f “unrelated errors”

@pytorch-bot

pytorch-bot Bot commented Apr 24, 2026

Copy link
Copy Markdown

❌ 🤖 pytorchbot command failed:

@pytorchbot: error: unrecognized arguments: errors”

usage: @pytorchbot [-h]
                   
                   {merge,revert,rebase,label,drci,lint,fix-lint,apply-lint,cherry-pick}
                   ...

Try @pytorchbot --help for more info.

@weifengpy

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge -f ‘unrelated ci errors’

@pytorch-bot

pytorch-bot Bot commented Apr 24, 2026

Copy link
Copy Markdown

❌ 🤖 pytorchbot command failed:

@pytorchbot: error: unrecognized arguments: ci errors’

usage: @pytorchbot [-h]
                   
                   {merge,revert,rebase,label,drci,lint,fix-lint,apply-lint,cherry-pick}
                   ...

Try @pytorchbot --help for more info.

@weifengpy

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge -f "unrelated CI error"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

wwwjn added a commit to pytorch/torchtitan that referenced this pull request Apr 27, 2026
ChunkedCELoss implementation in eager.

## Implementation

When FSDP enabled:
~- separate [norm, lm_head] FSDP group: separate backward (lm_head,
decoder) will double fire reduce-scatters on the same FSDP module~ Need
pytorch/pytorch#180428 to be landed
- set_reshard_after_forward = false
- set_reshard_after_backward = false
- Reduce-scatter (SUM reduce) fires per-chunk for lm_head weights’
gradients
- h_chunk.grad is populated via plain autograd, collected by
GradAccumulator

When TP is enabled:
- If SP is applied, all-gather on TP mesh to be Replicate(). Local
tensor shape[B, L/N, D]
- Then Detach
- Apply chunk: chunk on sequence dimension. Local shape: [B, L/N, D]. 
- Calculate CE loss on each chunk sequentially. Loss parallel is applied
when calculating each chunk.

## Memory Profiling

Qwen3-0.6B model FSDP=4

w/o ChunkedLoss:
<img width="1920" height="610" alt="Screenshot 2026-04-14 at 3 47 00 PM"
src="https://github.com/user-attachments/assets/36f6f0d4-484c-4524-b143-cb98a6b33b2a"
/>

With ChunkedCELoss:
<img width="1920" height="610" alt="Screenshot 2026-04-14 at 3 45 44 PM"
src="https://github.com/user-attachments/assets/b80398f5-21e9-4007-9bbf-142e763f3060"
/>

## Compatibility Test
(llama3 debug model)

TP + no SP

TP + SP

CP 
<img width="564" height="294" alt="Screenshot 2026-04-14 at 2 38 59 PM"
src="https://github.com/user-attachments/assets/cc6e9062-54e4-4b0d-ae65-0d25eec1ed52"
/>

PP
- Not supported for now.  
- Waiting for #2972 to be
fixed


Compile 
<img width="565" height="268" alt="Screenshot 2026-04-14 at 4 14 19 PM"
src="https://github.com/user-attachments/assets/33825d6f-06ad-4026-a91b-684e5723e39e"
/>
@github-actions
github-actions Bot deleted the gh/weifengpy/123/head branch May 24, 2026 02:27
aperson30 pushed a commit to aperson30/pytorch that referenced this pull request Jun 20, 2026
…orch#180428)

torchtitan wraps `fully_shard([norm, lm_head])`. Two execution patterns:
- **Full forward** (no chunked loss): `norm` and `lm_head` run together
- **Chunked loss**: the model forward runs `norm`-only. Then `lm_head(chunk)` is called standalone per chunk with per-chunk backward

Depending on `_modules_to_run_forward` to drive unshard/reshard is wrong
for the chunked-loss pattern

## Changes

1. **Unshard gated on `is_unsharded`, not `_modules_to_run_forward`.**
   The pre-hook unshards whenever the group isn't already unsharded,
   independent of `_modules_to_run_forward`

2. **Root post-forward cleanup for incomplete groups.**
   `_force_complete_incomplete_states` runs at the root's
   `post_forward`

3. **Clear `iter_forward_root` in post-backward unconditionally.**
   When `model.lm_head(chunk)` claims `iter_forward_root` via its
   pre_forward, the group's `_post_forward` never fires to clear it
   (partial group)

## Why this design

Any call pattern that runs some submodule of the wrapped tree
leaves correctly reduced sharded grads after `.backward()` — across:

- Normal `model(x).backward()`.
- Unused-param cases (some modules don't run).
- Chunked-loss (standalone per-chunk calls).
- Grad accumulation (`set_requires_gradient_sync(False)`).
- Multiple forward passes before one backward.

chunked-loss fires N+1 reduce-scatters (one per chunk + one for
`h.backward`) instead of 1.

Users who know their pattern can reclaim the
single-RS behavior explicitly via `set_requires_gradient_sync(False)`: see torchtitan pytorch/torchtitan#2937

Pull Request resolved: pytorch#180428
Approved by: https://github.com/tianyu-l
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…orch#180428)

torchtitan wraps `fully_shard([norm, lm_head])`. Two execution patterns:
- **Full forward** (no chunked loss): `norm` and `lm_head` run together
- **Chunked loss**: the model forward runs `norm`-only. Then `lm_head(chunk)` is called standalone per chunk with per-chunk backward

Depending on `_modules_to_run_forward` to drive unshard/reshard is wrong
for the chunked-loss pattern

## Changes

1. **Unshard gated on `is_unsharded`, not `_modules_to_run_forward`.**
   The pre-hook unshards whenever the group isn't already unsharded,
   independent of `_modules_to_run_forward`

2. **Root post-forward cleanup for incomplete groups.**
   `_force_complete_incomplete_states` runs at the root's
   `post_forward`

3. **Clear `iter_forward_root` in post-backward unconditionally.**
   When `model.lm_head(chunk)` claims `iter_forward_root` via its
   pre_forward, the group's `_post_forward` never fires to clear it
   (partial group)

## Why this design

Any call pattern that runs some submodule of the wrapped tree
leaves correctly reduced sharded grads after `.backward()` — across:

- Normal `model(x).backward()`.
- Unused-param cases (some modules don't run).
- Chunked-loss (standalone per-chunk calls).
- Grad accumulation (`set_requires_gradient_sync(False)`).
- Multiple forward passes before one backward.

chunked-loss fires N+1 reduce-scatters (one per chunk + one for
`h.backward`) instead of 1.

Users who know their pattern can reclaim the
single-RS behavior explicitly via `set_requires_gradient_sync(False)`: see torchtitan pytorch/torchtitan#2937

Pull Request resolved: pytorch#180428
Approved by: https://github.com/tianyu-l
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…orch#180428)

torchtitan wraps `fully_shard([norm, lm_head])`. Two execution patterns:
- **Full forward** (no chunked loss): `norm` and `lm_head` run together
- **Chunked loss**: the model forward runs `norm`-only. Then `lm_head(chunk)` is called standalone per chunk with per-chunk backward

Depending on `_modules_to_run_forward` to drive unshard/reshard is wrong
for the chunked-loss pattern

## Changes

1. **Unshard gated on `is_unsharded`, not `_modules_to_run_forward`.**
   The pre-hook unshards whenever the group isn't already unsharded,
   independent of `_modules_to_run_forward`

2. **Root post-forward cleanup for incomplete groups.**
   `_force_complete_incomplete_states` runs at the root's
   `post_forward`

3. **Clear `iter_forward_root` in post-backward unconditionally.**
   When `model.lm_head(chunk)` claims `iter_forward_root` via its
   pre_forward, the group's `_post_forward` never fires to clear it
   (partial group)

## Why this design

Any call pattern that runs some submodule of the wrapped tree
leaves correctly reduced sharded grads after `.backward()` — across:

- Normal `model(x).backward()`.
- Unused-param cases (some modules don't run).
- Chunked-loss (standalone per-chunk calls).
- Grad accumulation (`set_requires_gradient_sync(False)`).
- Multiple forward passes before one backward.

chunked-loss fires N+1 reduce-scatters (one per chunk + one for
`h.backward`) instead of 1.

Users who know their pattern can reclaim the
single-RS behavior explicitly via `set_requires_gradient_sync(False)`: see torchtitan pytorch/torchtitan#2937

Pull Request resolved: pytorch#180428
Approved by: https://github.com/tianyu-l
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 ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: distributed (fsdp2) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants