Skip to content

[FSDP2] Add set_reduce_scatter_max_input_buffers to mitigate reduce-scatter blocking backward compute - #186000

Closed
weifengpy wants to merge 4 commits into
gh/weifengpy/148/basefrom
gh/weifengpy/148/head
Closed

weifengpy wants to merge 4 commits into
gh/weifengpy/148/basefrom
gh/weifengpy/148/head

Conversation

@weifengpy

@weifengpy weifengpy commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

FSDP keeps one reduce-scatter input buffer in flight: the compute stream must wait on the previous reduce-scatter before the next copy-in (chunk_cat) can reuse that buffer (FSDP::post_backward_rs_wait). When the reduce-scatter is exposed, that recycle wait stalls backward compute every layer — e.g. 37.6 ms/step of compute-stream idle, 100% gated by a reduce-scatter finishing, on an omnifm_v5 trace. There's no compute→reduce-scatter data dependency (backward never reads the reduced gradient), so the coupling is pure buffer-reuse bookkeeping.

This exposes the in-flight buffer count — hardwired to 1 — as a per-module tunable:

FSDPModule.set_reduce_scatter_max_input_buffers(max_input_buffers: int, *, recurse: bool = True)

Raising it lets the next copy-in write a fresh buffer instead of waiting, removing the stall. 1 (default) keeps today's behavior; 2 clears the stall once it's ≥ the reduce-scatter pipeline depth while bounding peak memory; larger caps overlap deeper at higher memory.

Design: generalize the existing recycle to keep at most max_input_buffers buffers — reclaim the oldest (current_stream.wait_event(oldest_rs), then drop the keepalive ref; no record_stream) before this layer appends one. 1 drains to zero and reuses the freed buffer → byte-identical to upstream, and the reclaim is a no-op once ≥ the pipeline depth. The copy-in stays on the compute stream (foreach_reduce unchanged) and grads free promptly, so only the retained input buffers cost memory. The cap is a positive int — no unbounded mode (a large cap already means "retain all").

Co-authored-by: Lei Tian [email protected]

@pytorch-bot

pytorch-bot Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 2 New Failures

As of commit 26c58fd with merge base f5d8a56 (image):

NEW FAILURES - The following jobs have failed:

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category labels Jun 2, 2026
weifengpy added a commit that referenced this pull request Jun 2, 2026
…n the RS stream)

Adds an experimental, default-off `FSDPModule` API,
`set_reduce_scatter_copy_in_on_rs_stream(enable=True, *, recurse=True)`, that runs
the gradient reduce-scatter copy-in (`chunk_cat`) on the reduce-scatter stream
instead of the default/compute stream.

Motivation: when reduce-scatter is exposed (comm slower than the backward compute
meant to hide it), recycling the RS-input buffer with
`current_stream.wait_event(prev_rs_event)` in `FSDP::post_backward_rs_wait` stalls
the compute stream. Running the copy-in on the RS stream makes the RS-input buffer
RS-stream-local, so no compute-stream reclaim wait is needed (each
`ReduceScatterState` records `needs_compute_stream_wait`, so mixed per-module
settings stay correct). The one new cross-stream lifetime -- the unsharded
gradients read by the copy-in -- is managed with the canonical keepalive-ref +
`wait_event`-before-`del` pattern (no `record_stream`), mirroring
`reduce_scatter_states`. Trades extra peak memory (retained grads) for overlap;
helps only when reduce-scatter is exposed.

Fully gated: the new path engages only per-module via the API (default off).
`foreach_reduce` keeps its 7-tuple return; `copy_in_on_rs_stream` and the grad
out-list are passed as optional kwargs only when enabled, so existing callers and
tests are unaffected.

Test Plan:
- `test_fully_shard_comm.py TestFullyShardCollectiveOps.test_reduce_scatter_fp16`
  (default/off): passes
- Local 4xH100, FSDP 1D + HSDP 2x2 via `set_reduce_scatter_copy_in_on_rs_stream`:
  sharded grads bitwise-identical off vs on

ghstack-source-id: a1984ad
Pull-Request: #186000
@weifengpy weifengpy changed the title [FSDP2] Run reduce-scatter copy-in on the RS stream (flag-gated, default off) [FSDP2] Add set_reduce_scatter_copy_in_on_rs_stream (run RS copy-in on the RS stream) Jun 2, 2026
weifengpy added a commit that referenced this pull request Jun 2, 2026
…n the RS stream)

Adds an experimental, default-off `FSDPModule` API,
`set_reduce_scatter_copy_in_on_rs_stream(enable=True, *, recurse=True)`, that runs
the gradient reduce-scatter copy-in (`chunk_cat`) on the reduce-scatter stream
instead of the default/compute stream.

Motivation: when reduce-scatter is exposed (comm slower than the backward compute
meant to hide it), recycling the RS-input buffer with
`current_stream.wait_event(prev_rs_event)` in `FSDP::post_backward_rs_wait` stalls
the compute stream. Running the copy-in on the RS stream makes the RS-input buffer
RS-stream-local, so no compute-stream reclaim wait is needed (each
`ReduceScatterState` records `needs_compute_stream_wait`, so mixed per-module
settings stay correct). The one new cross-stream lifetime -- the unsharded
gradients read by the copy-in -- is managed with the canonical keepalive-ref +
`wait_event`-before-`del` pattern (no `record_stream`), mirroring
`reduce_scatter_states`. Trades extra peak memory (retained grads) for overlap;
helps only when reduce-scatter is exposed.

Fully gated: the new path engages only per-module via the API (default off).
`foreach_reduce` keeps its 7-tuple return; `copy_in_on_rs_stream` and the grad
out-list are passed as optional kwargs only when enabled, so existing callers and
tests are unaffected.

Test Plan:
- `test_fully_shard_comm.py TestFullyShardCollectiveOps.test_reduce_scatter_fp16`
  (default/off): passes
- Local 4xH100, FSDP 1D + HSDP 2x2 via `set_reduce_scatter_copy_in_on_rs_stream`:
  sharded grads bitwise-identical off vs on

ghstack-source-id: a1984ad
Pull-Request: #186000
weifengpy added a commit that referenced this pull request Jun 2, 2026
…n the RS stream)

Adds an experimental, default-off `FSDPModule` API,
`set_reduce_scatter_copy_in_on_rs_stream(enable=True, *, recurse=True)`, that runs
the gradient reduce-scatter copy-in (`chunk_cat`) on the reduce-scatter stream
instead of the default/compute stream.

Motivation: when reduce-scatter is exposed (comm slower than the backward compute
meant to hide it), recycling the RS-input buffer with
`current_stream.wait_event(prev_rs_event)` in `FSDP::post_backward_rs_wait` stalls
the compute stream. Running the copy-in on the RS stream makes the RS-input buffer
RS-stream-local, so no compute-stream reclaim wait is needed (each
`ReduceScatterState` records `needs_compute_stream_wait`, so mixed per-module
settings stay correct). The one new cross-stream lifetime -- the unsharded
gradients read by the copy-in -- is managed with the canonical keepalive-ref +
`wait_event`-before-`del` pattern (no `record_stream`), mirroring
`reduce_scatter_states`. Trades extra peak memory (retained grads) for overlap;
helps only when reduce-scatter is exposed.

Fully gated: the new path engages only per-module via the API (default off).
`foreach_reduce` keeps its 7-tuple return; `copy_in_on_rs_stream` and the grad
out-list are passed as optional kwargs only when enabled, so existing callers and
tests are unaffected.

Test Plan:
- `test_fully_shard_comm.py TestFullyShardCollectiveOps.test_reduce_scatter_fp16`
  (default/off): passes
- Local 4xH100, FSDP 1D + HSDP 2x2 via `set_reduce_scatter_copy_in_on_rs_stream`:
  sharded grads bitwise-identical off vs on

ghstack-source-id: 1f67d4d
Pull-Request: #186000
weifengpy added a commit that referenced this pull request Jun 3, 2026
…off the compute stream)

By default FSDP2 runs the post-backward reduce-scatter copy-in (chunk_cat) on
the compute stream and recycles the RS-input buffer with
current_stream.wait_event(prev_rs_event) in FSDP::post_backward_rs_wait. When a
reduce-scatter is exposed, that recycle wait stalls the compute stream (measured
37.6 ms/step of compute-stream idle, 100% gated by an RS finishing, on an
omnifm_v5 trace). There is no compute->RS data dependency -- backward math never
reads the reduced gradient; only the optimizer does, after backward -- so the
coupling is buffer-reuse bookkeeping and can be moved off the compute stream.

This adds an opt-in, per-module API:

    FSDPModule.set_reduce_scatter_copy_in_max_in_flight(
        max_in_flight: int | None = None, *, recurse: bool = True
    )

Calling it enables running the gradient reduce-scatter copy-in on a dedicated
copy-in stream (off by default -- not calling it). max_in_flight is a cap-K dial
on how many in-flight copy-in RS-input buffers may be held (None = unbounded).

Design (producer->consumer: grads on compute -> copy-in -> RS):
- The copy-in runs on a dedicated high-priority copy-in stream (not the compute
  stream, not the RS collective stream). A dedicated stream -- rather than the RS
  stream -- keeps the copy-in from serializing behind the previous RS, which
  would feed the RS schedule back into the grad reclaim and re-stall compute.
- Cross-stream buffer lifetimes use ref-hold + event (no record_stream, matching
  the rest of _fully_shard): grads are held until
  current_stream.wait_event(copy_in_event) before del; RS-input buffers are held
  in reduce_scatter_states and freed at finalize (after the RS is known done).
- cap-K (max_in_flight) bounds the held RS-input buffers: reclaim the oldest via
  reduce_scatter_copy_in_stream.wait_event(rs_event) -- on the copy-in stream,
  not compute. It is a no-op whenever K >= the RS pipeline depth, so it caps peak
  memory with zero added stall in the overlapped regime.

Fully gated: when not enabled, foreach_reduce receives the original positional
args, returns the original 7-tuple, and the RS-input keeps
needs_compute_stream_wait=True -- byte-identical to upstream (mixed per-module
on/off stays correct via the per-entry needs_compute_stream_wait flag).

Test Plan:
- test_fully_shard_comm.py test_set_reduce_scatter_copy_in_max_in_flight
  (16 subtests over mesh shape x reshard_after_forward x mixed precision x
  max_in_flight in {None, 2}): passes
- test_fully_shard_comm.py TestFullyShardCollectiveOps.test_reduce_scatter_fp16
  (default/off): passes
- Local 4xH100, FSDP 1D + HSDP 2x2: sharded grads bitwise-identical off vs on,
  including a long-RS stress run; memory off 6.11 GB, on K=inf 7.73 (+1.62),
  K=2 7.00, K=1 6.76 GB (cap-K bounds the overhead monotonically, parity
  bitwise at all K)

ghstack-source-id: d5f9876
Pull-Request: #186000
@weifengpy weifengpy changed the title [FSDP2] Add set_reduce_scatter_copy_in_on_rs_stream (run RS copy-in on the RS stream) [FSDP2] Add set_reduce_scatter_copy_in_max_in_flight (run RS copy-in off the compute stream) Jun 3, 2026
weifengpy added a commit that referenced this pull request Jun 3, 2026
… RS copy-in buffers)

By default FSDP2 retains a single reduce-scatter input buffer: the copy-in
(chunk_cat) runs on the compute stream and the buffer is recycled with
current_stream.wait_event(prev_rs_event) in FSDP::post_backward_rs_wait. Because
only one buffer is kept alive, each layer's post_backward must wait on the
previous layer's reduce-scatter before the next copy-in can reuse it -- so when
the reduce-scatter is exposed, that recycle wait stalls the compute stream
(measured 37.6 ms/step of compute-stream idle, 100% gated by an RS finishing, on
an omnifm_v5 trace). There is no compute->RS data dependency -- backward math
never reads the reduced gradient; only the optimizer does, after backward -- so
the coupling is pure buffer-reuse bookkeeping.

This adds an opt-in, per-module API:

    FSDPModule.set_reduce_scatter_copy_in_max_in_flight(
        max_in_flight: int | None = None, *, recurse: bool = True
    )

Calling it enables retaining more than one reduce-scatter input buffer in flight,
so the next copy-in writes a fresh buffer instead of waiting on the in-flight
reduce-scatter -- removing the stall. max_in_flight caps the retained buffers
(None = unbounded, retained until end of backward).

Design:
- The copy-in stays on the compute stream (foreach_reduce is unchanged from
  upstream). The only change is the recycle policy: hold up to max_in_flight
  reduce-scatter input buffers instead of one.
- The recycle wait is relaxed, not moved: when the held count exceeds
  max_in_flight, reclaim the oldest with current_stream.wait_event(oldest_rs)
  then drop the keepalive ref (no record_stream, matching the rest of
  _fully_shard). This is a no-op whenever max_in_flight >= the reduce-scatter
  pipeline depth, so it removes the stall with zero added wait in the overlapped
  regime. max_in_flight=1 reduces to the baseline (the stall returns), so
  max_in_flight must be >= the pipeline depth (typically >= 2) to gain overlap.
- Grads free promptly in compute-stream order (as upstream); only the retained
  reduce-scatter input buffers cost extra memory.

Fully gated: when not enabled, foreach_reduce is byte-identical to upstream, the
eager per-layer recycle runs, and no extra stream is allocated.

Test Plan:
- test_fully_shard_comm.py test_set_reduce_scatter_copy_in_max_in_flight
  (16 subtests over mesh shape x reshard_after_forward x mixed precision x
  max_in_flight in {None, 2}): passes
- Local 4xH100, FSDP 1D + HSDP 2x2: sharded grads bitwise-identical off vs on at
  max_in_flight in {None, 2, 1}, including a long-RS stress run.
- Memory (6 blocks, 8192/16384, batch 512, bf16, reshard_after_forward=False):
  off 6.11 GB; on K=inf 6.80 (+0.70), K=2 6.11, K=1 6.11 GB.
- Long-RS trace, off vs on: compute-stream gaps >500us drop 7 -> 2; off's five
  interspersed 1.2-2.8 ms per-layer recycle stalls collapse (on's mid-backward
  gaps are <=0.23 ms; the exposed RS is pushed to a single end-of-backward
  drain, off the critical path).

ghstack-source-id: b1b2b6b
Pull-Request: #186000
@weifengpy weifengpy changed the title [FSDP2] Add set_reduce_scatter_copy_in_max_in_flight (run RS copy-in off the compute stream) [FSDP2] Add set_reduce_scatter_copy_in_max_in_flight (bound in-flight RS copy-in buffers) Jun 3, 2026
weifengpy added a commit that referenced this pull request Jun 3, 2026
… RS copy-in buffers)

By default FSDP2 keeps a single reduce-scatter copy-in (chunk_cat) input buffer
in flight: the copy-in runs on the compute stream, and the buffer is recycled in
FSDP::post_backward_rs_wait by waiting the compute stream on the previous
reduce-scatter before the next copy-in reuses it. So each layer's post_backward
waits on the previous layer's reduce-scatter -- and when the reduce-scatter is
exposed, that recycle wait stalls the compute stream (measured 37.6 ms/step of
compute-stream idle, 100% gated by an RS finishing, on an omnifm_v5 trace).
There is no compute->RS data dependency -- backward never reads the reduced
gradient; only the optimizer does, after backward -- so the coupling is pure
buffer-reuse bookkeeping.

This exposes the in-flight buffer count -- currently hardwired to 1 -- as a
per-module tunable:

    FSDPModule.set_reduce_scatter_copy_in_max_in_flight(
        max_in_flight: int | None = None, *, recurse: bool = True
    )

Raising the cap lets the next copy-in write a fresh buffer instead of waiting on
the in-flight reduce-scatter, removing the stall. max_in_flight=1 is the default
(today's single-buffer behavior); None retains all buffers until end of backward
(call with no argument); a small value (e.g. 2) bounds peak memory.

Design:
- The copy-in stays on the compute stream (foreach_reduce is unchanged from
  upstream). The change is purely the recycle policy.
- Generalize the existing recycle (FSDP::post_backward_rs_wait, before the
  reduce) to keep at most max_in_flight buffers: reclaim the oldest --
  current_stream.wait_event(oldest_rs) then drop the keepalive ref (no
  record_stream) -- until fewer than max_in_flight remain, before this layer
  appends one more. max_in_flight=1 drains to zero and reuses the freed buffer,
  byte-identical to upstream. The reclaim is a no-op once max_in_flight >= the
  reduce-scatter pipeline depth (removes the stall with zero added wait in the
  overlapped regime); below the pipeline depth it keeps the stall -- the
  memory<->overlap dial.
- Grads free promptly in compute-stream order (as upstream); only the retained
  reduce-scatter input buffers cost extra memory.

Fully gated: the default max_in_flight=1 is byte-identical to upstream (same
recycle, no extra stream, no record_stream).

Test Plan:
- test_fully_shard_comm.py test_set_reduce_scatter_copy_in_max_in_flight
  (24 subtests over mesh shape x reshard_after_forward x mixed precision x
  max_in_flight in {None, 2, 1}): passes
- Local 4xH100, FSDP 1D + HSDP 2x2: sharded grads bitwise-identical to the
  default at max_in_flight in {None, 2, 1}, including a long-RS stress run.
- Memory (6 blocks, 8192/16384, batch 512, bf16, reshard_after_forward=False):
  default(=1) 6.11 GB; None 6.80 (+0.70), 2 6.11, 1 6.11 (== default).
- Long-RS trace, default vs None: compute-stream gaps >500us drop 7 -> 3; the
  default's five interspersed 1.2-2.9 ms per-layer recycle stalls collapse to a
  single end-of-backward drain (off the critical path).

ghstack-source-id: 8923d05
Pull-Request: #186000
weifengpy added a commit that referenced this pull request Jun 3, 2026
… RS copy-in buffers)

By default FSDP2 keeps a single reduce-scatter copy-in (chunk_cat) input buffer
in flight: the copy-in runs on the compute stream, and the buffer is recycled in
FSDP::post_backward_rs_wait by waiting the compute stream on the previous
reduce-scatter before the next copy-in reuses it. So each layer's post_backward
waits on the previous layer's reduce-scatter -- and when the reduce-scatter is
exposed, that recycle wait stalls the compute stream (measured 37.6 ms/step of
compute-stream idle, 100% gated by an RS finishing, on an omnifm_v5 trace).
There is no compute->RS data dependency -- backward never reads the reduced
gradient; only the optimizer does, after backward -- so the coupling is pure
buffer-reuse bookkeeping.

This exposes the in-flight buffer count -- currently hardwired to 1 -- as a
per-module tunable:

    FSDPModule.set_reduce_scatter_copy_in_max_in_flight(
        max_in_flight: int, *, recurse: bool = True
    )

Raising the cap lets the next copy-in write a fresh buffer instead of waiting on
the in-flight reduce-scatter, removing the stall. max_in_flight=1 is the default
(today's single-buffer behavior); a small value (e.g. 2) removes the stall when
>= the reduce-scatter pipeline depth while bounding peak memory; larger values
retain more buffers for deeper overlap at higher peak memory.

Design:
- The copy-in stays on the compute stream (foreach_reduce is unchanged from
  upstream). The change is purely the recycle policy.
- Generalize the existing recycle (FSDP::post_backward_rs_wait, before the
  reduce) to keep at most max_in_flight buffers: reclaim the oldest --
  current_stream.wait_event(oldest_rs) then drop the keepalive ref (no
  record_stream) -- until fewer than max_in_flight remain, before this layer
  appends one more. max_in_flight=1 drains to zero and reuses the freed buffer,
  byte-identical to upstream. The reclaim is a no-op once max_in_flight >= the
  reduce-scatter pipeline depth (removes the stall with zero added wait in the
  overlapped regime); below it the stall persists -- the memory<->overlap dial.
- Grads free promptly in compute-stream order (as upstream); only the retained
  reduce-scatter input buffers cost extra memory.

The cap is a positive int (no unbounded mode): a finite cap >= the pipeline
depth already removes the stall with bounded memory, and "retain everything" is
just a large cap, so an unbounded sentinel would only add an unbounded-memory
footgun.

Fully gated: the default max_in_flight=1 is byte-identical to upstream (same
recycle, no extra stream, no record_stream).

Test Plan:
- test_fully_shard_comm.py test_set_reduce_scatter_copy_in_max_in_flight
  (16 subtests over mesh shape x reshard_after_forward x mixed precision x
  max_in_flight in {1, 2}): passes
- Local 4xH100, FSDP 1D + HSDP 2x2: sharded grads bitwise-identical to the
  default at max_in_flight in {1, 2, large}, including a long-RS stress run.
- Memory (6 blocks, 8192/16384, batch 512, bf16, reshard_after_forward=False):
  default(=1) 6.11 GB; large-cap 6.80 (+0.70), 2 6.11, 1 6.11 (== default).
- Long-RS trace, default vs large-cap: compute-stream gaps >500us drop 7 -> 3;
  the default's five interspersed 1.2-2.9 ms per-layer recycle stalls collapse to
  a single end-of-backward drain (off the critical path).

ghstack-source-id: 1c36cd1
Pull-Request: #186000
weifengpy added a commit that referenced this pull request Jun 3, 2026
…-scatter input buffers)

By default FSDP2 keeps a single reduce-scatter copy-in (chunk_cat) input buffer
in flight: the copy-in runs on the compute stream, and the buffer is recycled in
FSDP::post_backward_rs_wait by waiting the compute stream on the previous
reduce-scatter before the next copy-in reuses it. So each layer's post_backward
waits on the previous layer's reduce-scatter -- and when the reduce-scatter is
exposed, that recycle wait stalls the compute stream (measured 37.6 ms/step of
compute-stream idle, 100% gated by an RS finishing, on an omnifm_v5 trace).
There is no compute->RS data dependency -- backward never reads the reduced
gradient; only the optimizer does, after backward -- so the coupling is pure
buffer-reuse bookkeeping.

This exposes the in-flight buffer count -- currently hardwired to 1 -- as a
per-module tunable:

    FSDPModule.set_reduce_scatter_max_input_buffers(
        max_input_buffers: int, *, recurse: bool = True
    )

Raising the cap lets the next copy-in write a fresh buffer instead of waiting on
the in-flight reduce-scatter, removing the stall. max_input_buffers=1 is the default
(today's single-buffer behavior); a small value (e.g. 2) removes the stall when
>= the reduce-scatter pipeline depth while bounding peak memory; larger values
retain more buffers for deeper overlap at higher peak memory.

Design:
- The copy-in stays on the compute stream (foreach_reduce is unchanged from
  upstream). The change is purely the recycle policy.
- Generalize the existing recycle (FSDP::post_backward_rs_wait, before the
  reduce) to keep at most max_input_buffers buffers: reclaim the oldest --
  current_stream.wait_event(oldest_rs) then drop the keepalive ref (no
  record_stream) -- until fewer than max_input_buffers remain, before this layer
  appends one more. max_input_buffers=1 drains to zero and reuses the freed buffer,
  byte-identical to upstream. The reclaim is a no-op once max_input_buffers >= the
  reduce-scatter pipeline depth (removes the stall with zero added wait in the
  overlapped regime); below it the stall persists -- the memory<->overlap dial.
- Grads free promptly in compute-stream order (as upstream); only the retained
  reduce-scatter input buffers cost extra memory.

The cap is a positive int (no unbounded mode): a finite cap >= the pipeline
depth already removes the stall with bounded memory, and "retain everything" is
just a large cap, so an unbounded sentinel would only add an unbounded-memory
footgun.

Fully gated: the default max_input_buffers=1 is byte-identical to upstream (same
recycle, no extra stream, no record_stream).

Test Plan:
- test_fully_shard_comm.py test_set_reduce_scatter_max_input_buffers
  (16 subtests over mesh shape x reshard_after_forward x mixed precision x
  max_input_buffers in {1, 2}): passes
- Local 4xH100, FSDP 1D + HSDP 2x2: sharded grads bitwise-identical to the
  default at max_input_buffers in {1, 2, large}, including a long-RS stress run.
- Memory (6 blocks, 8192/16384, batch 512, bf16, reshard_after_forward=False):
  default(=1) 6.11 GB; large-cap 6.80 (+0.70), 2 6.11, 1 6.11 (== default).
- Long-RS trace, default vs large-cap: compute-stream gaps >500us drop 7 -> 3;
  the default's five interspersed 1.2-2.9 ms per-layer recycle stalls collapse to
  a single end-of-backward drain (off the critical path).

ghstack-source-id: 97bca09
Pull-Request: #186000
@weifengpy weifengpy changed the title [FSDP2] Add set_reduce_scatter_copy_in_max_in_flight (bound in-flight RS copy-in buffers) [FSDP2] Add set_reduce_scatter_max_input_buffers (cap retained reduce-scatter input buffers) Jun 3, 2026
@weifengpy weifengpy changed the title [FSDP2] Add set_reduce_scatter_max_input_buffers (cap retained reduce-scatter input buffers) [FSDP2] set_reduce_scatter_max_input_buffers to mitigate RS blocking backward compute Jun 3, 2026
weifengpy added a commit that referenced this pull request Jun 3, 2026
…-scatter input buffers)

By default FSDP2 keeps a single reduce-scatter copy-in (chunk_cat) input buffer
in flight: the copy-in runs on the compute stream, and the buffer is recycled in
FSDP::post_backward_rs_wait by waiting the compute stream on the previous
reduce-scatter before the next copy-in reuses it. So each layer's post_backward
waits on the previous layer's reduce-scatter -- and when the reduce-scatter is
exposed, that recycle wait stalls the compute stream (measured 37.6 ms/step of
compute-stream idle, 100% gated by an RS finishing, on an omnifm_v5 trace).
There is no compute->RS data dependency -- backward never reads the reduced
gradient; only the optimizer does, after backward -- so the coupling is pure
buffer-reuse bookkeeping.

This exposes the in-flight buffer count -- currently hardwired to 1 -- as a
per-module tunable:

    FSDPModule.set_reduce_scatter_max_input_buffers(
        max_input_buffers: int, *, recurse: bool = True
    )

Raising the cap lets the next copy-in write a fresh buffer instead of waiting on
the in-flight reduce-scatter, removing the stall. max_input_buffers=1 is the default
(today's single-buffer behavior); a small value (e.g. 2) removes the stall when
>= the reduce-scatter pipeline depth while bounding peak memory; larger values
retain more buffers for deeper overlap at higher peak memory.

Design:
- The copy-in stays on the compute stream (foreach_reduce is unchanged from
  upstream). The change is purely the recycle policy.
- Generalize the existing recycle (FSDP::post_backward_rs_wait, before the
  reduce) to keep at most max_input_buffers buffers: reclaim the oldest --
  current_stream.wait_event(oldest_rs) then drop the keepalive ref (no
  record_stream) -- until fewer than max_input_buffers remain, before this layer
  appends one more. max_input_buffers=1 drains to zero and reuses the freed buffer,
  byte-identical to upstream. The reclaim is a no-op once max_input_buffers >= the
  reduce-scatter pipeline depth (removes the stall with zero added wait in the
  overlapped regime); below it the stall persists -- the memory<->overlap dial.
- Grads free promptly in compute-stream order (as upstream); only the retained
  reduce-scatter input buffers cost extra memory.

The cap is a positive int (no unbounded mode): a finite cap >= the pipeline
depth already removes the stall with bounded memory, and "retain everything" is
just a large cap, so an unbounded sentinel would only add an unbounded-memory
footgun.

Fully gated: the default max_input_buffers=1 is byte-identical to upstream (same
recycle, no extra stream, no record_stream).

Test Plan:
- test_fully_shard_comm.py test_set_reduce_scatter_max_input_buffers
  (8 subtests over mesh shape x reshard_after_forward x max_input_buffers in
  {1, 2}, under bf16 mixed precision): passes
- Local 4xH100, FSDP 1D + HSDP 2x2: sharded grads bitwise-identical to the
  default at max_input_buffers in {1, 2, large}, including a long-RS stress run.
- Memory (6 blocks, 8192/16384, batch 512, bf16, reshard_after_forward=False):
  default(=1) 6.11 GB; large-cap 6.80 (+0.70), 2 6.11, 1 6.11 (== default).
- Long-RS trace, default vs large-cap: compute-stream gaps >500us drop 7 -> 3;
  the default's five interspersed 1.2-2.9 ms per-layer recycle stalls collapse to
  a single end-of-backward drain (off the critical path).

ghstack-source-id: c4cb640
Pull-Request: #186000
@weifengpy
weifengpy marked this pull request as ready for review June 3, 2026 22:43
@weifengpy weifengpy changed the title [FSDP2] set_reduce_scatter_max_input_buffers to mitigate RS blocking backward compute [FSDP2] Add set_reduce_scatter_max_input_buffers to mitigate reduce-scatter blocking backward compute Jun 3, 2026
weifengpy added a commit that referenced this pull request Jun 3, 2026
…-scatter input buffers)

By default FSDP2 keeps a single reduce-scatter copy-in (chunk_cat) input buffer
in flight: the copy-in runs on the compute stream, and the buffer is recycled in
FSDP::post_backward_rs_wait by waiting the compute stream on the previous
reduce-scatter before the next copy-in reuses it. So each layer's post_backward
waits on the previous layer's reduce-scatter -- and when the reduce-scatter is
exposed, that recycle wait stalls the compute stream (measured 37.6 ms/step of
compute-stream idle, 100% gated by an RS finishing, on an omnifm_v5 trace).
There is no compute->RS data dependency -- backward never reads the reduced
gradient; only the optimizer does, after backward -- so the coupling is pure
buffer-reuse bookkeeping.

This exposes the in-flight buffer count -- currently hardwired to 1 -- as a
per-module tunable:

    FSDPModule.set_reduce_scatter_max_input_buffers(
        max_input_buffers: int, *, recurse: bool = True
    )

Raising the cap lets the next copy-in write a fresh buffer instead of waiting on
the in-flight reduce-scatter, removing the stall. max_input_buffers=1 is the default
(today's single-buffer behavior); a small value (e.g. 2) removes the stall when
>= the reduce-scatter pipeline depth while bounding peak memory; larger values
retain more buffers for deeper overlap at higher peak memory.

Design:
- The copy-in stays on the compute stream (foreach_reduce is unchanged from
  upstream). The change is purely the recycle policy.
- Generalize the existing recycle (FSDP::post_backward_rs_wait, before the
  reduce) to keep at most max_input_buffers buffers: reclaim the oldest --
  current_stream.wait_event(oldest_rs) then drop the keepalive ref (no
  record_stream) -- until fewer than max_input_buffers remain, before this layer
  appends one more. max_input_buffers=1 drains to zero and reuses the freed buffer,
  byte-identical to upstream. The reclaim is a no-op once max_input_buffers >= the
  reduce-scatter pipeline depth (removes the stall with zero added wait in the
  overlapped regime); below it the stall persists -- the memory<->overlap dial.
- Grads free promptly in compute-stream order (as upstream); only the retained
  reduce-scatter input buffers cost extra memory.

The cap is a positive int (no unbounded mode): a finite cap >= the pipeline
depth already removes the stall with bounded memory, and "retain everything" is
just a large cap, so an unbounded sentinel would only add an unbounded-memory
footgun.

Fully gated: the default max_input_buffers=1 is byte-identical to upstream (same
recycle, no extra stream, no record_stream).

Test Plan:
- test_fully_shard_comm.py test_set_reduce_scatter_max_input_buffers
  (8 subtests over mesh shape x reshard_after_forward x max_input_buffers in
  {1, 2}, under bf16 mixed precision): passes
- Local 4xH100, FSDP 1D + HSDP 2x2: sharded grads bitwise-identical to the
  default at max_input_buffers in {1, 2, large}, including a long-RS stress run.
- Memory (6 blocks, 8192/16384, batch 512, bf16, reshard_after_forward=False):
  default(=1) 6.11 GB; large-cap 6.80 (+0.70), 2 6.11, 1 6.11 (== default).
- Long-RS trace, default vs large-cap: compute-stream gaps >500us drop 7 -> 3;
  the default's five interspersed 1.2-2.9 ms per-layer recycle stalls collapse to
  a single end-of-backward drain (off the critical path).

Co-authored-by: Lei Tian <[email protected]>
ghstack-source-id: c4cb640
Pull-Request: #186000
weifengpy added a commit that referenced this pull request Jun 3, 2026
…-scatter input buffers)

By default FSDP2 keeps a single reduce-scatter copy-in (chunk_cat) input buffer
in flight: the copy-in runs on the compute stream, and the buffer is recycled in
FSDP::post_backward_rs_wait by waiting the compute stream on the previous
reduce-scatter before the next copy-in reuses it. So each layer's post_backward
waits on the previous layer's reduce-scatter -- and when the reduce-scatter is
exposed, that recycle wait stalls the compute stream (measured 37.6 ms/step of
compute-stream idle, 100% gated by an RS finishing, on an omnifm_v5 trace).
There is no compute->RS data dependency -- backward never reads the reduced
gradient; only the optimizer does, after backward -- so the coupling is pure
buffer-reuse bookkeeping.

This exposes the in-flight buffer count -- currently hardwired to 1 -- as a
per-module tunable:

    FSDPModule.set_reduce_scatter_max_input_buffers(
        max_input_buffers: int, *, recurse: bool = True
    )

Raising the cap lets the next copy-in write a fresh buffer instead of waiting on
the in-flight reduce-scatter, removing the stall. max_input_buffers=1 is the default
(today's single-buffer behavior); a small value (e.g. 2) removes the stall when
>= the reduce-scatter pipeline depth while bounding peak memory; larger values
retain more buffers for deeper overlap at higher peak memory.

Design:
- The copy-in stays on the compute stream (foreach_reduce is unchanged from
  upstream). The change is purely the recycle policy.
- Generalize the existing recycle (FSDP::post_backward_rs_wait, before the
  reduce) to keep at most max_input_buffers buffers: reclaim the oldest --
  current_stream.wait_event(oldest_rs) then drop the keepalive ref (no
  record_stream) -- until fewer than max_input_buffers remain, before this layer
  appends one more. max_input_buffers=1 drains to zero and reuses the freed buffer,
  byte-identical to upstream. The reclaim is a no-op once max_input_buffers >= the
  reduce-scatter pipeline depth (removes the stall with zero added wait in the
  overlapped regime); below it the stall persists -- the memory<->overlap dial.
- Grads free promptly in compute-stream order (as upstream); only the retained
  reduce-scatter input buffers cost extra memory.

The cap is a positive int (no unbounded mode): a finite cap >= the pipeline
depth already removes the stall with bounded memory, and "retain everything" is
just a large cap, so an unbounded sentinel would only add an unbounded-memory
footgun.

Fully gated: the default max_input_buffers=1 is byte-identical to upstream (same
recycle, no extra stream, no record_stream).

Test Plan:
- test_fully_shard_comm.py test_set_reduce_scatter_max_input_buffers
  (8 subtests over mesh shape x reshard_after_forward x max_input_buffers in
  {1, 2}, under bf16 mixed precision): passes
- Local 4xH100, FSDP 1D + HSDP 2x2: sharded grads bitwise-identical to the
  default at max_input_buffers in {1, 2, large}, including a long-RS stress run.
- Memory (6 blocks, 8192/16384, batch 512, bf16, reshard_after_forward=False):
  default(=1) 6.11 GB; large-cap 6.80 (+0.70), 2 6.11, 1 6.11 (== default).
- Long-RS trace, default vs large-cap: compute-stream gaps >500us drop 7 -> 3;
  the default's five interspersed 1.2-2.9 ms per-layer recycle stalls collapse to
  a single end-of-backward drain (off the critical path).

Co-authored-by: Lei Tian <[email protected]>
ghstack-source-id: c4cb640
Pull-Request: #186000
@linux-foundation-easycla

linux-foundation-easycla Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: leitian / name: Lei Tian (6573795)
  • ✅ login: weifengpy / name: Wei Feng (6573795)

weifengpy added a commit that referenced this pull request Jun 3, 2026
…-scatter input buffers)

By default FSDP2 keeps a single reduce-scatter copy-in (chunk_cat) input buffer
in flight: the copy-in runs on the compute stream, and the buffer is recycled in
FSDP::post_backward_rs_wait by waiting the compute stream on the previous
reduce-scatter before the next copy-in reuses it. So each layer's post_backward
waits on the previous layer's reduce-scatter -- and when the reduce-scatter is
exposed, that recycle wait stalls the compute stream (measured 37.6 ms/step of
compute-stream idle, 100% gated by an RS finishing, on an omnifm_v5 trace).
There is no compute->RS data dependency -- backward never reads the reduced
gradient; only the optimizer does, after backward -- so the coupling is pure
buffer-reuse bookkeeping.

This exposes the in-flight buffer count -- currently hardwired to 1 -- as a
per-module tunable:

    FSDPModule.set_reduce_scatter_max_input_buffers(
        max_input_buffers: int, *, recurse: bool = True
    )

Raising the cap lets the next copy-in write a fresh buffer instead of waiting on
the in-flight reduce-scatter, removing the stall. max_input_buffers=1 is the default
(today's single-buffer behavior); a small value (e.g. 2) removes the stall when
>= the reduce-scatter pipeline depth while bounding peak memory; larger values
retain more buffers for deeper overlap at higher peak memory.

Design:
- The copy-in stays on the compute stream (foreach_reduce is unchanged from
  upstream). The change is purely the recycle policy.
- Generalize the existing recycle (FSDP::post_backward_rs_wait, before the
  reduce) to keep at most max_input_buffers buffers: reclaim the oldest --
  current_stream.wait_event(oldest_rs) then drop the keepalive ref (no
  record_stream) -- until fewer than max_input_buffers remain, before this layer
  appends one more. max_input_buffers=1 drains to zero and reuses the freed buffer,
  byte-identical to upstream. The reclaim is a no-op once max_input_buffers >= the
  reduce-scatter pipeline depth (removes the stall with zero added wait in the
  overlapped regime); below it the stall persists -- the memory<->overlap dial.
- Grads free promptly in compute-stream order (as upstream); only the retained
  reduce-scatter input buffers cost extra memory.

The cap is a positive int (no unbounded mode): a finite cap >= the pipeline
depth already removes the stall with bounded memory, and "retain everything" is
just a large cap, so an unbounded sentinel would only add an unbounded-memory
footgun.

Fully gated: the default max_input_buffers=1 is byte-identical to upstream (same
recycle, no extra stream, no record_stream).

Test Plan:
- test_fully_shard_comm.py test_set_reduce_scatter_max_input_buffers
  (8 subtests over mesh shape x reshard_after_forward x max_input_buffers in
  {1, 2}, under bf16 mixed precision): passes
- Local 4xH100, FSDP 1D + HSDP 2x2: sharded grads bitwise-identical to the
  default at max_input_buffers in {1, 2, large}, including a long-RS stress run.
- Memory (6 blocks, 8192/16384, batch 512, bf16, reshard_after_forward=False):
  default(=1) 6.11 GB; large-cap 6.80 (+0.70), 2 6.11, 1 6.11 (== default).
- Long-RS trace, default vs large-cap: compute-stream gaps >500us drop 7 -> 3;
  the default's five interspersed 1.2-2.9 ms per-layer recycle stalls collapse to
  a single end-of-backward drain (off the critical path).

Co-authored-by: Lei Tian <[email protected]>
ghstack-source-id: c4cb640
Pull-Request: #186000
@weifengpy
weifengpy requested a review from anshul-si June 3, 2026 23:05
[ghstack-poisoned]

Co-authored-by: Lei Tian <[email protected]>
@weifengpy
weifengpy force-pushed the gh/weifengpy/148/head branch from 6dd264c to 6573795 Compare June 3, 2026 23:10
@anshul-si

Copy link
Copy Markdown
Contributor

@claude review this pr

@claude

claude Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Claude finished @anshul-si's task in 1m 19s —— View job


PR Review: [FSDP2] Add set_reduce_scatter_max_input_buffers

  • Gather context and read changed files
  • Analyze implementation correctness
  • Review test coverage
  • Provide review feedback

Overall: Well-designed change with a clean API. The logic is correct and the default behavior is preserved. A few observations below.


Correctness

The core logic change in _fsdp_param_group.py:651-657 is sound:

states = self.comm_ctx.reduce_scatter_states
while len(states) >= max_input_buffers:
    oldest = states.pop(0)
    if oldest.event is not None:
        self.device_handle.current_stream().wait_event(oldest.event)
    del oldest

When max_input_buffers=1, the while loop drains all states (the list had 1 entry from the previous layer, so len(states) >= 1 → pop it → list is empty → exit). This matches the old behavior of clearing the entire list each layer. ✅

The end-of-backward cleanup in _fsdp_state.py:416-419 correctly drains all remaining states regardless of max_input_buffers, ensuring no dangling buffers survive past backward. ✅

The _reset_iter_state path (_fsdp_state.py:478-481) also iterates and clears all remaining states — safe with multiple buffers. ✅


Minor Issues

1. list.pop(0) is O(n) — _fsdp_param_group.py:653

With max_input_buffers likely being 2–4 in practice, this is fine and arguably simpler than collections.deque. However, if someone sets a large cap (e.g., 32 on a deep model where backward accumulates states), each layer's reclaim loop shifts O(n) elements. Worth noting as a theoretical concern only — in practice the loop body runs 0–1 times for typical caps.

2. Validation could also reject non-int values — _fully_shard.py:736

The current check if max_input_buffers < 1 would accept 1.5 without error (though it would work fine since len(states) >= 1.5 is valid Python). Since the docstring says "positive int", consider if not isinstance(max_input_buffers, int) or max_input_buffers < 1 for strictness. Low priority — the type annotation already constrains this.

3. Test gap: no test for invalid input — The test doesn't exercise the ValueError path (passing 0 or negative). Very minor, but a one-liner assertRaises would complete coverage of the public API validation.


Style / Comments

The comments in the reclaim block (_fsdp_param_group.py:635-645) are long relative to the repo's "minimize comments" guideline. The existing single-line comment they replaced (Wait on prior module's RS states...) was concise; the new one explains the same thing in 10 lines. Consider trimming to:

# Reclaim oldest RS input buffers, keeping at most max_input_buffers in
# flight. With default=1 this waits on the prior RS every layer; raising
# it lets the next copy-in use a fresh buffer instead of stalling.

Similarly, the field-level comment at line 219-225 could be tighter since the docstring on the public API already provides the full explanation.


Test Coverage

The test is thorough: it parameterizes over FSDP/HSDP, reshard_after_forward, and both max_input_buffers=1 (identity) and max_input_buffers=2. It validates numeric parity of both parameters and gradients over 3 training steps. This is good coverage for a scheduling-only change.

One consideration: the test confirms numerical correctness but doesn't verify that the buffer retention mechanism actually works (i.e., that with max_input_buffers=2 there's no stall). This is reasonable — verifying overlap is hard in a unit test and belongs to benchmarking.


Summary

This is a well-scoped, correct change. The API mirrors existing FSDP module setters (e.g., set_reduce_scatter_unused_params), the default preserves existing behavior byte-for-byte, and the test validates parity. The main feedback is cosmetic: the inline comments are longer than typical for this codebase.

Verdict: Looks good to land. The issues above are nits, not blockers.


@anshul-si anshul-si 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.

LGTM! From my understanding, this is also a similar solution of introducing flexibility in controlling number of buffers, but solving the opposite problem where instead of accumulating too much memory, now we don't have enough buffers, so the compute stream is blocked?

weifengpy added a commit that referenced this pull request Jun 5, 2026
…-scatter input buffers)

By default FSDP2 keeps a single reduce-scatter copy-in (chunk_cat) input buffer
in flight: the copy-in runs on the compute stream, and the buffer is recycled in
FSDP::post_backward_rs_wait by waiting the compute stream on the previous
reduce-scatter before the next copy-in reuses it. So each layer's post_backward
waits on the previous layer's reduce-scatter -- and when the reduce-scatter is
exposed, that recycle wait stalls the compute stream (measured 37.6 ms/step of
compute-stream idle, 100% gated by an RS finishing, on an omnifm_v5 trace).
There is no compute->RS data dependency -- backward never reads the reduced
gradient; only the optimizer does, after backward -- so the coupling is pure
buffer-reuse bookkeeping.

This exposes the in-flight buffer count -- currently hardwired to 1 -- as a
per-module tunable:

    FSDPModule.set_reduce_scatter_max_input_buffers(
        max_input_buffers: int, *, recurse: bool = True
    )

Raising the cap lets the next copy-in write a fresh buffer instead of waiting on
the in-flight reduce-scatter, removing the stall. max_input_buffers=1 is the default
(today's single-buffer behavior); a small value (e.g. 2) removes the stall when
>= the reduce-scatter pipeline depth while bounding peak memory; larger values
retain more buffers for deeper overlap at higher peak memory.

Design:
- The copy-in stays on the compute stream (foreach_reduce is unchanged from
  upstream). The change is purely the recycle policy.
- Generalize the existing recycle (FSDP::post_backward_rs_wait, before the
  reduce) to keep at most max_input_buffers buffers: reclaim the oldest --
  current_stream.wait_event(oldest_rs) then drop the keepalive ref (no
  record_stream) -- until fewer than max_input_buffers remain, before this layer
  appends one more. max_input_buffers=1 drains to zero and reuses the freed buffer,
  byte-identical to upstream. The reclaim is a no-op once max_input_buffers >= the
  reduce-scatter pipeline depth (removes the stall with zero added wait in the
  overlapped regime); below it the stall persists -- the memory<->overlap dial.
- Grads free promptly in compute-stream order (as upstream); only the retained
  reduce-scatter input buffers cost extra memory.

The cap is a positive int (no unbounded mode): a finite cap >= the pipeline
depth already removes the stall with bounded memory, and "retain everything" is
just a large cap, so an unbounded sentinel would only add an unbounded-memory
footgun.

Fully gated: the default max_input_buffers=1 is byte-identical to upstream (same
recycle, no extra stream, no record_stream).

Test Plan:
- test_fully_shard_comm.py test_set_reduce_scatter_max_input_buffers
  (8 subtests over mesh shape x reshard_after_forward x max_input_buffers in
  {1, 2}, under bf16 mixed precision): passes
- Local 4xH100, FSDP 1D + HSDP 2x2: sharded grads bitwise-identical to the
  default at max_input_buffers in {1, 2, large}, including a long-RS stress run.
- Memory (6 blocks, 8192/16384, batch 512, bf16, reshard_after_forward=False):
  default(=1) 6.11 GB; large-cap 6.80 (+0.70), 2 6.11, 1 6.11 (== default).
- Long-RS trace, default vs large-cap: compute-stream gaps >500us drop 7 -> 3;
  the default's five interspersed 1.2-2.9 ms per-layer recycle stalls collapse to
  a single end-of-backward drain (off the critical path).

Co-authored-by: Lei Tian <[email protected]>
ghstack-source-id: 30fb713
Pull-Request: #186000
[ghstack-poisoned]

Co-authored-by: Lei Tian <[email protected]>
@weifengpy

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jun 5, 2026
@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

@weifengpy

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge -f "non-related CI errors"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

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

@weifengpy weifengpy added release notes: distributed (fsdp2) release notes category and removed release notes: distributed (fsdp) release notes category labels Jun 8, 2026
pytorchmergebot pushed a commit that referenced this pull request Jun 10, 2026
…186335)

By default FSDP2 runs all-gather and reduce-scatter on separate CUDA streams but
through the same process group -- one NCCL communicator, which processes one
collective at a time and so serializes them on the wire. This adds an opt-in
FSDPModule API to give reduce-scatter its own communicator:

    FSDPModule.set_separate_reduce_scatter_group(enable=True, *, recurse=True)

When enabled, FSDP creates a dedicated process group over the shard ranks
(dist.new_group), one per distinct set of shard ranks (typically one
communicator), so reduce-scatter and all-gather can progress concurrently when
the network can sustain it; enable=False resets to the shared group. The default
is unchanged -- reduce-scatter shares the shard process group -- so this is
purely opt-in and creates no extra communicators unless requested.

This redesigns the approach explored in (closed) PR #177015, which made the
separate communicator the unconditional default (and created one even for
post-forward meshes); here it is an opt-in toggle.

Test Plan:
```
python test/distributed/_composable/fsdp/test_fully_shard_overlap.py \
  TestFullyShardOverlap.test_set_separate_reduce_scatter_group \
  TestFullyShardOverlap.test_fully_shard_backward_comm_overlap
```
Both pass on 4xH100:
- test_set_separate_reduce_scatter_group: default shares the shard PG; enabling
  creates one dedicated PG shared across same-rank-set meshes; disabling resets
  to the shared PG.
- test_fully_shard_backward_comm_overlap: real backward AG/RS overlap (large
  matmuls + collectives) is no slower than a serialized single-communicator
  reference.

Authored with Claude.

Co-authored-by: Lei Tian <[email protected]>
Pull Request resolved: #186335
Approved by: https://github.com/anshul-si
ghstack dependencies: #186000

Co-authored-by: Lei Tian <[email protected]>
jemitche1 pushed a commit to jemitche1/pytorch that referenced this pull request Jun 13, 2026
…catter blocking backward compute (pytorch#186000)

FSDP keeps **one** reduce-scatter input buffer in flight: the compute stream must wait on the previous reduce-scatter before the next copy-in (`chunk_cat`) can reuse that buffer (`FSDP::post_backward_rs_wait`). When the reduce-scatter is exposed, that recycle wait stalls backward compute every layer — e.g. 37.6 ms/step of compute-stream idle, 100% gated by a reduce-scatter finishing, on an omnifm_v5 trace. There's no compute→reduce-scatter data dependency (backward never reads the reduced gradient), so the coupling is pure buffer-reuse bookkeeping.

This exposes the in-flight buffer count — hardwired to 1 — as a per-module tunable:

```python
FSDPModule.set_reduce_scatter_max_input_buffers(max_input_buffers: int, *, recurse: bool = True)
```

Raising it lets the next copy-in write a **fresh** buffer instead of waiting, removing the stall. `1` (default) keeps today's behavior; `2` clears the stall once it's `≥` the reduce-scatter pipeline depth while bounding peak memory; larger caps overlap deeper at higher memory.

**Design:** generalize the existing recycle to keep at most `max_input_buffers` buffers — reclaim the oldest (`current_stream.wait_event(oldest_rs)`, then drop the keepalive ref; no `record_stream`) before this layer appends one. `1` drains to zero and reuses the freed buffer → **byte-identical to upstream**, and the reclaim is a no-op once `≥` the pipeline depth. The copy-in stays on the compute stream (`foreach_reduce` unchanged) and grads free promptly, so only the retained input buffers cost memory. The cap is a positive int — no unbounded mode (a large cap already means "retain all").

Co-authored-by: Lei Tian <[email protected]>

Pull Request resolved: pytorch#186000
Approved by: https://github.com/anshul-si

Co-authored-by: Lei Tian <[email protected]>
jemitche1 pushed a commit to jemitche1/pytorch that referenced this pull request Jun 13, 2026
…ytorch#186335)

By default FSDP2 runs all-gather and reduce-scatter on separate CUDA streams but
through the same process group -- one NCCL communicator, which processes one
collective at a time and so serializes them on the wire. This adds an opt-in
FSDPModule API to give reduce-scatter its own communicator:

    FSDPModule.set_separate_reduce_scatter_group(enable=True, *, recurse=True)

When enabled, FSDP creates a dedicated process group over the shard ranks
(dist.new_group), one per distinct set of shard ranks (typically one
communicator), so reduce-scatter and all-gather can progress concurrently when
the network can sustain it; enable=False resets to the shared group. The default
is unchanged -- reduce-scatter shares the shard process group -- so this is
purely opt-in and creates no extra communicators unless requested.

This redesigns the approach explored in (closed) PR pytorch#177015, which made the
separate communicator the unconditional default (and created one even for
post-forward meshes); here it is an opt-in toggle.

Test Plan:
```
python test/distributed/_composable/fsdp/test_fully_shard_overlap.py \
  TestFullyShardOverlap.test_set_separate_reduce_scatter_group \
  TestFullyShardOverlap.test_fully_shard_backward_comm_overlap
```
Both pass on 4xH100:
- test_set_separate_reduce_scatter_group: default shares the shard PG; enabling
  creates one dedicated PG shared across same-rank-set meshes; disabling resets
  to the shared PG.
- test_fully_shard_backward_comm_overlap: real backward AG/RS overlap (large
  matmuls + collectives) is no slower than a serialized single-communicator
  reference.

Authored with Claude.

Co-authored-by: Lei Tian <[email protected]>
Pull Request resolved: pytorch#186335
Approved by: https://github.com/anshul-si
ghstack dependencies: pytorch#186000

Co-authored-by: Lei Tian <[email protected]>
@github-actions
github-actions Bot deleted the gh/weifengpy/148/head branch July 9, 2026 02:24
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…catter blocking backward compute (pytorch#186000)

FSDP keeps **one** reduce-scatter input buffer in flight: the compute stream must wait on the previous reduce-scatter before the next copy-in (`chunk_cat`) can reuse that buffer (`FSDP::post_backward_rs_wait`). When the reduce-scatter is exposed, that recycle wait stalls backward compute every layer — e.g. 37.6 ms/step of compute-stream idle, 100% gated by a reduce-scatter finishing, on an omnifm_v5 trace. There's no compute→reduce-scatter data dependency (backward never reads the reduced gradient), so the coupling is pure buffer-reuse bookkeeping.

This exposes the in-flight buffer count — hardwired to 1 — as a per-module tunable:

```python
FSDPModule.set_reduce_scatter_max_input_buffers(max_input_buffers: int, *, recurse: bool = True)
```

Raising it lets the next copy-in write a **fresh** buffer instead of waiting, removing the stall. `1` (default) keeps today's behavior; `2` clears the stall once it's `≥` the reduce-scatter pipeline depth while bounding peak memory; larger caps overlap deeper at higher memory.

**Design:** generalize the existing recycle to keep at most `max_input_buffers` buffers — reclaim the oldest (`current_stream.wait_event(oldest_rs)`, then drop the keepalive ref; no `record_stream`) before this layer appends one. `1` drains to zero and reuses the freed buffer → **byte-identical to upstream**, and the reclaim is a no-op once `≥` the pipeline depth. The copy-in stays on the compute stream (`foreach_reduce` unchanged) and grads free promptly, so only the retained input buffers cost memory. The cap is a positive int — no unbounded mode (a large cap already means "retain all").

Co-authored-by: Lei Tian <[email protected]>

Pull Request resolved: pytorch#186000
Approved by: https://github.com/anshul-si

Co-authored-by: Lei Tian <[email protected]>
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…ytorch#186335)

By default FSDP2 runs all-gather and reduce-scatter on separate CUDA streams but
through the same process group -- one NCCL communicator, which processes one
collective at a time and so serializes them on the wire. This adds an opt-in
FSDPModule API to give reduce-scatter its own communicator:

    FSDPModule.set_separate_reduce_scatter_group(enable=True, *, recurse=True)

When enabled, FSDP creates a dedicated process group over the shard ranks
(dist.new_group), one per distinct set of shard ranks (typically one
communicator), so reduce-scatter and all-gather can progress concurrently when
the network can sustain it; enable=False resets to the shared group. The default
is unchanged -- reduce-scatter shares the shard process group -- so this is
purely opt-in and creates no extra communicators unless requested.

This redesigns the approach explored in (closed) PR pytorch#177015, which made the
separate communicator the unconditional default (and created one even for
post-forward meshes); here it is an opt-in toggle.

Test Plan:
```
python test/distributed/_composable/fsdp/test_fully_shard_overlap.py \
  TestFullyShardOverlap.test_set_separate_reduce_scatter_group \
  TestFullyShardOverlap.test_fully_shard_backward_comm_overlap
```
Both pass on 4xH100:
- test_set_separate_reduce_scatter_group: default shares the shard PG; enabling
  creates one dedicated PG shared across same-rank-set meshes; disabling resets
  to the shared PG.
- test_fully_shard_backward_comm_overlap: real backward AG/RS overlap (large
  matmuls + collectives) is no slower than a serialized single-communicator
  reference.

Authored with Claude.

Co-authored-by: Lei Tian <[email protected]>
Pull Request resolved: pytorch#186335
Approved by: https://github.com/anshul-si
ghstack dependencies: pytorch#186000

Co-authored-by: Lei Tian <[email protected]>
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…catter blocking backward compute (pytorch#186000)

FSDP keeps **one** reduce-scatter input buffer in flight: the compute stream must wait on the previous reduce-scatter before the next copy-in (`chunk_cat`) can reuse that buffer (`FSDP::post_backward_rs_wait`). When the reduce-scatter is exposed, that recycle wait stalls backward compute every layer — e.g. 37.6 ms/step of compute-stream idle, 100% gated by a reduce-scatter finishing, on an omnifm_v5 trace. There's no compute→reduce-scatter data dependency (backward never reads the reduced gradient), so the coupling is pure buffer-reuse bookkeeping.

This exposes the in-flight buffer count — hardwired to 1 — as a per-module tunable:

```python
FSDPModule.set_reduce_scatter_max_input_buffers(max_input_buffers: int, *, recurse: bool = True)
```

Raising it lets the next copy-in write a **fresh** buffer instead of waiting, removing the stall. `1` (default) keeps today's behavior; `2` clears the stall once it's `≥` the reduce-scatter pipeline depth while bounding peak memory; larger caps overlap deeper at higher memory.

**Design:** generalize the existing recycle to keep at most `max_input_buffers` buffers — reclaim the oldest (`current_stream.wait_event(oldest_rs)`, then drop the keepalive ref; no `record_stream`) before this layer appends one. `1` drains to zero and reuses the freed buffer → **byte-identical to upstream**, and the reclaim is a no-op once `≥` the pipeline depth. The copy-in stays on the compute stream (`foreach_reduce` unchanged) and grads free promptly, so only the retained input buffers cost memory. The cap is a positive int — no unbounded mode (a large cap already means "retain all").

Co-authored-by: Lei Tian <[email protected]>

Pull Request resolved: pytorch#186000
Approved by: https://github.com/anshul-si

Co-authored-by: Lei Tian <[email protected]>
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ytorch#186335)

By default FSDP2 runs all-gather and reduce-scatter on separate CUDA streams but
through the same process group -- one NCCL communicator, which processes one
collective at a time and so serializes them on the wire. This adds an opt-in
FSDPModule API to give reduce-scatter its own communicator:

    FSDPModule.set_separate_reduce_scatter_group(enable=True, *, recurse=True)

When enabled, FSDP creates a dedicated process group over the shard ranks
(dist.new_group), one per distinct set of shard ranks (typically one
communicator), so reduce-scatter and all-gather can progress concurrently when
the network can sustain it; enable=False resets to the shared group. The default
is unchanged -- reduce-scatter shares the shard process group -- so this is
purely opt-in and creates no extra communicators unless requested.

This redesigns the approach explored in (closed) PR pytorch#177015, which made the
separate communicator the unconditional default (and created one even for
post-forward meshes); here it is an opt-in toggle.

Test Plan:
```
python test/distributed/_composable/fsdp/test_fully_shard_overlap.py \
  TestFullyShardOverlap.test_set_separate_reduce_scatter_group \
  TestFullyShardOverlap.test_fully_shard_backward_comm_overlap
```
Both pass on 4xH100:
- test_set_separate_reduce_scatter_group: default shares the shard PG; enabling
  creates one dedicated PG shared across same-rank-set meshes; disabling resets
  to the shared PG.
- test_fully_shard_backward_comm_overlap: real backward AG/RS overlap (large
  matmuls + collectives) is no slower than a serialized single-communicator
  reference.

Authored with Claude.

Co-authored-by: Lei Tian <[email protected]>
Pull Request resolved: pytorch#186335
Approved by: https://github.com/anshul-si
ghstack dependencies: pytorch#186000

Co-authored-by: Lei Tian <[email protected]>
jerrymannil pushed a commit to ROCm/pytorch that referenced this pull request Jul 29, 2026
…catter blocking backward compute (pytorch#186000)

FSDP keeps **one** reduce-scatter input buffer in flight: the compute stream must wait on the previous reduce-scatter before the next copy-in (`chunk_cat`) can reuse that buffer (`FSDP::post_backward_rs_wait`). When the reduce-scatter is exposed, that recycle wait stalls backward compute every layer — e.g. 37.6 ms/step of compute-stream idle, 100% gated by a reduce-scatter finishing, on an omnifm_v5 trace. There's no compute→reduce-scatter data dependency (backward never reads the reduced gradient), so the coupling is pure buffer-reuse bookkeeping.

This exposes the in-flight buffer count — hardwired to 1 — as a per-module tunable:

```python
FSDPModule.set_reduce_scatter_max_input_buffers(max_input_buffers: int, *, recurse: bool = True)
```

Raising it lets the next copy-in write a **fresh** buffer instead of waiting, removing the stall. `1` (default) keeps today's behavior; `2` clears the stall once it's `≥` the reduce-scatter pipeline depth while bounding peak memory; larger caps overlap deeper at higher memory.

**Design:** generalize the existing recycle to keep at most `max_input_buffers` buffers — reclaim the oldest (`current_stream.wait_event(oldest_rs)`, then drop the keepalive ref; no `record_stream`) before this layer appends one. `1` drains to zero and reuses the freed buffer → **byte-identical to upstream**, and the reclaim is a no-op once `≥` the pipeline depth. The copy-in stays on the compute stream (`foreach_reduce` unchanged) and grads free promptly, so only the retained input buffers cost memory. The cap is a positive int — no unbounded mode (a large cap already means "retain all").

Co-authored-by: Lei Tian <[email protected]>

Pull Request resolved: pytorch#186000
Approved by: https://github.com/anshul-si

Co-authored-by: Lei Tian <[email protected]>
jerrymannil pushed a commit to ROCm/pytorch that referenced this pull request Jul 29, 2026
…ytorch#186335)

By default FSDP2 runs all-gather and reduce-scatter on separate CUDA streams but
through the same process group -- one NCCL communicator, which processes one
collective at a time and so serializes them on the wire. This adds an opt-in
FSDPModule API to give reduce-scatter its own communicator:

    FSDPModule.set_separate_reduce_scatter_group(enable=True, *, recurse=True)

When enabled, FSDP creates a dedicated process group over the shard ranks
(dist.new_group), one per distinct set of shard ranks (typically one
communicator), so reduce-scatter and all-gather can progress concurrently when
the network can sustain it; enable=False resets to the shared group. The default
is unchanged -- reduce-scatter shares the shard process group -- so this is
purely opt-in and creates no extra communicators unless requested.

This redesigns the approach explored in (closed) PR pytorch#177015, which made the
separate communicator the unconditional default (and created one even for
post-forward meshes); here it is an opt-in toggle.

Test Plan:
```
python test/distributed/_composable/fsdp/test_fully_shard_overlap.py \
  TestFullyShardOverlap.test_set_separate_reduce_scatter_group \
  TestFullyShardOverlap.test_fully_shard_backward_comm_overlap
```
Both pass on 4xH100:
- test_set_separate_reduce_scatter_group: default shares the shard PG; enabling
  creates one dedicated PG shared across same-rank-set meshes; disabling resets
  to the shared PG.
- test_fully_shard_backward_comm_overlap: real backward AG/RS overlap (large
  matmuls + collectives) is no slower than a serialized single-communicator
  reference.

Authored with Claude.

Co-authored-by: Lei Tian <[email protected]>
Pull Request resolved: pytorch#186335
Approved by: https://github.com/anshul-si
ghstack dependencies: pytorch#186000

Co-authored-by: Lei Tian <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: distributed (fsdp2) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants