Repository navigation
[Loss] Preserve caller FSDP policies across chunked backward - #5563
Conversation
|
|
|
@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. |
|
@claude explain the issue to me in simpler ways -- use example if it's helpful also review the PR |
|
Claude finished @tianyu-l's task in 2m 59s —— View job Part 1 -- The problem, explained simplyBackground: what deferred accumulation is trying to do. Say one optimizer step uses 3 microbatches (mb0, mb1, mb2). With
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, What 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, unconditionallyExample: on mb0 the engine says "don't sync", but the wrapper turns sync on for 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 Each decoder group gets reduced twice instead of once, plus an early Bug C: a grouped The PR's fix:
Part 2 -- ReviewThe 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.
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
2. Default HSDP behavior changes, but was only checked on CPU. In the HSDP default (non-deferred) mode, 3. Reshard before reduction on the last microbatch with deferral ( 4. The frozen-decoder grouped-head workaround (
5. Test coverage doesn't cover the new behavior. The test diff only adapts the existing mock. There's no checked-in test for:
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 6. Audit sibling callsites. 7. Nits.
Before merge, in addition to the author's request: run Overall: the bugs are real and the numerical evidence is strong. My hesitation is the amount of private FSDP2 state being manipulated in core I only read the code; I didn't run any tests (no torch or GPUs in this environment). |
|
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. |
|
@claude take another look
|
|
Claude finished @tianyu-l's task in 7m 14s —— View job Re-review: chunked-loss FSDP policy preservation
I only read the code and traced FSDP2's root post-backward callback, 1. CorrectnessCorrect as written
Needs attention before merge (a) PP: what the wrapper preserves is the previous microbatch's policy. Under PP, Mathematically it should still be correct, because PP's finalization reduces whatever is pending. But it changes how (b) Production uses only the grouped layout; the separate layout is test-only. (c) A pre-existing perf issue that the defer path fixes only some of the time. With the default (d) Test robustness. The test counts reductions by patching 2. Readability and maintainabilityThere is room here. In rough order of impact: 2.1 Drop pending-gradient detection by always isolating the head pass (when # 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)
2.2 Put all private FSDP access behind one object, and move it to # 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 groupsThen 2.3 Smaller items
3. What belongs in the upstream FSDP APIListed by how much private state each removes from torchtitan:
Each private access should get a Summary
|
discard metadata-inference gradients before the first training microbatch and retain caller replica-reduction policy until manual finalization.
| # 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 | ||
| ) |
There was a problem hiding this comment.
should this be in upstream pytorch pipelining code or should it be here?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
should this be a separate file, or should it be included in fsdp.py, or is it worth creating a folder for fsdp/
There was a problem hiding this comment.
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
|
@claude reivew my latest comments |
|
Claude finished @tianyu-l's task in 1m 59s —— View job Replies to your three inline comments
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.
|
| 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:
- 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 onmain. - Keep
fsdp_lifecycle.pyas a separate file (no package), with a module docstring and upstream TODOs. - 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.
|
@ZenAlexa what claude says makes sense to me. Could you help address the final nits? |
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.
|
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. |
|
@claude review again |
There was a problem hiding this comment.
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_reductionis 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_backwardhook is renamed tobefore_last_forward. TODOs now link pytorch/pytorch#203176, #203177 and #203178. - The
SimpleNamespacemock tests intest_loss.pyare 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
_RecordingFSDPLinearprivate-state mock is removed. - The
before_last_backwardnaming 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
- 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+pppassed one002910only 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 at636e16d. - 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.
- Cost: the head's unsharded weight and accumulated gradient now stay alive from F0 until finalization. With
Should consider
test_chunked_loss_fsdp.pystill reports failures withraise RuntimeError(...)(for example at lines 195-199).self.assertEqualortorch.testing.assert_closewould 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,65b1173and1bbb64b. 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
PipelineStagesetsreshard_after_backward=Falseon non-final backwards (the memory claim in must-fix 2 rests on this); - whether
llama3_fsdp+tp+ppnow drifts; - the CPU, GPU and Lint runs at
636e16d, which were still queued or running at review time.
|
@claude I didn't see the expected PP numerics change in CI, why? Also could you analyze what failed in CI? |
|
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 What failedThe job ran 14 tests: 11 passed and 3 failed. The 3 failures are golden mismatches (
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 Why it's easy to miss
What this means for mergeThe CI result matches the intended change, so it isn't a new bug. To land it, these goldens need regenerating:
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)
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. |
|
@ZenAlexa could you do the two thing that claude suggested?
I didn't check closely but the new golden should be in the CI failure.
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.
|
both are in now, for perf there weren't 8 free GPUs on the box, so it's 4 Hopper GPUs with FSDP2 |
|
@claude review again The evidence sounds good enough to me. |
There was a problem hiding this comment.
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).
c45720emerges main. The lifecycle, loss and PP code doesn't change. The only edits to PR files are test adjustments for main's config moves: theParallelismConfigimport path andPrecisionConfig()in two pipeline tests.e41cf11regeneratesllama3_pp.txt,gpt_oss_pp.txtanddeepseek_v3_cp_pp.txtundera10g/. The values match the ones the636e16dmodels 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 changeRS(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!" forllama3_fsdp+tp+pp,gpt_oss_pp+fsdp+cp+ep+sacopanddeepseek_v3_fsdp+cp+pp+ep. That makes two runs of the new values, at636e16dande41cf11, and main at73c4ebdreproduced 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=2and 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
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.yamlruns these configs with exact-match goldens on every push to main, so the ROCm job turns red when this merges. Before merging, addciflow/rocmand 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 withraise RuntimeError(...). Usingself.assertEqual/torch.testing.assert_closewould 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.
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.
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.
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.
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.
… 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`).
why
ChunkedLossWrapperruns 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
torchtitan/distributed/fsdp_lifecycle.py, shared by loss and validation. the loss loop usesbefore_last_forwardandafter_forwardwithout private FSDP reads.is_last_backward, including when a chunk raises.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) + ...toRS(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 forllama3_pp.txtand 3 forgpt_oss_pp.txtanddeepseek_v3_cp_pp.txt.e41cf117eimports the new A10G values from the "Baseline metrics in import file format" section of the models job at636e16dand keeps the file headers. the main models job at73c4ebdacran the same2.16.0.dev20261102+cu132build 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/rocmon this PR would produce them here, otherwise they follow the #5423 refresh pattern, sinceintegration_test_rocm.yamlruns these configs on every push to main.test_dense_llama3_hsdp_graph_pp_vs_eageruses eager Interleaved1F1B PP as its baseline withrtol=1e-4andatol=1e-5. its workflow is path-filtered totorchtitan/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-smiasNVIDIA L20X), PyTorch2.16.0.dev20261102+cu130with the CUDA 13.0580.95.05forward-compat user-mode driver on kernel driver570.172.08. the host is shared and eight free GPUs weren't available, so the runs use FSDP2dp_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-rankmax_activeandmax_reservedmemory over the run. main is887d89561(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.fsdp_defer_gradient_reduction1F1B and Interleaved1F1B gain about 4% throughput on every rank, and the deferred-accumulation row covers
finalize_gradients=Falseacross 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_storageand 13.00 GiB from_restore_unsharded_grad_dtypesin 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@2124d731binc45720e4d. main stopped re-exportingParallelismConfigfromtorchtitan.config, so the lifecycle scenario imports it fromtorchtitan.config.parallelism, and the partial-backward implementation is otherwise unchanged by the merge.on macOS arm64, Python
3.13.18, PyTorch2.16.0.dev20261026and 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 previouse0029100edbbrevision, 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' -qremaining merge gate
upstream lifecycle trackers
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 PyTorch2.16.0.dev20261101+cu132passed the prior 40-combination lifecycle scenario.65b11734, real-PG features job passedfsdp_deferred_gradient_reductionon two ranks andfsdp_pp_deferred_gradient_reductionon four ranks with recorded CUDA graphs, andfsdp_per_group_cuda_graphandshared_eval_cuda_graphpassed 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.