Skip to content

[FSDP2] Add gradient accumulation finalization API - #196640

Closed
fegin wants to merge 12 commits into
gh/fegin/362/basefrom
gh/fegin/362/head
Closed

fegin wants to merge 12 commits into
gh/fegin/362/basefrom
gh/fegin/362/head

Conversation

@fegin

@fegin fegin commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Add a public FSDPModule method, finalize_gradient_accumulation, that completes deferred gradient reduction on the caller thread. It reshards parameters and reduces the accumulated gradients into sharded .grad.

The autograd final callback runs on the autograd thread, so its stream waits cannot be captured in a CUDA graph. Reuse its cleanup on the caller thread, but track deferred reduction explicitly so finalization does not rerun post-backward or reduce zero gradients after a synchronized backward. Temporarily override gradient synchronization, all-reduce, reshard, and last-backward settings, then restore them.

A separate callback would duplicate iteration cleanup. The deferred-work flag keeps one cleanup path while gating the reduction. HSDP all-reduce-only deferral requires a separate collective and gradient view-out path, so reject it explicitly instead of silently skipping gradients.

Test Plan:

python3 test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_finalize_gradient_accumulation
python3 test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_finalize_gradient_accumulation_rejects_partial_all_reduce
python3 test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardCudaGraph.test_finalize_gradient_accumulation_cudagraph
UV_NO_CONFIG=1 lintrunner -a

AI assistance: This commit was authored with Codex.

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category labels Sep 10, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit 94a5b50 with merge base f239880 (image):

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin requested a review from weifengpy September 18, 2026 15:14

@SherlockNoMad SherlockNoMad 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.

@weifengpy should do the major signoff.
not fsdp2 expert, but changes looks ok to me

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@fegin your PR has been successfully reverted.

@pytorchmergebot pytorchmergebot added Reverted ci-no-td Do not run TD on this PR labels Sep 25, 2026
[ghstack-poisoned]
@fegin

fegin commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

Fix the internal errors. Landing this PR again.

@fegin

fegin commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@fegin

fegin commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

fegin added a commit to pytorch/torchtitan that referenced this pull request Sep 29, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #4662
* #4661
* #4660
* #4659
* __->__ #4658

----
**Conflict with #4649, need
to discuss how to incorporate with
#4649
**Depend on pytorch/pytorch#196640 and
pytorch/pytorch#196641

- Add `parallelism.fsdp_defer_gradient_reduction` to reduce gradients
after the final backward of a gradient accumulation group.
- Replay the whole optimizer step during SDC checks.
- Use the public FSDP and pipeline finalization APIs.
pytorchmergebot pushed a commit that referenced this pull request Sep 29, 2026
Add an async option to `finalize_backward` that returns a public gradient-reduction handle. The handle keeps reduction buffers alive and completes stream synchronization and cleanup when waited.

Keep synchronous finalization as the default and implement it through the same handle path.
Pull Request resolved: #196724
Approved by: https://github.com/SherlockNoMad, https://github.com/weifengpy
ghstack dependencies: #196640
pytorchmergebot pushed a commit that referenced this pull request Sep 30, 2026
**Split pipeline FSDP gradient reduction into explicit start and wait actions.**

`REDUCE_GRAD` starts asynchronous FSDP gradient finalization and stores its public `GradientReductionHandle`. `WAIT_REDUCE_GRAD` waits for that handle and completes gradient scaling. Every reduction has exactly one matching wait, and each pipeline rank may have at most one pending reduction.

By default, the wait remains adjacent to its reduction, preserving existing behavior. With `defer_reduce_grad_wait=True`, schedule lowering moves only the wait to immediately before the next local reduction or to the end of the schedule. The reduction remains at its existing causal point, allowing its communication to overlap with the next local stage's backward computation.

For pre-lowered compute-comms schedules, the action stream is the source of truth. Their `REDUCE_GRAD` and `WAIT_REDUCE_GRAD` ordering is validated regardless of the constructor option.

Non-final outer gradient-accumulation steps skip both actions. Deferred waits reject FSDP stages that share a communication context because another stage cannot safely use that context while a reduction is pending.
Pull Request resolved: #196725
Approved by: https://github.com/SherlockNoMad, https://github.com/sanketpurandare
ghstack dependencies: #196640, #196724
wuyl1 added a commit to wuyl1/pytorch that referenced this pull request Sep 30, 2026
Skip default-layout eligibility and per-parameter metadata work. An unused
prefetch can survive integer resharding with the old mesh; wait for and discard
it before switching meshes and releasing its lease. Enforce per-group ownership
for custom layouts and consolidate the regression fixtures.

