Skip to content

[fsdp] Don't re-gather the head group after ChunkedLossWrapper - #6454

Open
francesco-bertolotti wants to merge 4 commits into
pytorch:mainfrom
francesco-bertolotti:f14-no-regather-lmhead
Open

francesco-bertolotti wants to merge 4 commits into
pytorch:mainfrom
francesco-bertolotti:f14-no-regather-lmhead

Conversation

@francesco-bertolotti

Copy link
Copy Markdown
Collaborator

Summary (human-written)

There is one extra all-gather per microbatch when using the chunked cross-entropy loss with FSDP. Here's how it happens:

  • layer.0 forward
  • ...
  • layer.N forward
  • final norm forward
  • model.forward ends with the post-norm hidden state
  • chunked cross entropy runs (forward and backward through the lm_head)
  • chunked cross entropy reshards the lm_head's FSDP group
  • final norm backward runs. The group was resharded by the chunked cross-entropy loss, so FSDP gathers it again. The final norm and the lm_head are in the same FSDP group (with tied weights, the group also includes tok_embeddings), so the whole group is re-gathered.
  • final norm backward ends and FSDP reshards the group (if reshard_after_backward is set).

The fix is simple. Instead of always resharding after the chunked loss, the loss reshards only when the head group is set to reshard after forward (fsdp_reshard_after_forward="always"), or when no decoder backward follows (e.g. eval). Otherwise the group stays gathered, the final norm's backward reuses it, and FSDP reshards the group itself when that backward ends.

To be fair I saw that are open PR in both titan and pytorch for this very same issue. So this might be considered as temporary fix. What it remains are the tests that check the number of gathers which shoud avoid future regressions on this side.

Why

apply_fsdp_to_decoder shards the head as fully_shard([norm, lm_head]) (or [tok_embeddings, norm, lm_head] when tied), not resharded after forward by default. ChunkedLossWrapper reshards it after the chunked head passes, and the decoder's backward starts with norm, so FSDP all-gathers the head again right away: one wasted full-lm_head gather per microbatch (about 1 GiB for Llama3-8B).

                          main                 this PR
model forward (norm)      all-gather head      all-gather head
chunked loss              reuse, reshard       reuse, keep gathered
decoder backward (norm)   all-gather again     reuse, then reshard

What changed

  • torchtitan/distributed/fsdp_lifecycle.py: when an outer backward follows and the group doesn't reshard after forward (post_forward_mesh_info is None), leave it gathered; the outer backward reshards it per reshard_after_backward. Other paths (reshard after forward, forward-only, pipeline) are unchanged.
  • tests/unit_tests/gpu/components/test_chunked_loss_fsdp.py: test_head_all_gathers runs the real Trainer (llama3, tied qwen3; fake comm backend, 1 GPU, 1 step of 2 microbatches) and checks the head's forward and backward gather counts for fsdp_reshard_after_forward x fsdp_defer_gradient_reduction.

Interim fix: draft #5946 moves this to FSDPModule.partial_backward (pytorch/pytorch#203961, draft), which deletes fsdp_lifecycle.py and also skips the re-gather under "always". The test marks those cases TODO(partial_backward).

Numerics

scripts/loss_compare.py --assert-equal, loss and grad_norm, 10 steps, main 2492504 vs. e6e356e, 4x A100-64GB: bitwise identical for FSDP 4 (llama3_debugmodel), HSDP 2x2, gradient accumulation (2 microbatches) and deferred reduction (muse_glimmer_debugmodel_fsdp2_deferred_gradient_reduction).

Performance

Head all-gathers per step (2 microbatches):

Case main this PR
llama3 fwd 2, bwd 2 fwd 2, bwd 0
llama3, deferred fwd 1, bwd 2 fwd 1, bwd 1
qwen3 (tied) fwd 2, bwd 2 fwd 2, bwd 0
qwen3 (tied), deferred fwd 1, bwd 1 fwd 1, bwd 0

Debug-model TPS and peak memory are unchanged within noise (small vocab, so this only shows no regression; not measured on a large-vocab model).

Testing

4x A100-64GB:

  • test_head_all_gathers: 8 passed; on main the 4 default cases fail with the extra backward gathers.
  • Existing TestChunkedLossFSDP (CPU and GPU) and test_loss.py: 41 passed.

Known issues

Self-review

pr-review (branch mode) at e6e356e: Needs discussion, since draft #5946 deletes fsdp_lifecycle.py. Not addressed: the "always" rule differs from #203961 (left to #5946); the fsdp_partial_backwards docstring doesn't mention that the group stays gathered for the outer backward.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Dec 1, 2026
@francesco-bertolotti francesco-bertolotti changed the title F14 no regather lmhead [fsdp] Don't re-gather the head group after ChunkedLossWrapper Dec 1, 2026
@francesco-bertolotti
francesco-bertolotti marked this pull request as ready for review December 1, 2026 15:58
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Dec 1, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the case where

  • there's no PP
  • fsdp_reshard_after_forward != "always"
  • no weight-tying

With https://github.com/pytorch/torchtitan/blob/main/torchtitan/distributed/fsdp.py#L446-L451, I would expect

  • one all-gather of [norm, lm_head] before norm
  • no all-gather inside ChunkedLossWrapper
  • no all-gather in backward for [norm, lm_head]

Does this match what this PR is doing?

Btw, how "deferrd" would change things?

@tianyu-l

tianyu-l commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 47s —— View job


Needs discussion -- review (correction: ignore the review's "fill in the human-written summary" line; that summary is already filled in).

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Needs discussion -- the 12-line fix is in the right owner and matches the expected gather schedule, but #5946 deletes this file and #6253 attacks the same re-gather by a different route. A maintainer should pick which one lands, and the new test needs to shrink.

Answer to @tianyu-l. Yes, it matches. Take no PP, fsdp_reshard_after_forward != "always", untied weights, no deferral. The test case (llama3, "default", False) -> {"forward": 2} covers 2 microbatches, so per microbatch it shows:

  • one head-group all-gather before norm,
  • none inside ChunkedLossWrapper (its module.unshard() is a no-op on an already-gathered group, and the test would count it under "forward"),
  • none in backward.

On main there is one extra backward gather per microbatch, because fsdp_lifecycle.py resharded unconditionally after the loss and norm backward re-gathered.

How deferred changes it. With fsdp_defer_gradient_reduction, training_engine.py:861 sets set_reshard_after_backward(is_last_accumulation_step). On non-last microbatches policy.reshard_after_backward is already False, so this PR changes nothing there: the group stays gathered from microbatch 0's forward through every backward. The only new case is the last microbatch: the loss leaves the group gathered, and norm's backward reshards it.

  • Ideal: 1 forward gather per step, 0 backward.
  • Measured on llama3: 1 forward gather plus 1 backward gather. That backward gather is a stale backward prefetch, the same on main, and fixed upstream by pytorch/pytorch#200476.
  • Tied qwen3 doesn't hit the stale prefetch.

Example. Llama3, FSDP, default policy, one microbatch:

                       main             this PR
norm fwd               AG [norm,head]   AG [norm,head]
chunked loss           reuse; reshard   reuse; keep
norm bwd               AG again         reuse
after norm bwd         reshard          reshard

Must fix

  • tests/unit_tests/gpu/components/test_chunked_loss_fsdp.py:79-126 -- This adds a GPU test that spawns 8 Trainer subprocesses and patches FSDP2's private foreach_all_gather. Extend the CPU test_accumulation_and_recovery with a dist.all_gather_single count instead (inline).
  • tests/unit_tests/gpu/components/test_chunked_loss_fsdp.py:32-40 -- The "always" and deferred cases pin counts this PR doesn't change, including an upstream bug. CI will fail when pytorch/pytorch#200476 lands (inline).

Should consider

  • torchtitan/distributed/fsdp_lifecycle.py:137-143 -- "Outer backward reshards it" holds only when the head shares a group with norm or tok_embeddings. A head-only group (CPU separate layout, or #6253's split) would now stay gathered through the whole decoder backward (inline, unverified).

Questions

  • For maintainers: land this as an interim fix before #5946, given that #5946 is blocked on pytorch/pytorch#203961 reaching a nightly? And should #6253 (split norm/lm_head into separate FSDP units) be closed in favor of this, or vice versa? Combining the two hits the should-consider above.
Details
  • Gate. The problem is real on main: the author's counts show 1 extra head all-gather per microbatch in backward. The root cause is fsdp_partial_backwards resharding regardless of whether an outer backward reuses the group. fsdp_lifecycle.py is torchtitan's owner of that policy, so the layer is right for an interim fix.
  • Other paths, checked.
    • "always": post_forward_mesh_info is not None, so the group still reshards.
    • Forward-only or frozen decoder: outer_backward_follows=False, so it still reshards.
    • PP: the stage sets reshard_after_backward=False, so the condition never reshards anyway.
    • Manual finalization: unchanged.
  • Peak memory. On main the group was re-gathered immediately for norm backward. Keeping it gathered between the loss and norm backward therefore doesn't raise peak memory for the in-repo grouped and tied layouts.
  • Overlap search. I searched fsdp_lifecycle and ChunkedLossWrapper. Found: #5946 (deletes fsdp_lifecycle.py; partial_backward covers this and also "always"), #6253 (splits norm/head groups; also fixes "always"; adds a separate_chunked_lm_head flag), and #6011 (FlexShard chunked loss).
  • Smallest test. About 10 lines in the existing CPU test: wrap dist.all_gather_single around loss.backward() and assert zero head-sized gathers for grouped/tied and not deferred (deferred last-microbatch as well, if it passes without the stale prefetch).

Not verified: when FSDP2 reshards a head-only group that no outer-backward module uses (I couldn't read the installed FSDP2 source); GPU test results.

Before merge: fill in the human-written summary. A maintainer still needs to review (core torchtitan/distributed/).

Comment on lines +79 to +126
def test_head_all_gathers(recipe, reshard_after_forward, deferred, expected, tmp_path):
"""A head kept unsharded after forward is not re-gathered in backward."""
# Each Trainer runs in a fresh process, as in real training, so no process
# group or mesh state carries over between cases.
context = mp.get_context("spawn")
queue = context.Queue()
process = context.Process(
target=_count_head_all_gathers,
args=(recipe, reshard_after_forward, deferred, str(tmp_path), queue),
)
process.start()
process.join()
assert process.exitcode == 0
assert queue.get(timeout=10) == expected


def _count_head_all_gathers(
recipe, reshard_after_forward, deferred, dump_folder, queue
):
os.environ.update(NGPU="2", LOCAL_RANK="0")
config = recipe(seq_len=16)
config.comm.backend = "fake"
config.dump_folder = dump_folder
config.training.steps = 1
config.training.disable_accelerator_graphs = True
# Two microbatches on each of the two fake data-parallel ranks.
config.training.num_tokens_per_train_step = (
2 * 2 * config.training.num_tokens_per_microbatch_per_dp_rank
)
config.parallelism.fsdp_reshard_after_forward = reshard_after_forward
config.parallelism.fsdp_defer_gradient_reduction = deferred

# TODO: Counting relies on FSDP2 internals (_fsdp_param_group.foreach_all_gather,
# FSDPParam._param_fqn) and torch._C._current_graph_task_id. Move to a public
# counting point when https://github.com/pytorch/pytorch/pull/203764 removes
# FSDPParamGroup.
head_all_gathers = Counter()
all_gather = _fsdp_param_group.foreach_all_gather

def counting_all_gather(fsdp_params, *args, **kwargs):
# The tied weight's FQN is tok_embeddings.weight, so match the final
# norm, which is in the head group of both models.
if any(p._param_fqn.split(".")[0] in ("norm", "lm_head") for p in fsdp_params):
in_backward = torch._C._current_graph_task_id() != -1
head_all_gathers["backward" if in_backward else "forward"] += 1
return all_gather(fsdp_params, *args, **kwargs)

with patch.object(_fsdp_param_group, "foreach_all_gather", counting_all_gather):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Must fix (tests rule: prefer extending existing coverage). This adds a GPU test that spawns 8 full Trainer processes and counts gathers by patching FSDP2's private _fsdp_param_group.foreach_all_gather (plus _param_fqn and torch._C._current_graph_task_id). The PR itself says pytorch/pytorch#203764 removes that function, so the test breaks with the FSDP2 engine swap.

The invariant is already almost covered, and more cheaply. tests/unit_tests/cpu/components/test_chunked_loss_fsdp.py::test_accumulation_and_recovery runs the grouped and tied layouts with reshard_after_forward=False under gloo, with and without deferral, over 3 microbatches. It already wraps dist.reduce_scatter_single (cpu/.../test_chunked_loss_fsdp.py:365). Wrap dist.all_gather_single the same way around loss.backward() and assert that no head-group-sized gather happens in the non-deferred, non-frozen grouped/tied cases. #5946 already counts at dist.all_gather_single this way. That is about 10 lines on CPU, with no subprocess and no private patch, and you can delete this file's additions.

Comment on lines +32 to +40
# TODO(stale prefetch): The deferred llama3 cases count one wasted backward
# re-gather: on the last microbatch, the first group's backward prefetch
# targets the previous microbatch's head from a stale post-forward order.
# Remove it once https://github.com/pytorch/pytorch/pull/200476 lands.
# TODO(partial_backward): With FSDPModule.partial_backward
# (https://github.com/pytorch/pytorch/pull/203961), adopted by
# https://github.com/pytorch/torchtitan/pull/5946, a head group shared with
# norm stays gathered for the outer backward under "always" too, so the
# "always" cases lose norm's backward re-gather.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Must fix. Six of the eight cases ("always", and deferred llama3) pin exact gather counts that this PR doesn't change. They include the stale-prefetch gather that is a known upstream bug. When pytorch/pytorch#200476 lands in a nightly, {"forward": 1, "backward": 1} becomes {"forward": 1} and torchtitan CI fails because upstream got better. These cases don't guard this PR's change; they snapshot FSDP's prefetch behavior. Keep only the assertion this PR owns: no head-group re-gather in backward when the group doesn't reshard after forward. Drop the TODO(stale prefetch) / TODO(partial_backward) bookkeeping with the cases.

Comment on lines +137 to +143
# Before an outer backward, leave the weights as the module's own
# forward would: unsharded unless it reshards after forward. The
# outer backward reshards them after its own use (e.g. norm in
# fully_shard([norm, lm_head])) instead of all-gathering them again.
keep_for_outer_backward = (
outer_backward_follows and policy.post_forward_mesh_info is None
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should consider (unverified, FSDP internals). The comment says the outer backward reshards the group "after its own use". That only holds when the head's group contains a module that runs in the outer backward (norm, or tok_embeddings when tied).

Take a group that holds only lm_head: the separate layout in test_accumulation_and_recovery, or the norm/head split proposed in #6253. No outer-backward module triggers that group's post-backward, so it now stays fully gathered until the root's final backward callback reshards it, through the whole decoder backward. On main it is resharded right after the loss. For a large vocab that is a full lm_head held at backward peak.

No in-repo apply_fsdp_to_decoder layout hits this today, since the head is always grouped with norm. But the condition doesn't express "shared with an outer-backward module". Either restrict keep_for_outer_backward to that case, or state the assumption in the comment and the fsdp_partial_backwards docstring.

@tianyu-l tianyu-l left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideal: 1 forward gather per step, 0 backward.
Measured on llama3: 1 forward gather plus 1 backward gather. That backward gather is a stale backward prefetch, the same on main, and fixed upstream by pytorch/pytorch#200476.

Seems we should land that pytorch PR.

Could you fix remaining bot comments and merge?

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/fake-pg Run 1-GPU Fake PG integration tests CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants