Repository navigation
[fsdp] Don't re-gather the head group after ChunkedLossWrapper - #6454
francesco-bertolotti wants to merge 4 commits into
Conversation
There was a problem hiding this comment.
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]beforenorm - 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?
|
@claude review |
There was a problem hiding this comment.
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(itsmodule.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 privateforeach_all_gather. Extend the CPUtest_accumulation_and_recoverywith adist.all_gather_singlecount 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 withnormortok_embeddings. A head-only group (CPUseparatelayout, 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_headinto 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 isfsdp_partial_backwardsresharding regardless of whether an outer backward reuses the group.fsdp_lifecycle.pyis torchtitan's owner of that policy, so the layer is right for an interim fix. - Other paths, checked.
"always":post_forward_mesh_infois 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
mainthe group was re-gathered immediately fornormbackward. Keeping it gathered between the loss andnormbackward therefore doesn't raise peak memory for the in-repo grouped and tied layouts. - Overlap search. I searched
fsdp_lifecycleandChunkedLossWrapper. Found: #5946 (deletesfsdp_lifecycle.py;partial_backwardcovers this and also"always"), #6253 (splits norm/head groups; also fixes"always"; adds aseparate_chunked_lm_headflag), and #6011 (FlexShard chunked loss). - Smallest test. About 10 lines in the existing CPU test: wrap
dist.all_gather_singlearoundloss.backward()and assert zero head-sized gathers forgrouped/tiedandnot 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/).
| 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): |
There was a problem hiding this comment.
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.
| # 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. |
There was a problem hiding this comment.
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.
| # 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 | ||
| ) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
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:
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_decodershards the head asfully_shard([norm, lm_head])(or[tok_embeddings, norm, lm_head]when tied), not resharded after forward by default.ChunkedLossWrapperreshards it after the chunked head passes, and the decoder's backward starts withnorm, so FSDP all-gathers the head again right away: one wasted full-lm_headgather per microbatch (about 1 GiB for Llama3-8B).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 perreshard_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_gathersruns the realTrainer(llama3, tied qwen3; fake comm backend, 1 GPU, 1 step of 2 microbatches) and checks the head's forward and backward gather counts forfsdp_reshard_after_forwardxfsdp_defer_gradient_reduction.Interim fix: draft #5946 moves this to
FSDPModule.partial_backward(pytorch/pytorch#203961, draft), which deletesfsdp_lifecycle.pyand also skips the re-gather under"always". The test marks those casesTODO(partial_backward).Numerics
scripts/loss_compare.py --assert-equal, loss and grad_norm, 10 steps,main2492504 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):
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; onmainthe 4defaultcases fail with the extra backward gathers.TestChunkedLossFSDP(CPU and GPU) andtest_loss.py: 41 passed.Known issues
main; fixed upstream by [FSDP2] Skip stale backward prefetch targets with no pending backward pytorch#200476, markedTODO(stale prefetch)in the test.foreach_all_gather, which [FSDP2] Run fully_shard on the FlexShard engine runtime; delete FSDPParamGroup (AI-assisted) pytorch#203764 removes.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); thefsdp_partial_backwardsdocstring doesn't mention that the group stays gathered for the outer backward.