Test Plan:
Rebased on main a1cf8eb, including pytorch#196640. Passed 42 CPU tests, 26 GPU
regressions, 10 upstream manual-finalization tests, and 32 lifecycle configurations
per device. Validation uses matching FSDP Python sources and existing ROCm
binaries; it does not replace full CI or end-to-end compiled-autograd validation.

Lifecycle commands in the local validation runtime:

```bash
python test_deferred_combination.py TestDeferredLayoutCPU -v
python test_deferred_combination.py TestDeferredLayoutCUDA -v
```

Repository checks:

```bash
python -m spin quicklint -- -a
git diff --check
```

Authored with assistance from OpenAI Codex.
pytorchmergebot pushed a commit that referenced this pull request Sep 30, 2026
Store a GradientEdge for each releasable, grad-requiring pipeline output so backward does not require the original tensor object. Track one pending batched send per output slot. When an existing schedule wait completes that send, release the send operations and the stage's output reference.

Keep unsupported output types, DDP, custom split backward, and last-stage outputs on their tensor-backed ownership paths. Forward-only schedules do not create unused GradientEdges.

**This PR does not change when sends are issued. This PR releases send and stage ownership after the send completes, using the matching backward as the causal retirement point.**

Test Plan:

```

python test/distributed/pipelining/test_backward.py

python test/distributed/pipelining/test_stage.py OutputSlotReleaseTest

```

Authored with assistance from Codex.
Pull Request resolved: #196963
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196640, #196724, #196725
pytorchmergebot pushed a commit that referenced this pull request Sep 30, 2026
## Summary

Add `WAIT_SEND_F` and `WAIT_SEND_B` as first-class pipeline schedule actions.

Each send now has an explicit matching wait. The runtime keeps the P2P operations, work handles, source tensors, and optional output-release callback alive until that wait executes.

## Motivation
Pipeline sends are nonblocking. Their work handles and source tensors must remain alive until communication completes.

Implicit end-of-step waits cannot express earlier ownership release and are unsuitable for static CUDA graph capture. Explicit actions make send lifetime part of the schedule.

This PR is stacked on #196963, which lets forward output ownership be released without breaking backward autograd connectivity.

## Design

For generated schedules:

  - Insert one wait for every send.
  - Place a forward-send wait after the matching backward action when available.
  - Place backward-send waits and unmatched forward-send waits at schedule end.

  For pre-lowered `compute_comms` schedules:

  - Require one ordered wait for every send.
  - Reject duplicate sends, missing waits, and waits without a pending send.

  At runtime:

  - Track each send by direction, stage, and microbatch.
  - Retire a send only when its explicit wait executes.
  - Release forward output ownership after the forward send completes.
  - Drain pending sends only when action execution fails.
  - Do not poll for communication completion.

  The schedule simulator also understands send-wait dependencies and requires he peer receive to be posted before a wait can complete.

  This PR does not enforce an outstanding-send count. A later PR can move these explicit waits earlier to satisfy a memory budget.

Pull Request resolved: #196726
Approved by: https://github.com/SherlockNoMad, https://github.com/sanketpurandare
ghstack dependencies: #196640, #196724, #196725, #196963
pytorchmergebot pushed a commit that referenced this pull request Sep 30, 2026
## Summary

Add an optional `max_outstanding_sends` limit to runtime pipeline schedules. The schedule moves existing send waits earlier to keep pending forward and backward sends within the per-rank limit.

Waits move only when dependency analysis proves the placement cannot create a cycle. Unsafe limits raise an actionable error. The default behavior remains unchanged.

Pull Request resolved: #196727
Approved by: https://github.com/sanketpurandare
ghstack dependencies: #196640, #196724, #196725, #196963, #196726
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
## Summary

Add an optional `max_outstanding_sends` limit to runtime pipeline schedules. The schedule moves existing send waits earlier to keep pending forward and backward sends within the per-rank limit.

Waits move only when dependency analysis proves the placement cannot create a cycle. Unsafe limits raise an actionable error. The default behavior remains unchanged.

Pull Request resolved: pytorch#196727
Approved by: https://github.com/sanketpurandare
ghstack dependencies: pytorch#196640, pytorch#196724, pytorch#196725, pytorch#196963, pytorch#196726
akoumpa added a commit to NVIDIA-NeMo/Automodel that referenced this pull request Nov 18, 2026
PyTorch 2.15 in the 26.11 base (pytorch/pytorch#196640 and its stack)
records the backward finalization mode when FSDP sees a backward start,
clears it when the root post-backward final callback ends the iteration,
and asserts in that callback that the mode is set.

The pipeline-parallel backward patch calls that private callback by hand.
The MoE path calls it once per FSDP unit, but the units of a stage share
the root's state context, so the second call failed with "Expected
manual backward finalization mode to be set" (step_3.5_flash_hellaswag_pp
in the 26.11 nightly). The same assertion fires when FSDP's own callback
already finalized a last backward under defer_fsdp_grad_sync: false.

Skip the manual callback when the mode is cleared: the iteration is
already finalized, or no backward reached the root. Earlier PyTorch has
no such field, so its behavior is unchanged.

Signed-off-by: Alexandros Koumparoulis <[email protected]>
akoumpa added a commit to NVIDIA-NeMo/Automodel that referenced this pull request Nov 19, 2026
* build: bump container to 26.11

Move the PyTorch base to nvcr.io/nvidia/pytorch:26.11-py3 (CUDA 13.5,
PyTorch 2.15.0a0+fd23299, cuDNN 9.28, cuBLAS 13.10, NCCL 2.32.6) and the
CUDA base to cuda-dl-base:26.11-cuda13.5-devel-ubuntu24.04.

Align the PyTorch-container overrides with the 26.11 base: platformdirs
4.12.4 -> 4.14.5 (the base registers its pytest plugin). cuDNN Frontend
stays at 1.30.0: the base's 1.32.0 requires nvidia-cutlass-dsl>=4.8 while
FA4, quack-kernels and ffpa pin 4.6.2. uv-pytorch.lock is regenerated
with uv 0.8.22; only platformdirs changes.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* build(docker): drop the NVGEMM backport now that the base includes it

The 26.11 PyTorch base already contains PyTorch #198292: the backport
patch reverse-applies cleanly to its torch/_inductor/utils.py. Remove the
patch and its apply step, as its header asked once PYTORCH_IMAGE includes
the fix, and keep the import check that the NVGEMM probe tolerates the
FA4/FFPA-compatible CuTe DSL.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* build: build Transformer Engine 2.21.0 in the container

Match the 26.11 base, which ships Transformer Engine 2.21.0. Build TE
from v2.21.0, reuse a base TE only from 2.21.0 on, and require 2.21.0 in
the PyTorch image's native-runtime check.

TE 2.21.0 keeps 2.20.2's runtime requirements (nvidia-cudnn-frontend
>=1.29.0), its FusedAdam implementation that te_patches.py caches is
unchanged, and its EP module exports the same NCCL-EP API.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* build(docker): patch fla's autotune keys for Triton 3.9

Triton 3.9 in the 26.11 base rejects a triton.autotune key that names a
value which is not a kernel argument. fla-core 0.4.2 has two such keys in
fla/ops/cp/chunk_delta_h.py ("STAGE"; "BT" and "USE_EXP2"), so importing
fla failed with "key contains names that are not kernel arguments". The
import runs from nemo_automodel._transformers.infrastructure through the
Kimi K3 model, so every recipe failed at startup in the 26.11 nightly.

Earlier Triton dropped the unknown names, so the patch removes them and
keeps the same tuning keys. The image build applies it to the installed
fla or confirms it is already applied, and rejects any other source. A
scan of all 212 autotune name lists in fla-core 0.4.2 finds no others,
and Automodel's own kernels have none.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* build: move flash-linear-attention to 0.5.2 for Triton 3.9

Triton 3.9 in the 26.11 base removed block pointers: tl.make_block_ptr
and tl.advance now raise NotImplementedError when a kernel compiles.
fla 0.4.2 uses them in 77 files, so its kernels fail at the first launch
(qwen3_5_4b, qwen3_5_35b and nemotron_flash_1b_squad in the 26.11
nightly, on H100 and VR200). fla 0.5.2 is the first release that no
longer uses them (fla-org/flash-linear-attention#1062).

- pyproject.toml: flash-linear-attention>=0.5.2,<0.6. The upper bound
  keeps the lock on the release that the container patch and the CP
  prewarm launches below were written against.
- docker/common/fla-autotune-keys.patch: retarget to fla-core 0.5.2.
  Its merge_fwd_bwd_kernel autotune key still names "BT", which is not
  a kernel argument and which Triton 3.9 rejects at import. The 0.4.2
  keys are gone.
- prewarm.py: fla 0.5.2 renamed the head arguments of the private CP
  kernels (H -> HV in merge_fwd_bwd_kernel; HV added to
  pre_process_bwd_kernel_merged) and replaced USE_EXP2 with USE_BG.
  Without this the prewarm logs a signature drift and skips.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* Update uv lock

Signed-off-by: NeMo Bot <[email protected]>

* fix(moe): skip FSDP's root callback once the backward is finalized

PyTorch 2.15 in the 26.11 base (pytorch/pytorch#196640 and its stack)
records the backward finalization mode when FSDP sees a backward start,
clears it when the root post-backward final callback ends the iteration,
and asserts in that callback that the mode is set.

The pipeline-parallel backward patch calls that private callback by hand.
The MoE path calls it once per FSDP unit, but the units of a stage share
the root's state context, so the second call failed with "Expected
manual backward finalization mode to be set" (step_3.5_flash_hellaswag_pp
in the 26.11 nightly). The same assertion fires when FSDP's own callback
already finalized a last backward under defer_fsdp_grad_sync: false.

Skip the manual callback when the mode is cleared: the iteration is
already finalized, or no backward reached the root. Earlier PyTorch has
no such field, so its behavior is unchanged.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* fix(pipelining): keep stock recv buffers when PyTorch allocates them JIT

PyTorch 2.15 in the 26.11 base (pytorch/pytorch#196463) allocates each
pipeline receive buffer just before its receive and hands it to the stage
computation, instead of preallocating one buffer set per microbatch. The
opt-in recv-buffer pools then have nothing to save: the ordinary 1F1B ring
aliases receive descriptors that no longer own long-lived buffers, and the
interleaved pool's owned copies only add memory. Both installers now keep
the stock buffers when torch.distributed.pipelining._recv_buffers exists.

The pool unit tests pin the probe for the fake stage layouts, skip the
real-PyTorch parity and negative-control runs under just-in-time buffers
(the negative control can no longer corrupt a reused buffer), and the
interleaved schedule harness sets the PyTorch 2.15 runtime defaults it
skips by bypassing __init__ (_unshard_lookahead, _defer_reduce_grad_wait,
_max_outstanding_sends).

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* build(docker): backport torchao's MoE FP8 autotune key fix for Triton 3.9

torchao v0.17.0, which the image builds for its MXFP8 kernels, names
"num_elements" in the triton.autotune key of
_triton_fp8_rowwise_3d_transpose_cast_rhs_kernel, but the kernel has no
such argument. Triton 3.9 in the 26.11 base rejects that when
torchao.prototype.moe_training is imported, so the MXFP8 grouped GEMM
resolver failed (tests/unit_tests/moe/test_mxfp8.py). Apply upstream's
fix, pytorch/ao#4880, to the v0.17.0 checkout before building the wheel.
The step accepts the original or the already-patched source only.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* ci(recipes): give nemotron_nano_v3_hellaswag 50 minutes in CI

Its nightly checkpoint-robustness job finished in 39.6 of its 40 minutes
on the 26.10 image. On 26.11 it trains with the same loss trajectory but
about 3% slower (93K vs 96K tokens/s), so it hit the Slurm time limit in
the automodel_reload phase in both 26.11 nightlies.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* test(ci): list the torchao patch among the container dependency inputs

The wheel-builder stage now copies docker/common/torchao-autotune-key.patch. prepare-container-dependencies.sh already fingerprints all of docker/, so only the test's explicit input list was missing it.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* test(optim): name the leaked types when the cyclic-garbage check fails

test_backward_leaves_no_cyclic_garbage failed in the 26.11 L0 CPU job
(1423 and 1420 unreachable objects in two runs) but passes alone in the
26.11 image, with and without a GPU, with coverage, and with the whole
tests/unit_tests/optim directory in one process. Some test that shares
its xdist worker leaves state behind. Report the collected object types
in the assertion so the next failure identifies the source.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* test(pipelining): skip interleaved pool parity when receives are JIT

The functional parity test asserts that installing the interleaved recv
pool leaves fewer receive descriptors than microbatches, and the 4-GPU
negative control expects corruption once the owned input copies are
removed. With PyTorch 2.15 (26.11), which allocates receive buffers just
in time, the installer keeps the stock buffers, so neither assertion
applies (L2_Distributed on H100 and GB200). Gate the module on the same
probe the unit tests use.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* test(optim): drain earlier tests' garbage before the cyclic-garbage check

On PyTorch 2.15 (26.11), the Dynamo tracing state of an earlier
torch.compile test in the same process (test_tp_linear, test_dsv4_layers,
test_experts or test_swiglu_triton) is released in two stages: the first
gc.collect() runs a finalizer that drops the last reference to another
cycle, which only the next collection finds. The single baseline collect
left those 168 to 1420 objects (FakeTensor, SymNode and fx.Node graphs,
traceback.FrameSummary) to the measured window, so the check failed
whenever such a test ran first in the xdist worker. Collect until nothing
is left before measuring; the check still covers every cycle the sketch
backward creates.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* test(pipelining): check interleaved parity with native JIT receives

Signed-off-by: Alexandros Koumparoulis <[email protected]>

---------

Signed-off-by: Alexandros Koumparoulis <[email protected]>
Signed-off-by: NeMo Bot <[email protected]>
Co-authored-by: NeMo Bot <[email protected]>
@github-actions
github-actions Bot deleted the gh/fegin/362/head branch December 2, 2026 01:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: distributed (fsdp) release notes category Reverted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants