Skip to content

[Loss] Preserve caller FSDP policies across chunked backward - #5563

Merged
tianyu-l merged 15 commits into
pytorch:mainfrom
ZenAlexa:contrib/5408-chunked-loss-deferred-sync
Nov 4, 2026
Merged

tianyu-l merged 15 commits into
pytorch:mainfrom
ZenAlexa:contrib/5408-chunked-loss-deferred-sync

Conversation

@ZenAlexa

@ZenAlexa ZenAlexa commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

why

ChunkedLossWrapper runs several head-only backwards before decoder backward. main restores head sync unconditionally on the final chunk, overwriting the caller's FSDP and HSDP accumulation policies. an inner root callback can also reduce earlier decoder gradients before the current microbatch arrives.

pipeline schedules choose their backward policy after the loss runs. the wrapper now follows the schedule's manual-finalization owner from the first head pass, so GPipe, 1F1B and Interleaved1F1B all defer every head microbatch until schedule finalization, the same way PP no-sync already treats every other group on the stage.

what changed

  • keep runtime policy and grouped-forward handling in torchtitan/distributed/fsdp_lifecycle.py, shared by loss and validation. the loss loop uses before_last_forward and after_forward without private FSDP reads.
  • save and restore each group's reduction, replica all-reduce and reshard settings and the root's is_last_backward, including when a chunk raises.
  • keep decoder gradients, prefetched weights and root finalization out of the inner head-only backwards. outside manual finalization, retain pending-gradient detection so a shared norm/head group coalesces its accumulated gradients into one reduction.
  • defer head reduction unconditionally under manual pipeline finalization, including the first microbatch. parameter residency stays with the schedule. outside pipelines, preserve the caller's early-reshard policy and the unreduced-gradient lifetime.
  • complete partial grouped forwards for training with a frozen decoder and for evaluation cleanup. register root iteration reset after dynamic pipeline metadata inference on success and failure, preserving gradients between normal accumulated schedule steps.
  • replace the private-state mock with real FSDP lifecycle observations, including tuple multi-output unshard and reshard behavior.
  • regenerate the three A10G pipeline goldens whose head reduction order changes.

GraphTrainer's production path uses SimpleFSDP and keeps its separate reduction owner.

pipeline numerics and goldens

one reduction per step changes the head's fp32 summation order from RS(g0) + RS(g1) + ... to RS(g0 + g1 + ...). with bf16 parameters and fp32 reduction the drift stays around 1e-6 relative, steps 1 and 2 stay bitwise equal, and the first changed step is 4 for llama3_pp.txt and 3 for gpt_oss_pp.txt and deepseek_v3_cp_pp.txt.

e41cf117e imports the new A10G values from the "Baseline metrics in import file format" section of the models job at 636e16d and keeps the file headers. the main models job at 73c4ebdac ran the same 2.16.0.dev20261102+cu132 build and reproduced the previous goldens exactly, so the runner repeats across runs and the only change in the imported values is this reduction order. the models job on the current head is the second same-environment run of the new values.

the MI350X copies of the same three files need a ROCm run. ciflow/rocm on this PR would produce them here, otherwise they follow the #5423 refresh pattern, since integration_test_rocm.yaml runs these configs on every push to main.

test_dense_llama3_hsdp_graph_pp_vs_eager uses eager Interleaved1F1B PP as its baseline with rtol=1e-4 and atol=1e-5. its workflow is path-filtered to torchtitan/experiments/graph_trainer/** and won't run on this PR, and the observed drift sits well inside that tolerance, so the next scheduled main run covers it.

last-stage memory and throughput

four Hopper GPUs on one host (sm_90, 132 SMs, 139.8 GiB each, reported by nvidia-smi as NVIDIA L20X), PyTorch 2.16.0.dev20261102+cu130 with the CUDA 13.0 580.95.05 forward-compat user-mode driver on kernel driver 570.172.08. the host is shared and eight free GPUs weren't available, so the runs use FSDP2 dp_shard=2 × pp=2.

the model is the Llama3 8B shape (32 layers, dim 4096, vocab 128256) with flex attention, ChunkedLossWrapper, bf16 parameters, fp32 reduction, one 8192-token sequence per microbatch, eight microbatches per step and accelerator graphs off. each run trains 20 steps and reports the median per-rank throughput and step time after five warmup steps, plus the per-rank max_active and max_reserved memory over the run. main is 887d89561 (the following main commit only changes SFT goldens), and the PR arm is code-identical to the current head. main and PR alternate order across two repetitions.

schedule main tps/GPU PR tps/GPU main step PR step last-stage peak active last-stage peak reserved
1F1B 8939, 8951 9316, 9354 3.666, 3.661 s 3.518, 3.503 s 61.49 → 57.80 GiB 71.66 → 67.95 GiB
1F1B, 2 accumulation steps, fsdp_defer_gradient_reduction 9063, 9066 9418, 9425 7.231, 7.229 s 6.959, 6.954 s 61.49 → 57.80 GiB 71.67 → 67.95 GiB
Interleaved1F1B, 2 stages per rank 9242, 9259 9601, 9623 3.546, 3.539 s 3.413, 3.405 s 68.90 → 66.47 GiB 79.12 → 74.56 GiB
GPipe 2286, 2364 2251, 2438 14.33, 13.86 s 14.56, 13.44 s 128.93 → 127.72 GiB 134.88 → 134.88 GiB

1F1B and Interleaved1F1B gain about 4% throughput on every rank, and the deferred-accumulation row covers finalize_gradients=False across schedule steps with the same result. GPipe keeps all eight microbatches' activations live and runs at 96% of device memory, so its throughput spread is wider than any difference and stays inconclusive. the first-stage ranks peak at 68.75 GiB under 1F1B and 75.27 GiB under Interleaved1F1B in both arms, so the job-wide peak in these two layouts is unchanged and the reduction lands on the output stage. under GPipe the output stage sets the job-wide peak, and it goes from 128.93 to 127.72 GiB with the first stage at 126.53 GiB in both arms.

a 1F1B profiler step on the output-stage rank shows 33 all-gathers and 25 reduce-scatters on main against 17 and 17 with this change, with all-gather time going from 142.1 to 47.8 ms and reduce-scatter time from 98.6 to 90.1 ms. the first-stage rank runs 17 and 17 in both arms.

a six-step 1F1B memory snapshot on the output-stage rank shows where the difference comes from. main's peak holds 3.914 GiB of FSDP collective buffers, exactly the size of two fp32 copies of the 128256 × 4096 head gradient, and this change holds none at its peak. the other allocation categories at the peak stay within 0.4 GiB of each other, including 7.48 GiB from _fsdp_param.py:alloc_storage and 13.00 GiB from _restore_unsharded_grad_dtypes in both arms. the snapshot covers one profiled step, so its peaks of 54.00 and 50.32 GiB sit below the 20-step maxima with the same 3.68 GiB difference as the table. so in these runs keeping the head unsharded until finalization adds nothing at the peak, and main's per-microbatch head reduction is what places staging buffers on top of the live activations.

losses vary run to run in both arms at this learning rate, so these runs measure memory and speed only. numerics come from the lifecycle scenario and goldens above.

current integration and validation

merged main@2124d731b in c45720e4d. main stopped re-exporting ParallelismConfig from torchtitan.config, so the lifecycle scenario imports it from torchtitan.config.parallelism, and the partial-backward implementation is otherwise unchanged by the merge.

on macOS arm64, Python 3.13.18, PyTorch 2.16.0.dev20261026 and four Gloo ranks, the lifecycle scenario passed 56 combinations plus one real grouped, frozen-decoder, two-output scenario. the matrix covers FSDP and HSDP, GPipe and 1F1B, deferred finalization, frozen decoders, tied weights, caller-policy restoration, reset/retry and losses, gradients and updated parameters against a full-logits reference. each finalized pipeline accumulation performs two reduce-scatters for a trainable decoder or one for a frozen decoder, and an accumulation without finalization performs zero. the same reduction-count scenario fails on the previous e0029100edbb revision, where GPipe performs five reductions in the checked accumulation.

on the current head the lifecycle entry and the selected loss and pipeline regressions report 90 passed with one LoRA CPU FlexAttention case deselected, and changed-file pre-commit checks, including Pyrefly, pass.

GLOO_SOCKET_IFNAME=lo0 pytest tests/unit_tests/cpu/components/test_chunked_loss_fsdp.py -q
pytest tests/unit_tests/cpu/components/test_loss.py tests/unit_tests/cpu/distributed/test_pipeline_parallel.py -k 'not lora' -q

remaining merge gate

  • the models job on the current head should pass the regenerated A10G goldens.
  • MI350X goldens need the ROCm run above.
  • representative convergence beyond the 10-step goldens hasn't run on this revision.

upstream lifecycle trackers

  • pytorch/pytorch#203176 tracks scoped partial backwards and completion of repeated standalone grouped forwards, including frozen inputs and evaluation cleanup.
  • pytorch/pytorch#203177 tracks value-based policy snapshots and exact restoration, including independent HSDP replica all-reduce settings.
  • pytorch/pytorch#203178 tracks FSDP iteration reset after pipeline metadata inference.

all three include self-contained two-rank CPU reproductions on PyTorch 2.16.0.dev20261026. the related pipeline policy RFC owns broader configurable schedule reduction and residency policy, and this PR implements the existing schedule's finalization contract.

earlier GPU evidence

  • e0029100edbb, November 2 multi-GPU job on eight A10G with PyTorch 2.16.0.dev20261101+cu132 passed the prior 40-combination lifecycle scenario.
  • 65b11734, real-PG features job passed fsdp_deferred_gradient_reduction on two ranks and fsdp_pp_deferred_gradient_reduction on four ranks with recorded CUDA graphs, and fsdp_per_group_cuda_graph and shared_eval_cuda_graph passed in the fake-PG job.
  • 1bbb64b44, two H100 with deterministic algorithms, kept ordinary FSDP loss, gradients, grad norm and parameters bitwise equal across sixteen reduced-model configurations, and deferred eager reduce-scatters dropped from seven to three separate owners or two grouped owners.

these results retain their recorded revisions.

Copilot AI balanced review requested due to automatic review settings October 20, 2026 09:12
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 20, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 20, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@pytorch-bot

pytorch-bot Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@ZenAlexa

Copy link
Copy Markdown
Contributor Author

@tianyu-l could you approve the pending Lint, CPU Unit Test, and GPU Unit Tests workflows for this revision? The two-H100 deterministic comparison and deferred-reduction, CUDA Graph, and recovery results are in the description.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude explain the issue to me in simpler ways -- use example if it's helpful

also review the PR

@claude

claude Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 59s —— View job


Part 1 -- The problem, explained simply

Background: what deferred accumulation is trying to do. Say one optimizer step uses 3 microbatches (mb0, mb1, mb2). With defer_fsdp_gradient_reduction, TrainingEngine (training_engine.py:772-776) tells the FSDP root:

requires_gradient_sync reshard_after_backward is_last_backward
mb0, mb1 False False False
mb2 True True True

So each param group should keep its unsharded gradients locally through mb0 and mb1, then do one reduce-scatter per group during mb2's backward. With HSDP, set_requires_all_reduce(is_last) works the same way for the replica all-reduce.

What ChunkedLossWrapper does inside one microbatch. It splits the sequence into N chunks and runs a separate chunk_loss.backward() for each chunk, only through lm_head, because the hidden states are detached. After the loop, the decoder backward runs once, as a separate autograd pass.

That gives N+1 backward passes per microbatch, and FSDP treats each one as a full backward.

Bug A: the wrapper overwrites the caller's settings. On main, the wrapper does this:

lm_head.set_requires_gradient_sync(False)     # chunks 0..N-2
...
lm_head.set_requires_gradient_sync(True)      # final chunk, unconditionally
...
lm_head.set_reshard_after_backward(True)      # after the loop, unconditionally

Example: on mb0 the engine says "don't sync", but the wrapper turns sync on for lm_head anyway. So lm_head reduce-scatters on every microbatch, and deferral never applies to it. set_requires_gradient_sync(True) also turns all_reduce_grads back on, which undoes the engine's HSDP set_requires_all_reduce(False). These are mostly wasted collectives. The math is still right, since the sum of reductions equals the reduction of the sum.

Bug B: an inner chunk backward reduces the decoder too early. When an autograd pass touches any FSDP module, FSDP's root post-backward callback runs over every group in the root context, not just lm_head. On mb2 (sync=True), the decoder groups are still holding unsharded grads from mb0 and mb1. So:

mb2, chunk-0 backward (lm_head only)
  -> root final callback visits decoder groups
  -> they have pending mb0+mb1 grads and sync=True
  -> reduce-scatter now                         <- reduction #1
mb2, decoder backward
  -> mb2 grads arrive -> reduce-scatter again   <- reduction #2

Each decoder group gets reduced twice instead of once, plus an early is_last_backward finalize. That matches the "7 reduce-scatters -> 3" numbers in the description.

Bug C: a grouped fully_shard([norm, lm_head]) with a frozen decoder. FSDP fires the group's post-forward, which registers the backward hooks, only after all modules in the group have run forward. The chunk loop only calls lm_head, so the group never finishes its forward. With a frozen decoder, the inputs don't require grad, so no input-side hook gets registered either. As a result, nothing triggers the group's backward lifecycle.

The PR's fix:

  1. Save each group's reduce/reshard policy and restore it on exit, including on exceptions, instead of hard-coding True.
  2. If any group already has pending grads (or HSDP partial state), keep sync off on all groups and set is_last_backward=False during the chunks. The outer decoder backward's root callback then reduces everything, including lm_head, exactly once.
  3. For case C, manually call FSDP's _post_forward so the output hook gets registered.

Part 2 -- Review

The diagnosis looks right to me, and I agree with the goal. My concerns are mostly about how the fix gets there.

1. Heavy dependence on FSDP2 private internals. This is the main concern. _chunked_loss_fsdp (loss.py:505-571) and the frozen-head branch (loss.py:~775) read and write these private attributes:

  • _get_fsdp_state, _lazy_init, _state_ctx.is_last_backward, _state_ctx.all_states, _auto_reshard_after_forward
  • on param groups: _fsdp_param_groups, post_forward_mesh_info, reduce_grads, all_reduce_grads, _post_backward_pending, _partial_reduce_output
  • state._post_forward(...) and _modules_to_run_forward.clear()

That is a lot of private state for a core component (Core Principle 1: this kind of complexity belongs upstream). Any FSDP2 refactor of these names or semantics would break it silently. The CPU tests won't catch that, because _RecordingFSDPLinear (test_loss.py:801-819) mocks the same private fields with a SimpleNamespace. Suggestions:

  • Upstream needs are really two narrow public APIs: (a) get/set policies as values, so they can be saved and restored, plus a "has pending unreduced grads" query; (b) a way to scope the root post-backward callback to one state, or a way to "complete a partial grouped forward". Could we open a PyTorch issue/PR and land this here with a TODO(<link>)?
  • At minimum, add a fail-fast check (e.g. hasattr on the private fields, with a clear error) so a PyTorch bump fails loudly instead of quietly doing the wrong thing.

2. Default HSDP behavior changes, but was only checked on CPU. In the HSDP default (non-deferred) mode, set_requires_all_reduce(False) on mb0..mbN-2 leaves _partial_reduce_output set. That makes defer_to_decoder True on mb1+ even without defer_fsdp_gradient_reduction. So the "default path is bitwise identical to main" claim applies to plain FSDP. For HSDP, the default path now uses the new deferral path on CUDA, and that hasn't been run natively (the description says native 4-GPU HSDP is unverified). Please run HSDP (dp_replicate>1) loss/grad_norm bitwise comparisons before merge.

3. Reshard before reduction on the last microbatch with deferral (loss.py:563-571). On mb2 with defer_to_decoder, the caller's reshard_after_backward is True. So group.reshard() runs on the lm_head groups at wrapper exit, before the outer callback's post_backward has reduced their unsharded grads. This relies on FSDP keeping unsharded_param.grad / unsharded_accumulated_grad alive and readable after to_sharded(). It apparently works on the tested nightly, but it's subtle and undocumented. Either skip the early reshard when defer_to_decoder (the outer post_backward already reshards), or add a comment explaining why it's safe.

4. The frozen-decoder grouped-head workaround (loss.py:~775-786).

  • Calling _post_forward by hand and clearing _modules_to_run_forward means faking FSDP's forward state machine. This seems like an FSDP limitation (a partially-run grouped forward gets no hooks), so it should be an upstream fix with a TODO.
  • It runs every chunk with a tuple of logits from all outputs. Please confirm that registering the output hook N times doesn't trigger N pre-backward unshards or N callback queues.
  • Is case C a bug on main today, i.e. are lm_head grads never reduced for head-only training with a grouped norm/head? If so, it deserves its own small PR and a regression test. It's separate from the policy-restoration fix.

5. Test coverage doesn't cover the new behavior. The test diff only adapts the existing mock. There's no checked-in test for:

  • caller policy restored after the wrapper (sync, reshard_after_backward, all_reduce, is_last_backward), including when an exception is raised mid-loop
  • defer_to_decoder being chosen when pending grads exist, and not chosen otherwise
  • the frozen-decoder grouped-head path

The description lists a lot of good ad-hoc verification (Gloo 2/4-rank, 2xH100), but none of it is in the repo. CLAUDE.md asks for CPU unit tests plus a GPU/multi-rank test for parallelism changes. The ciflow/fake-pg label is set; could some of the Gloo scenarios become fake-PG or multi-process tests? Something like "count reduce-scatters on the last microbatch with defer_fsdp_gradient_reduction + chunked loss" would lock in the 7->3 fix.

6. Audit sibling callsites. torchtitan/experiments/graph_trainer/chunked_loss.py:102,124 uses the same pattern: it restores with set_requires_gradient_sync(True, recurse=False) unconditionally, so it overrides the caller's policy and HSDP all_reduce_grads. GraphTrainer currently rejects FSDP2 deferred reduction (test_trace_module.py:163), so this may be moot there, but please confirm that HSDP gradient accumulation isn't affected.

7. Nits.

  • _chunked_loss_fsdp yields either None or a callable, and None is overloaded to mean both "not FSDP" and "deferred". A small enum or two explicit fields would read more clearly at loss.py:751-756.
  • policies stores 5-tuples that get unpacked as _, _, _ in three places. A small dataclass or NamedTuple would help.
  • The docstring sentence "Deferred accumulation retains the unsharded weights and gradients for the next microbatch" is accurate but vague about who reduces lm_head in the deferred case (the outer decoder backward's root callback). Worth stating that explicitly.
  • The isinstance(lm_head, FSDPModule) check is now done twice: in the context manager and in the per-chunk frozen-head branch.

Before merge, in addition to the author's request: run fsdp_deferred_gradient_reduction, fsdp_pp_deferred_gradient_reduction (PP's stage backward interacts with is_last_backward differently), fsdp_per_group_cuda_graph, shared_eval_cuda_graph, and an HSDP config with chunked loss.

Overall: the bugs are real and the numerical evidence is strong. My hesitation is the amount of private FSDP2 state being manipulated in core loss.py. I'd prefer narrowing this down: split the frozen-grouped-head fix (C) into its own PR, and pursue upstream public hooks for (1) and (4), tracked with a TODO.

I only read the code; I didn't run any tests (no torch or GPUs in this environment).

@ZenAlexa

Copy link
Copy Markdown
Contributor Author

The wrapper now preserves the caller's policies across the inner chunk backwards, so a three-microbatch step can keep its gradients together until decoder backward. Added real four-rank FSDP/HSDP CPU and GPU regressions for grouped and frozen heads, failures with pending gradients, and reset/retry; all 16 CPU combinations pass. The public sync setter also changes HSDP's separate all-reduce flag, so the policy snapshot remains in one private-state boundary. Kept early reshard and documented its ownership: the autograd leaf retains gradients after full weight storage is released; current native coverage and the two model-CI failures are recorded in the description.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude take another look

  • verify correctness
  • see if the readability and maintainability can be improved -- I feel there's room
  • give suggestions on what should go to upstream FSDP API

@claude

claude Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 7m 14s —— View job


Re-review: chunked-loss FSDP policy preservation

  • Gather context (diff vs 4103c72, FSDP2 call paths, engine/PP/fsdp.py callers)
  • Verify correctness
  • Readability / maintainability suggestions
  • Upstream FSDP API suggestions

I only read the code and traced FSDP2's root post-backward callback, post_backward, finalize_backward and the grouped-forward hooks by hand. torch isn't installed in this runner, so I couldn't check the private attribute names against the pinned nightly or run the tests.


1. Correctness

Correct as written

  • Bug B (decoder reduced too early) is real, and the defer path fixes it. In each inner chunk_loss.backward(), the root final callback calls post_backward() on every group in all_states that isn't already POST_BACKWARD. On the last microbatch, that reduce-scatters the decoder's pending mb0+mb1 gradients during chunk 0, and then again in decoder backward. In the defer path, every group has reduce_grads=False and reshard_after_backward=False, and is_last_backward=False. Those callbacks then only accumulate gradients, and decoder backward does a single reduction.
  • Early reshard with pending gradients (my earlier item 3) is safe. FSDP's own reduce_grads=False branch of post_backward calls reshard() before to_accumulated_grad_if_needed(). to_sharded() only frees all-gather storage, and _unsharded_param.grad survives. So the wrapper relies on the same contract FSDP relies on internally, and the new comment at loss.py:571-572 is accurate. Withdrawn.
  • Bug C (frozen decoder, grouped head) is real on main. Only chunk 0's logits finish the grouped forward. Chunks 1..N-1 get neither an output pre-backward hook nor an input post-backward hook, because frozen inputs carry no hook. Their lm_head gradients sit in unsharded_param.grad with nothing to reduce them. Calling _post_forward each chunk fixes this. Implicit prefetch indices stay balanced, because each chunk adds one post-forward index and its backward pops one.
  • Exception path. The finally block restores everything the setup touched. The test checks the policies both after a mid-loop failure and after reset_iter_state().

Needs attention before merge

(a) PP: what the wrapper preserves is the previous microbatch's policy. Under PP, ChunkedLossWrapper runs inside the last stage's forward step (loss computation). PyTorch pipelining sets the FSDP policy in backward_maybe_with_nosync, i.e. after the loss. On main, the wrapper force-reduces lm_head on every microbatch, so this didn't matter. With this PR, lm_head's reduction follows whatever the previous stage backward or the previous step's finalization left behind. The pending-gradient detection can also switch to the defer path partway through the schedule.

Mathematically it should still be correct, because PP's finalization reduces whatever is pending. But it changes how lm_head gradients are grouped into reductions, which changes floating-point summation order. My guess is that this explains the DeepSeek-V3 / GPT-OSS PP loss/grad-norm failures in the model job. I haven't confirmed it, and it needs a same-environment main-vs-PR rerun. If the comparison there is exact-match, the expected-numerics change needs to be stated and re-baselined. If it's tolerance-based, it's a real bug. Either way, it shouldn't land unexplained.

(b) Production uses only the grouped layout; the separate layout is test-only. torchtitan/distributed/fsdp.py:339-358 always does fully_shard([norm, lm_head]), or [tok_embeddings, norm, lm_head] with weight tying. The test matrix covers grouped, which is good. The tied 3-module group isn't covered, though: its group pre-forward fires on tok_embeddings, whose input is integer token ids, so no input post-backward hook gets registered. Please add a grouped_tied variant to the matrix, or at least run the weight-tied model through fsdp_deferred_gradient_reduction.

(c) A pre-existing perf issue that the defer path fixes only some of the time. With the default is_last_backward=True, chunk 0's root callback runs _finalize_backward() on all states. As I recall upstream (not checked against your nightly), that clears every decoder group's _post_forward_indices and the shared post_forward_order. Decoder backward would then lose implicit backward prefetch for every layer. The ep_degree > 1 path uses explicit prefetch (fsdp.py:510-520) and is unaffected. The defer path avoids this because it sets is_last_backward=False. The non-defer path, which is the default plain-FSDP step and the frozen-decoder case, still has it. Worth confirming with a trace: either way, it is a strong argument for §2.1.

(d) Test robustness. The test counts reductions by patching dist.reduce_scatter_single. Upstream FSDP2 has historically called dist.reduce_scatter_tensor. If CI's nightly uses a different entry point, the count assertion fails loudly, which is fine. Please confirm it runs in the CPU and GPU CI images, not just locally.


2. Readability and maintainability

There is room here. In rough order of impact:

2.1 Drop pending-gradient detection by always isolating the head pass (when decoder_requires_grad).
defer_to_decoder exists because the inner callbacks touch non-head groups. Mask those groups unconditionally instead:

# decoder_requires_grad: decoder backward follows in this microbatch and owns
# the root finalization. Inner head-only passes must not reduce, reshard or
# finalize any non-head group.
for group in non_head_groups:
    group.reduce_grads = False
    group.reshard_after_backward = False
state_ctx.is_last_backward = False
# head groups: reduce_grads=False until the final chunk, then the caller's policy (unchanged)
  • In the default plain-FSDP step, non-head groups have no gradients during chunks, so masking them changes nothing numerically. lm_head still reduces at the final chunk, overlapped with decoder backward, exactly as on main. The bitwise-identical default is preserved.
  • In deferred mode on the last microbatch, decoder groups can't reduce early, so bug B is fixed without the _post_backward_pending / _partial_reduce_output reads.
  • It also fixes (c) for every path, and stops a prefetched last block from being resharded and then re-gathered between chunk 0 and decoder backward.
  • It deletes the None | Callable yield and the mid-loop restore_gradient_sync() call. There is a single path when the decoder is trainable and a single path when it is frozen. The frozen path leaves the other groups and is_last_backward alone, since no decoder backward follows.
  • Cost: with a grouped [norm, lm_head] in deferred mode, the last microbatch does one extra small reduce-scatter (norm's mb2 gradient, in decoder backward), so the test would expect 3 instead of 2. I think that's worth it to drop the two private reads that encode FSDP's notion of "pending".

Fix this →

2.2 Put all private FSDP access behind one object, and move it to torchtitan/distributed/.
The PR description says the private accesses stay inside the chunked FSDP boundary. But the frozen-head _post_forward / _modules_to_run_forward workaround sits in __call__ (loss.py:778-788), which re-checks isinstance(lm_head, FSDPModule). It also duplicates post_validate_fsdp_for_cuda_graph (distributed/fsdp.py:57-59), which has a matching TODO: Use public FSDP APIs. Suggestion:

# torchtitan/distributed/fsdp.py
def finish_grouped_forward(module: FSDPModule, output: Any) -> Any: ...  # shared with post_validate_fsdp_for_cuda_graph

@contextmanager
def isolated_head_backward(head, *, run_backward, decoder_requires_grad) -> Iterator[HeadBackwardHooks]:
    ...

class HeadBackwardHooks:          # no-op implementation when head is not an FSDPModule
    def after_forward(self, output): ...   # frozen grouped head -> finish_grouped_forward
    def before_last_chunk(self): ...       # restore caller sync on head groups

Then loss.py is FSDP-agnostic. It needs no FSDPModule import or private access, and the chunk loop reads hooks.before_last_chunk() / logits = hooks.after_forward(logits). This follows the "model-agnostic parallelism helpers -> torchtitan/distributed/" rule, and the GraphTrainer variant could reuse the hooks interface later.

2.3 Smaller items

  • Replace the 5-tuples (unpacked as _, _, _ three times) with a @dataclass(slots=True) class _GroupPolicy that has snapshot(group) and restore(group) methods.
  • loss.py:566-569: name the condition, e.g. release_head_weights = reshard_after_backward or not run_backward # forward-only has no backward to reshard, and precompute head_groups = set(state._fsdp_param_groups) instead of a list membership test inside the loop.
  • The class docstring (loss.py:603-607) should say who reduces lm_head in each case: the final chunk when the decoder is frozen or nothing is pending; otherwise decoder backward via the group's post-backward hook or the root callback. "Deferred accumulation retains the unsharded weights and gradients" is still vague.
  • Most of the loss.py diff is re-indenting the chunk body. Pulling the per-chunk body into a _run_chunk(...) method would shrink both this diff and __call__.
  • Tests:
    • test_accumulation_and_recovery is a single 150-line method with closures, using raise RuntimeError instead of assertions. Split it into helpers (_build, _accumulate, _inject_failure, _check_against_reference), and use torch.testing.assert_close / self.assertEqual so failures show diffs.
    • _RecordingFSDPLinear in test_loss.py now rebuilds FSDP's private layout with SimpleNamespace. Those tests would pass even if FSDP renamed the fields. Now that the real-FSDP test exists, I'd trim the mock tests back to the event-order checks (unshard once, N forwards) and drop the policy assertions from them.

3. What belongs in the upstream FSDP API

Listed by how much private state each removes from torchtitan:

  1. A scoped "partial backward" for the root callback. This is the main one. For example: with fsdp_root.partial_backward(): or backward(..., fsdp_partial=True). Inside the scope, the root final callback only runs post_backward for states whose hooks actually fired, skips _finalize_backward, and leaves post_forward_order / _post_forward_indices alone. Chunked loss, PP's split-backward / zero-bubble, and any multi-pass backward need these semantics. It would remove the is_last_backward overwrite and the non-head group masking, and it would fix (c) upstream.
  2. Value-based policy snapshot and restore.
    policy = module.get_fsdp_policy(recurse=False)   # reduce_grads, all_reduce_grads, reshard_after_backward, reshard_after_forward (incl. int / mesh info)
    with module.fsdp_policy(requires_gradient_sync=False, reshard_after_forward=False, reshard_after_backward=False, recurse=False): ...
    Also decouple set_requires_gradient_sync from all_reduce_grads, or add a keep_all_reduce=True argument. Today set_requires_gradient_sync(True) silently undoes set_requires_all_reduce(False), which is the original HSDP part of bug A.
  3. Finishing a partial grouped forward. Either FSDPModule.finish_forward(output), or make a re-entrant call to one member of a fully_shard([a, b]) group register the output pre-backward hook on every call. This would replace both the frozen-head workaround here and post_validate_fsdp_for_cuda_graph.
  4. A documented contract that reshard() keeps unreduced gradients. FSDP already relies on this internally. Documenting it turns loss.py:571-572 into a contract instead of an observation.
  5. has_pending_gradients() / has_pending_partial_reduction(). Only needed if (1) doesn't land and §2.1 isn't adopted.

Each private access should get a TODO(<upstream issue link>) pointing at the item above that replaces it. Please open (1)–(3) as PyTorch issues, since they are the exit path for this code.


Summary

  • Correctness: the fixes for B and C are correct, and the early-reshard concern is resolved.
  • Blocking:
    • The PP loss/grad-norm failures need an explanation; (a) is my hypothesis.
    • The weight-tied 3-module group has no coverage.
    • The real GPU/HSDP runs listed in the description are still outstanding.
  • Maintainability: §2.1 removes the pending-gradient detection and the overloaded yield while keeping the default path bitwise-identical. §2.2 actually puts all private FSDP access in one place, in torchtitan/distributed/.
  • Upstream: a scoped partial backward, value-based policy get/set (with the HSDP all-reduce decoupled), and grouped-forward completion.

Comment on lines +517 to +523
# Metadata inference runs a real backward. Discard its unreduced FSDP
# gradients as well as the sharded gradients cleared by the stage.
for stage in stages:
if isinstance(stage.submod, FSDPModule):
schedule.register_post_metadata_inference_cleanup(
stage.submod.reset_iter_state
)

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 this be in upstream pytorch pipelining code or should it be here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this belongs in upstream PipelineStage cleanup.I kept the registration here cuz preserving deferred reduction leaves metadata-probe state outside param.grad, and the first real step needs that state cleared.

main forces head sync on in the last chunk, which clears that state early, so the cleanup needs to stay with this fix

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

tracked the cleanup in pytorch/pytorch#203178 with a standalone reproduction. the local registration keeps discarded metadata-probe gradients out of the first training step until PipelineStage owns that reset.

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 this be a separate file, or should it be included in fsdp.py, or is it worth creating a folder for fsdp/

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think should keep it separate since this file owns runtime state and fsdp.py owns sharding setup

both loss and validation use it, and keeping the private accesses here gives the upstream replacement one place to remove

added the module docstring and moved the grouped-forward TODO to the helper that owns it

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude reivew my latest comments

@claude

claude Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 59s —— View job


Replies to your three inline comments

  • Read the current diff of fsdp_lifecycle.py, fsdp.py, pipeline_parallel.py and loss.py
  • Traced the callers and the existing register_post_metadata_inference_cleanup users
  • Answers below

I couldn't import torch in this runner (permission prompt), so I haven't checked the upstream pipelining and FSDP source on the pinned nightly. The points about upstream internals below come from reading the code and from memory.


1. pipeline_parallel.py:517-523: should the metadata-inference cleanup be upstream or here?

It belongs upstream in the long run. Keep it here as a stopgap with a TODO.

  • The hook API is already upstream. register_post_metadata_inference_cleanup is a method on the PyTorch schedule; torchtitan doesn't define it. Dist-MoE already uses it (models/common/dist_moe/runtime.py:396-402). So the only open question is who registers the FSDP cleanup.
  • The bug comes from PipelineStage and FSDPModule interacting, not from torchtitan. Metadata inference runs a real backward. The stage then clears the sharded .grad, but it doesn't touch FSDP's per-iteration state: unsharded or accumulated grads kept under reduce_grads=False, and pending post-backward state. Upstream stage.py already special-cases FSDPModule (backward_maybe_with_nosync, and the manual reduce/finalize at the end of a step). The cleanup should live in that same file, next to the existing grad clearing, e.g. if isinstance(self.submod, FSDPModule): self.submod.reset_iter_state(). Then every PipelineStage + FSDP2 user gets the fix, not only torchtitan.
  • Until then, here is the right place. _build_pipeline_schedule is the one spot where the schedule and stages meet, and GraphTrainer (SimpleFSDP) is unaffected because the isinstance check filters it out. Suggestions:
    • Add a TODO(<pytorch issue>) stating that PipelineStage should reset FSDPModule iteration state after metadata inference.
    • Reword the comment so it says why the stage's own cleanup isn't enough, e.g. "The stage clears param.grad, but FSDP keeps unreduced unsharded grads and pending post-backward state outside param.grad when reduction is deferred."
  • Scope question for the author: can this leak happen on main (plain FSDP+PP with defer_fsdp_gradient_reduction)? Or only with this PR's defer_head_reduction under manual_backward_finalization?
    • If it happens on main: it's an independent correctness fix and should be its own small PR with its own test. That also keeps this PR's PP numerics story clean.
    • If it only happens with this PR: say so in the comment. Otherwise a reader can't tell why chunked loss requires a PP change.

2. fsdp_lifecycle.py: separate file, merge into fsdp.py, or a fsdp/ package?

Recommendation: keep it a separate file and don't create a package yet. Make the file's purpose explicit.

  • Two different kinds of code. fsdp.py is parallelize-time code: it applies fully_shard, picks meshes and reshard policies, and imports models.common.linear and models.common.moe. fsdp_lifecycle.py is runtime code that manipulates FSDP2 private state, which is the part you want to shrink and eventually delete. Keeping it in its own file means:
    • every private-API access in this PR sits in one ~130-line file, and loss.py no longer touches FSDP internals (good, matches the earlier §2.2 ask);
    • the upstream exit path is one file to delete, not scattered hunks in a 518-line fsdp.py;
    • it has no dependency on torchtitan.models. The dependency direction is already right: fsdp.py imports complete_fsdp_grouped_forward from it.
  • Why not a fsdp/ package: two files don't justify it. Turning torchtitan/distributed/fsdp.py into a package means churning or re-exporting every torchtitan.distributed.fsdp import across models and experiments. The other private-FSDP users (fsdp.py:410-416, rl/generator/vllm/model_wrapper.py, experiments/torchft/manager.py) are unrelated and shouldn't be pulled in by this PR. Revisit if a third runtime FSDP-state helper shows up in core.
  • Small follow-ups in the file:
    • Add a module docstring, e.g. "Runtime FSDP2 lifecycle helpers that depend on private FSDP state; each function names the upstream API that would replace it."
    • Move the TODO: Use public FSDP APIs for grouped eval cleanup from fsdp.py:52 onto complete_fsdp_grouped_forward, since that's now where the private access lives.
    • Give each function a TODO(<link>) that maps to the upstream items: (1) scoped partial backward, (2) value-based policy snapshot/restore with HSDP all-reduce decoupled, (3) grouped-forward completion.

3. fsdp_lifecycle.py:41: is chunked_loss_fsdp really tied to chunked loss?

The mechanism isn't tied to chunked loss; only the vocabulary is. What the context manager actually does, for one FSDP module:

  1. keeps it unsharded across several forward calls;
  2. runs several partial backwards that stop at detached inputs;
  3. stops those inner backwards from reducing, resharding or finalizing any other group in the root (is_last_backward=False, non-head groups masked);
  4. hands the reduction back to the caller's policy on the last pass, unless pending grads mean it should coalesce into the outer backward;
  5. restores every policy on exit.

That is exactly upstream item (1), "scoped partial backward". The same pattern applies to GraphTrainer's chunked loss, chunked MTP heads, or any detach-then-backward-a-submodule trick. Naming it after the eventual upstream concept lets a reader see what the private-state code stands in for, and makes the swap mechanical later.

Suggested renames:

current suggested
chunked_loss_fsdp fsdp_partial_backwards (or isolated_fsdp_partial_backwards)
lm_head param module
decoder_requires_grad outer_backward_follows. This is the real meaning: another backward through the root follows and owns finalization.
_ChunkedLossHooks PartialBackwardHooks
before_last_chunk before_last_backward
defer_head_reduction defer_to_outer_backward

If you'd rather keep it chunked-loss-specific, that's defensible too, since the before_last_chunk contract is tailored to it. In that case the current name is honest, but the docstring should say so explicitly: "Assumes module is the only FSDP module run in the inner passes and that all inner passes precede a single outer backward."

A related readability nit from the earlier review that's still open: the context manager yields None when the head isn't FSDP, so loss.py checks if fsdp is not None twice inside the chunk loop (loss.py:736, loss.py:756). Yielding a no-op PartialBackwardHooks instead removes both branches, and the loop body then reads the same with or without FSDP.


Summary:

  1. The PP cleanup should eventually live in upstream PipelineStage; keep it here with a TODO, and confirm whether it's actually a separate fix that's reachable on main.
  2. Keep fsdp_lifecycle.py as a separate file (no package), with a module docstring and upstream TODOs.
  3. The logic is generic, so I'd rename it after the "scoped partial backward" concept rather than chunked loss.

I only posted review comments; I made no code changes.

@tianyu-l

Copy link
Copy Markdown
Contributor

@ZenAlexa what claude says makes sense to me. Could you help address the final nits?

@tianyu-l
tianyu-l requested a review from weifengpy October 29, 2026 05:26
let the pipeline schedule own every head microbatch from its first forward,
retain its parameter residency, and preserve non-pipeline accumulation policy.
replace private-state mock checks with real grouped multi-output coverage and
link the lifecycle workarounds to their upstream trackers.

validation: four-rank Gloo lifecycle scenarios passed 56 combinations and the
multi-output case, 89 selected regressions passed with one LoRA case deselected,
and changed-file pre-commit checks passed. the old head reproduces five GPipe
reduce-scatters where the schedule-owned contract requires two. GPU model,
backend golden, memory, throughput and convergence checks remain pending.
integrate upstream 196b4a5 and keep the eight partial-backward patch
files unchanged. the four-rank lifecycle scenario and selected loss and
pipeline regressions pass on the combined tree.
@ZenAlexa

ZenAlexa commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

yep, the first head pass now follows the schedule's manual-finalization mode too, so every head microbatch waits for the schedule's reduction and parameter residency stays with the schedule. this removes the dependence on the previous backward's flags for both GPipe and 1F1B. the resulting summation-order change is intentional, and the remaining model checks and backend-specific golden regeneration are listed in the description.

non-head groups are already masked for every inner pass when decoder backward follows, and that keeps their gradients and prefetch state with the outer backward. the pending-gradient check now applies only outside manual finalization, where it keeps the shared norm/head group's accumulated gradients together for one reduction. restoring head sync on every last chunk would split that group's reduction again, so the check stays within this single lifecycle owner.

@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 40s —— View job


Request changes: the code now defers the head under PP as requested; merge still needs regenerated PP goldens and last-stage memory and throughput numbers from a GPU run. Review

@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: Request changes -- The lifecycle code now does what was asked: under PP, the head's reduction always waits for the schedule's finalization. What still blocks merge is evidence, not code. The PP goldens this intentionally breaks haven't been regenerated, and there are no last-stage memory or throughput numbers yet. Both need a GPU run that a maintainer has to trigger.

What changed since the last review (e002910 -> 636e16d). The real changes are in 049301b, which is a merge commit that also carries edits. 636e16d is a plain merge of main and leaves the PR files untouched.

  • fsdp_lifecycle.py:88-97: when the schedule finalizes backward manually (manual_backward_finalization), defer_reduction is now unconditionally True. The HSDP-only clause is gone.
  • fsdp_lifecycle.py:136-143: under manual finalization the wrapper no longer reshards the head after a backward. Residency follows the schedule's no-sync policy.
  • The before_last_backward hook is renamed to before_last_forward. TODOs now link pytorch/pytorch#203176, #203177 and #203178.
  • The SimpleNamespace mock tests in test_loss.py are deleted and replaced by a real-FSDP multi-output scenario. The PP matrix adds a plain-FSDP axis and asserts reduce-scatter counts at finalization.

Example. One stage holds decoder plus the grouped (norm, lm_head), runs 1F1B, and takes 3 microbatches (counts are reduce-scatters per step):

            F0        F1        F2        finalize      total
main        head RS   head RS   head RS   head+decoder  5
e002910     head RS   accum     accum     head+decoder  3   (GPipe: same as main)
636e16d     accum     accum     accum     head+decoder  2   (every schedule)

The expected_reductions check in test_chunked_loss_fsdp.py:191-199 asserts exactly this count (2, or 1 with a frozen decoder) for both GPipe and 1F1B.

Resolved since the last review

  • PP head deferral now depends on the schedule, not on the policy the previous action left behind (must-fix 1, code side).
  • The TODOs link upstream issues instead of comments on this PR (must-fix 2).
  • The _RecordingFSDPLinear private-state mock is removed.
  • The before_last_backward naming nit is fixed.
  • §2.1 (pending-gradient reads): the author explained that outside PP, the check keeps a shared [norm, lm_head] group's accumulated gradients in one reduction, and there was no pushback. Accepted.

Must fix

  1. Regenerate the PP goldens in this PR. The summation-order change now covers every PP + FSDP config that uses ChunkedLossWrapper, not just the two that failed before. llama3_fsdp+tp+pp passed on e002910 only because its schedule happened to reduce per microbatch. Expect it to drift now too (unverified). Per CLAUDE.md principle 6, every affected backend (A10G and MI350X) needs regenerated files, with the explanation already in the description. A maintainer needs to trigger the 8-GPU model job at 636e16d.
  2. Report last-stage peak memory and throughput on an 8-GPU PP config before and after.
    • Cost: the head's unsharded weight and accumulated gradient now stay alive from F0 until finalization. With finalize_gradients=False, they stay alive across schedule steps. Main resharded and reduced the head every microbatch.
    • Gain: the per-microbatch head all-gather and reduce-scatter go away.
    • This is the intended trade, and it matches what PP's no-sync already does to every other group on the stage. But it is a memory change on the main PP path, so it needs numbers.

Should consider

  • test_chunked_loss_fsdp.py still reports failures with raise RuntimeError(...) (for example at lines 195-199). self.assertEqual or torch.testing.assert_close would show diffs. This was raised earlier and is still open.
  • The PR description has grown into a revision-by-revision log, with evidence from e002910, 81b3eec, 142f595, 65b1173 and 1bbb64b. Trimming it to the current head's behavior, the before/after table above and the pending GPU gates would make it easier to verify.

A maintainer still needs to review, since this touches core loss and PP code.

Not verified:

  • that the upstream PipelineStage sets reshard_after_backward=False on non-final backwards (the memory claim in must-fix 2 rests on this);
  • whether llama3_fsdp+tp+pp now drifts;
  • the CPU, GPU and Lint runs at 636e16d, which were still queued or running at review time.

@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@claude I didn't see the expected PP numerics change in CI, why?

Also could you analyze what failed in CI?

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 53s —— View job


CI does show the PP numerics change. It's the reason the only failing job, 8 GPU Integration (Real PG, models) at 636e16d, fails. All three PP configs with a golden file now mismatch, and llama3_fsdp+tp+pp is one of them; it passed at e002910. The change is easy to miss because it is about 1e-6 relative, starts only at step 3 or 4, and lands in the same job that was already failing.

What failed

The job ran 14 tests: 11 passed and 3 failed. The 3 failures are golden mismatches (--assert-equal, exact match):

test schedule / microbatches first mismatch on e002910
llama3_fsdp+tp+pp 1F1B / 2 grad_norm step 4 (2.1186187 vs 2.1186206), loss step 5 passed
gpt_oss_pp+fsdp+cp+ep+sacop Interleaved1F1B / 8 loss and grad_norm step 3 failed from step 3
deepseek_v3_fsdp+cp+pp+ep Interleaved1F1B / 8 grad_norm step 3, loss step 4 failed from grad_norm step 6

Everything else passed: Lint, CPU unit tests, GPU unit tests, the real-PG features job and the fake-PG job. Nothing outside these three tests failed. The earlier deepseek_v4_dist_muon_fsdp+ep config error is also gone.

Why it's easy to miss

  1. It's the same job and two of the same tests as before. The check list looks unchanged. The new parts are that llama3_fsdp+tp+pp now fails and that DeepSeek-V3 drifts 3 steps earlier.
  2. llama3_fsdp+tp+pp is exactly the case that confirms the fix. With 1F1B and 2 microbatches, the head reductions per step are:
    main:     RS(g0) + RS(g1)    # head reduce-scatters each microbatch
    e002910:  RS(g0) + RS(g1)    # F0 reduces; g1 waits for finalize, still alone -> same as main
    636e16d:  RS(g0 + g1)        # one reduction at schedule finalization
    
    It passed on e002910 because that revision grouped the reductions exactly like main, and it fails now because the grouping really changed. This is the "head reduces once per step on every schedule" behavior you asked for.
  3. The drift is tiny and starts late. Steps 1-2 are bitwise equal in all three tests, and the gap stays around 1e-6 relative. My best explanation, not verified: the defaults are mixed_precision_param=bfloat16 and mixed_precision_reduce=float32. Summing a few bf16-valued gradients in fp32 is usually exact, so changing the order only changes a few elements. Small fp32 weight differences are also rounded away when the weights are cast to bf16 for the forward, until enough of them accumulate.
  4. The other PP tests have no golden files. kimi_k2_5_muon_pp+fsdp+ep, qwen3_5_moe_fsdp+tp+ep+pp, gpt_oss_pp+fsdp+ep+sacop and muse_glimmer_mm_tp+cp+pp+sp only check that training runs, so they pass whatever the numerics. Muse Glimmer has no FSDP anyway.
  5. The fake-PG job has no PP config, so it can't show this.
  6. It reported late. The run was created at 05:10 UTC but the models job only ran 12:47-13:18 UTC, so a check before then would have shown it pending.

What this means for merge

The CI result matches the intended change, so it isn't a new bug. To land it, these goldens need regenerating:

  • A10G: llama3_pp.txt, deepseek_v3_cp_pp.txt, gpt_oss_pp.txt. The job log already prints the new values in import-file format.
  • MI350X: the same three files. No MI350X run happened here, so those need a ROCm run.

The last-stage peak memory and throughput numbers from the previous review are still missing.

New A10G values from this run (from the "Baseline metrics in import file format" section of the log)

llama3_pp.txt (llama3_debugmodel_fsdp2_tp2_pp2, 8 GPUs):

1 8.009735107421875 1.4477896690368652
2 7.683945178985596 1.5535205602645874
3 7.142040252685547 1.555664300918579
4 6.181266784667969 2.1186187267303467
5 5.075373649597168 2.4585580825805664
6 4.70943546295166 2.239171266555786
7 4.471715450286865 1.9791001081466675
8 4.3873395919799805 1.8554835319519043
9 4.382715225219727 1.6733289957046509
10 4.196065902709961 1.6919898986816406

gpt_oss_pp.txt (gpt_oss_debugmodel_flex_fsdp2_cp2_pp2_ep4_sac):

1 7.947325706481934 42.14341354370117
2 5.397617340087891 12.37936019897461
3 5.166503429412842 3.94514799118042
4 4.561830997467041 2.7369089126586914
5 4.238156318664551 2.276972770690918
6 4.081898212432861 2.101266622543335
7 3.9613945484161377 1.8508731126785278
8 3.9131340980529785 1.6495610475540161
9 3.957181930541992 1.4691781997680664
10 3.9080262184143066 1.4215927124023438

deepseek_v3_cp_pp.txt: see the job log at line ~9720. The steps 1-2 values match the current golden.

The regenerated files should be checked against a second run on the same environment before they're committed, so they aren't one-off values.

I only read the CI logs and the test definitions. I didn't run anything or change any files.

@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@ZenAlexa could you do the two thing that claude suggested?

Regenerate the PP goldens in this PR.

I didn't check closely but the new golden should be in the CI failure.

Report last-stage peak memory and throughput on an 8-GPU PP config before and after.
Cost: the head's unsharded weight and accumulated gradient now stay alive from F0 until finalization. With finalize_gradients=False, they stay alive across schedule steps. Main resharded and reduced the head every microbatch.
Gain: the per-microbatch head all-gather and reduce-scatter go away.
This is the intended trade, and it matches what PP's no-sync already does to every other group on the stage. But it is a memory change on the main PP path, so it needs numbers.

It would be great if you could verify the perf, even on small scale.

integrate upstream 2124d73. the precision and parallelism config moves leave the
partial-backward implementation unchanged. main stopped re-exporting
ParallelismConfig from torchtitan.config, so the lifecycle test imports it from
torchtitan.config.parallelism.
the head now reduces once per pipeline step with the rest of its stage, so its
gradient sums microbatches locally before the reduce-scatter. take the new
values from the models job at 636e16d, which ran the same torch
2.16.0.dev20261102+cu132 build as the main job at 73c4ebd that reproduced
the previous goldens exactly. steps 1-2 or 1-3 are unchanged in every file.
@ZenAlexa

ZenAlexa commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

both are in now, e41cf117e regenerates the three A10G PP goldens from the 636e16d models job, and main's models job at 73c4ebd reproduced the old values bit for bit on the same torch build, so the new ones aren't one-off numbers and the only thing that moved is the head reduction order. the MI350X copies need a ROCm run, so if someone can add ciflow/rocm here i'll import them from that log into this PR and skip a #5423-style follow-up.

for perf there weren't 8 free GPUs on the box, so it's 4 Hopper GPUs with FSDP2 dp_shard=2 × pp=2 on the Llama3 8B shape at seq 8192 with 8 microbatches, and 1F1B, Interleaved1F1B and 1F1B with deferred accumulation each get about 4% more throughput and drop the output-stage peak by 3.7, 2.4 and 3.7 GiB. the memory snapshot shows that main's output-stage peak carries 3.9 GiB of FSDP collective buffers, which is exactly two fp32 copies of the head gradient, and the rest of the peak stays within 0.4 GiB between the two arms, so the longer head lifetime doesn't add anything at the peak. the first stage sets the job-wide peak under 1F1B and Interleaved1F1B and stays the same in both arms, so the job peak holds there. GPipe runs at 96% of device memory, its throughput difference is inside run-to-run noise, and its output stage sets the job peak and comes in 1.2 GiB lower. the full table, collective counts and setup are in the description.

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

@claude review again

The evidence sounds good enough to me.

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 21s —— View job


Approve, with one item before merging: the MI350X PP goldens still need a ROCm run. Review

@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: Approve -- please address the item below before merging. Both remaining blockers from the 11-03 review are now resolved. The A10G PP goldens were regenerated and pass on a second same-environment run, and the description now has last-stage memory and throughput numbers, which @tianyu-l accepted.

What changed since the last review (636e16d -> e41cf11).

  • c45720e merges main. The lifecycle, loss and PP code doesn't change. The only edits to PR files are test adjustments for main's config moves: the ParallelismConfig import path and PrecisionConfig() in two pipeline tests.
  • e41cf11 regenerates llama3_pp.txt, gpt_oss_pp.txt and deepseek_v3_cp_pp.txt under a10g/. The values match the ones the 636e16d models job printed. Steps 1-2 (1-3 for llama3) are unchanged, and the later steps move by about 1e-6 relative. That is the expected summation-order change RS(g0) + RS(g1) + ... -> RS(g0 + g1 + ...) for the head.

Example. For one stage holding decoder + (norm, lm_head) under 1F1B with 3 microbatches, the reduce-scatters per step are:

            F0        F1        F2        finalize      total
main        head RS   head RS   head RS   head+decoder  5
this PR     accum     accum     accum     head+decoder  2   (every schedule)

Resolved since the last review

  • PP goldens (A10G). On e41cf11, the 8 GPU models job reports "All losses are equal ... Assertion passed!" for llama3_fsdp+tp+pp, gpt_oss_pp+fsdp+cp+ep+sacop and deepseek_v3_fsdp+cp+pp+ep. That makes two runs of the new values, at 636e16d and e41cf11, and main at 73c4ebd reproduced the old values on the same torch build. Lint, CPU, GPU and fake-PG are green.
  • Last-stage memory and throughput. On 4x Hopper with dp_shard=2 x pp=2 and the Llama3-8B shape: 1F1B and Interleaved1F1B are about 4% faster, and output-stage peak memory drops by 2.4-3.7 GiB. The job-wide peak is unchanged, because the first stage sets it. The snapshot ties main's extra peak to the per-microbatch fp32 head-gradient collective buffers.

Must fix

  1. tests/assets/losses/real_pg/mi350x/{llama3_pp,gpt_oss_pp,deepseek_v3_cp_pp}.txt -- These are still the old values. integration_test_rocm.yaml runs these configs with exact-match goldens on every push to main, so the ROCm job turns red when this merges. Before merging, add ciflow/rocm and import the three files from that log. If that isn't possible, land the #5423-style refresh right after.

Should consider

  • tests/unit_tests/cpu/components/test_chunked_loss_fsdp.py:85,120,124,196,393-423 -- Failures are still reported with raise RuntimeError(...). Using self.assertEqual / torch.testing.assert_close would show the mismatching values. This is non-blocking.

A maintainer still needs to review, since this touches core loss and PP code.

Not verified: convergence beyond the 10-step goldens (the description lists it as not run on this revision), and the MI350X numerics.

@tianyu-l
tianyu-l merged commit 485c065 into pytorch:main Nov 4, 2026
felipemello1 pushed a commit to felipemello1/torchtitan that referenced this pull request Nov 5, 2026
From the "Baseline metrics in import file format" blocks of this PR's
ciflow/rocm run 41939381783 on 48c891c (models job). These are the
3 tests main's own ROCm job fails since pytorch#5563; every other MI350X
golden passed in that run, Muse Glimmer's included.
felipemello1 pushed a commit to felipemello1/torchtitan that referenced this pull request Nov 5, 2026
From the "Baseline metrics in import file format" blocks of this PR's
ciflow/real-pg run 41939378172 on 48c891c. Only these 3 tests failed
there and in the ciflow/fake-pg run's real-PG suite; Muse Glimmer
passed with main's values.
felipemello1 pushed a commit that referenced this pull request Nov 5, 2026
Conflicts: tests/assets/losses/real_pg/a10g/{deepseek_v3_cp_pp,gpt_oss_pp}.txt
(#5563 refreshed them on main). Took main's side; CI regenerates them.
felipemello1 pushed a commit that referenced this pull request Nov 5, 2026
Conflicts resolved so main's new behavior and this PR's sum-then-scale design both hold:
- #4819 (FLOPs per input batch): the graphable forward/backward returns (loss, metrics) and
  forward_backward builds ForwardBackwardResult with num_flops; kept, with this PR's single-argument
  _run_forward_backward. The core, GraphTrainer and TorchFT trainers keep main's FLOPs reduction and
  this PR's loss logging (sums divided by the step's loss tokens). TorchFT averages FLOPs over the
  replicas when ft_pg is set, also without DP or CP.
- #5779 (max_context_length from the model config): preprocess_inputs drops max_context_length and
  keeps aux_loss_denominators.
- #5563 (ChunkedLossWrapper keeps caller FSDP policies): main's chunked loop, without the count
  argument. test_chunked_loss_fsdp.py: losses are sums; the test divides gradients once by the loss
  tokens before comparing, as optim_step does.
- #5757/#5796 (SFT data change): sft.txt goldens taken from main; regenerated from CI next.
tianyu-l added a commit that referenced this pull request Nov 8, 2026
… order (#5943)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
#5563 changed the pipeline head's gradient reduction from `RS(g0) +
RS(g1) + ...`
to `RS(g0 + g1 + ...)` and regenerated the three A10G pipeline goldens.
Its
description noted that the MI350X copies of the same three files still
needed a
ROCm run. They were never refreshed, so `Integration Tests (ROCm)` has
failed on
every push to main since 485c065 (2026-11-04):

```
[llama3_fsdp+tp+pp]          loss mismatch at step 6: baseline=4.709461688995361, imported=4.7094831466674805
[gpt_oss_pp+fsdp+cp+ep+sacop] loss mismatch at step 4: baseline=4.553682804107666, imported=4.553784370422363
[deepseek_v3_fsdp+cp+pp+ep]   loss mismatch at step 5: baseline=4.468291282653809, imported=4.46826171875
RuntimeError: 3 integration test(s) failed
```

([latest failing models
job](https://github.com/pytorch/torchtitan/actions/runs/42412314917/job/128522936186),
at 6e5974a)

## What changed
Mechanical, test assets only:
`tests/assets/losses/real_pg/mi350x/{llama3_pp,gpt_oss_pp,deepseek_v3_cp_pp}.txt`
get their step rows from that job's "Baseline metrics in import file
format"
output. The file headers are unchanged.

## Numerics
The new values match the pattern #5563 described for A10G. The early
steps stay
bitwise equal, and the first changed step is 3–5, with drift around 1e-6
relative:

| File | First changed step | Steps 1..N-1 |
| --- | --- | --- |
| `llama3_pp.txt` | 5 (grad_norm) | bitwise equal |
| `gpt_oss_pp.txt` | 3 (grad_norm) | bitwise equal |
| `deepseek_v3_cp_pp.txt` | 4 (grad_norm) | bitwise equal |

The MI350X runner is reproducible. Every main push from 485c065
through
6e5974a (about 30 runs, several PyTorch nightlies) printed
bitwise-identical
baseline values for all three configs.

One value to look at: in `gpt_oss_pp.txt`, step 9 grad_norm goes from
1.466 to 2.028.
It is deterministic across those runs. The step 9 loss is essentially
unchanged
(3.957991 vs 3.958083), and step 10 grad_norm goes back to 1.444. That
points to
a one-step MoE spike on this tiny debug model, not a systematic
gradient-scale
change: a doubled head gradient would raise every step.

## Testing
None run locally (no MI350X). The ROCm models job on this PR should pass
with
the refreshed files (`ciflow/rocm`).
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. high priority

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants