Skip to content

ZeRO-1/2: order gradient bucket reads, rewrites and releases across streams without overlap_comm - #9133

Merged
sfc-gh-truwase merged 10 commits into
deepspeedai:masterfrom
seanbell:zero12-producer-stream-wait
Nov 24, 2026
Merged

sfc-gh-truwase merged 10 commits into
deepspeedai:masterfrom
seanbell:zero12-producer-stream-wait

Conversation

@seanbell

@seanbell seanbell commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary. Bug fix: without overlap_comm (the ZeRO-1/2 default), gradient hooks on more than one stream can race the
gradient bucket's reduction; this applies the stream ordering the CPU-offload path already uses. CPU-tested only.

Without overlap_comm, order the ZeRO-1/2 gradient bucket across streams: the reduction waits for every stream that
produced the bucket (or an oversized gradient), a hook that writes the bucket after a flush waits for that flush's
reduction, the first writes to a newly allocated bucket wait for the stream that allocated it, and memory a reduction
reads is not handed to new work before the reduction is done. Without contiguous_gradients, the reduction of the
gradients themselves waits for their producers too. This reuses the producer events, reuse events and record_stream
calls DeepSpeed already makes for the CPU-offloaded optimizer. With
overlap_comm, the existing copy_streams wait (#8080, for #8061) now also covers the producer of an oversized
gradient.

Status. This change, its tests and this description were written with an AI agent (Claude). The commits
carry the submitter's Signed-off-by. The change has not run on any accelerator (none was available); see
"Validation" for exactly what was and was not run. A maintainer marked the PR ready for review on 2026-11-23; a reviewer still needs to run
the CUDA tests below. Maintainers are welcome to push to this branch or to take the change over.

Problem

Line numbers are for master 40a9f40b, file deepspeed/runtime/zero/stage_1_and_2.py.

With contiguous gradients, each gradient hook copies its gradient into the shared IPG bucket on its current stream
(:1571). A hook whose gradient does not fit first flushes the bucket (:1537), and average_tensor reduces it. A
gradient larger than reduce_bucket_size is not copied; it is reduced in place at the next flush (:1564, :2311).
Four orderings are needed when hooks run on more than one stream, as #8061 reports under torch.compile:

  1. Read after write. The reduction must not read the bucket until every copy into it has finished, nor an
    oversized gradient until the stream that produced it has finished writing it.
  2. Write after read. After a flush, a hook must not write into the bucket buffer before the previous reduction
    has finished reading it. The reduction also writes the reduced values back into the bucket (buf.copy_(synced) in
    allreduce_and_copy), so the hook's copy must also come after that write.
  3. Release after read. PyTorch's caching allocator returns a freed block to the pool of the stream that allocated
    it, and the next allocation on that stream may reuse it at once, unless record_stream named the other streams
    still using it. A rank that does not own an oversized gradient releases it as soon as its flush has queued the
    reduction (clear_grad_attribute, :2354), and the bucket buffer is released at the end of each backward
    (_release_ipg_buffers, :946). If the reducing stream is not the stream that allocated that memory, new work on
    the allocating stream can overwrite it before the reduction has read it.
  4. Write after allocation. setup_buckets allocates the bucket on the stream of whichever hook runs first in a
    backward (:3383). The caching allocator can return a block that a tensor freed on that stream still has queued
    work on; stream order protects that work only from later work on the same stream. A hook on another stream that
    writes the new bucket before the first flush must wait for the allocating stream.

The reduction is not one read. average_tensor groups the bucket's slices by process group (and destination rank),
and each group's allreduce_bucket flattens its slices (:2452) and then runs a collective (:2469) on the reducing
stream. A collective holds its stream until every rank has joined. When one flush reduces more than one process group
(for example data-parallel and expert-data-parallel slices in the same bucket), the second group's slices are read
only after the first group's collective completes, and any reduction can be queued behind earlier collectives. During
that time, hooks on another stream can already be copying the next gradients into the same elements.

Without contiguous_gradients, a flush reduces the gradients themselves (buffered_reduce_fallback and its
fp32-preserving variant, :2317, :2322) on the flushing stream, so orderings 1 and 3 apply to them directly.

Hooks reach more than one stream in two known ways: the backward itself runs on several streams (#8061), or a
parameter's AccumulateGrad node, which records the stream current at its creation, outlives an iteration and keeps its
hooks on that stream after the current stream changes. PyTorch warns about the second case ("an AccumulateGrad node
created prior to the current iteration being kept alive"). ZeRO-1/2 itself keeps such nodes alive for the parameters a
rank holds a fragment of, through its fragment mappings; #9135 removes that. This PR orders the bucket whatever
the source.

Today:

  • CPU-offloaded optimizer (_offload_gradient_safety_enabled, :234): orderings 1 and 2 use events. Every hook
    records a producer event (_record_bucket_producer, :1522) that the reduction waits on (:1708-1714). Every
    flush that read the buffer records a reuse event (:2361-2365) that every later copy into that buffer waits on
    (:1567-1569). _record_gradient_stream (:1517) records each incoming gradient on its hook's stream (:1557)
    and the reduced tensor on the reducing stream (:1732).
  • overlap_comm without offload: the reduction stream waits on the streams recorded in copy_streams
    (:1579-1580, :1715-1727). Oversized gradients are not recorded, so their reduction waits on the flushing hook's
    stream instead (:1724), which need not be the producer's. Buffer reuse is ordered by the double buffer and the
    current-stream barrier (:1727); per-buffer reuse ordering is the subject of ZeRO-1/2: synchronize IPG buffer reuse per buffer #8366. The epilogue synchronizes the
    device before releasing the bucket, and since ZeRO-1/2: record reduction stream on oversized gradients under overlap_comm #9031 (merged after 40a9f40b) reduce_ipg_grads records the
    reduction stream on an oversized gradient before reducing it.
  • Neither (the ZeRO-1/2 default; overlap_comm defaults to false below stage 3): none of the four. The
    reduction runs on the flushing hook's current stream (:1729) without waiting on any other stream, nothing orders a
    later hook's copy (:1571) after the previous reduction, and nothing records the reducing stream on what it reads.

Root cause: the producer events, reuse events and record_stream calls are gated on _offload_gradient_safety_enabled,
but none of the first three hazards depends on offload. Without overlap_comm the same single buffer, and each
oversized gradient, is produced, reduced and released by hooks whose streams can differ, with or without offload. The
fourth is open in every mode: the reuse events are cleared with the buffers at the end of each backward, so nothing
orders the first fill of the next one.

Change

  • Add _gradient_stream_safety_enabled(): true with the offload protections (unchanged) or when neither
    overlap_comm nor ZenFlow is in use. The four places that record or wait on the bucket's producer and reuse events,
    and _record_gradient_stream, use it instead of _offload_gradient_safety_enabled. Without overlap_comm, the
    bucket and oversized gradients are now protected the same way with and without offload.
  • With overlap_comm, record the producer stream in copy_streams for oversized gradients too (the recording moves
    out of the copy branch), so their reduction waits on the stream that produced them.
  • After setup_buckets allocates the buffers, record one event on the allocating stream and use it as every buffer's
    reuse event, so the first fill's writers wait on it through the existing reuse wait; the first flush replaces it as
    before. This also applies with the CPU-offloaded optimizer, which had the same gap.
  • Without contiguous_gradients, reduce_ipg_grads waits on the bucket's producer events before either fallback reads
    the gradients and records the reducing stream on each of them. The reducing stream is chosen once at the top of
    reduce_ipg_grads; the removed branch picked the same stream in every case.

Production code: 30 additions and 22 deletions in stage_1_and_2.py against the merge base, of which 5 are the new
helper and 4 are reworded comments. Tests: 233 additions and 7 deletions. No config key, public API or checkpoint
content changes. ZenFlow behaves as before; the CPU-offload mode gains only the allocation event. Accelerators whose
resolves_data_dependency() is true record no events, as before.

Tradeoffs:

  • Cost without overlap_comm and offload. Per hook: one event record on the hook's stream and, after the first
    flush of a backward, one wait_event before each bucket copy. Per flush: one wait_event per producer stream and
    one event record. Per backward: one event record at allocation, which turns the first fill's copies into waits as
    well. This is what the offload path already does after its first flush. No host synchronization, no new buffers, no change to
    collectives or reduction order. When all hooks run on one stream, every wait is on an event that stream has already
    passed. Not measured on a device.
  • A rewrite waits for the whole previous reduction, collectives included. With a single buffer this is the
    ordering that is needed; when hooks run on another stream, their copies now start after the previous flush's
    collectives finish.
  • Two mechanisms remain: events (offload, or no overlap_comm) and copy_streams (overlap_comm without
    offload). The earlier revision of this PR added a third (a copy_streams wait without overlap_comm); this revision
    removes it in favor of the existing events. Moving overlap_comm to events too would change that mode's semantics
    (wait at record time instead of at flush time, no current-stream fallback) and overlap ZeRO-1/2: synchronize IPG buffer reuse per buffer #8366, so it is left alone.
  • record_stream is a no-op when the recorded stream is the one that allocated the memory, so a single-stream
    run gains only the call. When the streams differ, the allocator keeps the freed block until the reducing stream has
    passed the point where it was freed, which can hold that memory slightly longer.
  • contiguous_gradients=false now waits on the producer events it already recorded, before the fallback reads
    the gradients.
  • A single bucket stream was considered and only simulated. Without overlap_comm and offload, the whole bucket
    path (allocation, copies, flushes and write-backs) could run on the existing reduction_stream, which would wait on
    each hook's stream and record each gradient on itself, with the epilogue and that stream waiting on each other
    around the final flush. Every bucket access would then follow stream order whatever streams the hooks use, with no
    per-hook events. A CPU simulation of streams, collectives and the caching allocator found no unordered access or
    early release with it; it was not run on a device. This PR keeps the event design because the alternative moves the
    default path's collectives off the current stream, so they overlap backward compute as with overlap_comm: a
    behavior and performance change that needs device runs, where this PR reuses ordering the offload path already
    ships.

Tests

In tests/unit/v1/zero/test_zero2_gradient_safety.py. The CPU tests use this file's existing harness: an optimizer
built with __new__ (make_optimizer), fake streams and events in place of the accelerator's, and a recorder in place
of the collective (gradient_reduction_w_predivide or dist.all_reduce). Only the CUDA tests use real streams.

  • test_bucket_accesses_are_ordered_across_hook_streams (replaces this PR's earlier producer-wait test),
    parametrized over overlap_comm and cpu_offload. It runs the real hook
    (reduce_independent_p_g_buckets_and_remove_grads), reduce_ipg_grads and average_tensor. The file's
    FakeStream and FakeEvent now carry a happens-before clock: an event remembers how far each stream had progressed
    when it was recorded, and wait_event/wait_stream merge that into the waiting stream. Every write into the bucket
    (Tensor.copy_), every reduction (an in-place all-reduce) and the production of each gradient is an access on the
    current stream. The test fails if two overlapping accesses on different streams are not ordered. Scenario, bucket
    size 8: hooks on streams A, B, A, D. B's hook flushes A's gradient; the second hook on A writes elements that flush
    read; the oversized gradient's hook on D flushes again; a final flush on C reduces the oversized gradient in place.
    Incorrect behaviors it catches: (1) a reduction that is not ordered after another stream's copy into the bucket, or
    after the production of an oversized gradient it reduces; (2) a hook that writes bucket elements from another stream
    before the previous reduction of those elements is ordered before it. Any correct mechanism passes (stream waits or
    events).
    • On master it fails without offload: without overlap_comm with 8 unordered pairs, including the rewrite
      B2 -> A4; with overlap_comm with D1 -> R3 (the oversized gradient). The offload cells pass on master and
      here.
    • Each half was checked on its own: with the producer events left offload-only, the test fails with the seven
      pairs other than B2 -> A4; with the reuse events left offload-only, it fails with exactly B2 -> A4.
  • test_released_gradient_waits_for_its_reduction (new), parametrized on cpu_offload. An oversized gradient
    produced on one fake stream is reduced by the next flush on another and released by a rank that does not own it.
    Tensor.record_stream is replaced by a recorder. The test checks that the memory the reduction read was recorded on
    the reducing stream, or that its allocating stream is ordered after the reduction. Incorrect behavior it catches: a
    gradient released while the stream reducing it has not finished with it, which the caching allocator can then hand
    to new work on the allocating stream. Any correct mechanism passes (record_stream or a stream wait). It fails
    without offload on master and on this PR's previous commit; the offload case passes on both.
  • test_first_bucket_write_waits_for_the_allocating_stream (new). setup_buckets runs on one fake stream that
    has queued work, then a hook on another stream writes the bucket. The test checks that the write is ordered after
    that work. Incorrect behavior it catches: a first write to a new bucket that can race work still queued on the block
    the allocator reused. It fails on master and without this PR's allocation event.
  • test_noncontiguous_reduction_waits_for_and_keeps_its_input (new). Without contiguous gradients, a gradient
    produced on one fake stream is reduced by a flush on another, on a rank that does not own it. The test checks that
    the fallback's read is ordered after the producer, and that the gradient's memory is recorded on the reducing stream
    or its allocating stream is ordered after the read. It fails on master, without this PR's fallback wait, and
    without its record_stream.
  • test_cuda_bucket_rewrite_waits_for_reduction (new, CUDA only, parametrized on cpu_offload). It delays the
    reducing stream with torch.cuda._sleep before the flush reads the bucket, then a hook on another stream writes the
    same elements. A rewrite that is not ordered after the reduction changes the values the reduction reads.
    Written, not executed. Expected on master: the non-offload case fails.
  • test_cuda_producer_handoff (from the earlier revision): bucketed and oversized gradients, with and without
    offload and overlap_comm. Written, not executed. Expected on master: the three non-offload cases other than
    (bucketed, overlap_comm) fail.

In tests/unit/v1/zero/test_overlap_comm_record_stream.py, only a comment changes: the current-stream fallback is now
reached only by an empty bucket.

Validation

Hardware: CPU only (x86_64, Intel Xeon Platinum 8375C; no accelerator, so no driver version). Python 3.12.13, torch 2.15.0+cpu, pytest 9.2.0,
DeepSpeed's requirements/requirements.txt installed. The runs below were made on head 852e5b66, which merged master at f1d37eb2 (it includes #9031). The branch has since been rebased onto master at 6d6aa589 to add the sign-off, with the same changes.
The two-rank CPU training test in the file ran.

DS_ACCELERATOR=cpu pytest tests/unit/v1/zero/test_zero2_gradient_safety.py tests/unit/v1/zero/test_overlap_comm_record_stream.py
  this branch:                                                 70 passed, 10 skipped (the CUDA tests)
  same tests on master (f1d37eb2):                             5 failed, 65 passed, 10 skipped
pre-commit run --files deepspeed/runtime/zero/stage_1_and_2.py tests/unit/v1/zero/test_zero2_gradient_safety.py \
    tests/unit/v1/zero/test_overlap_comm_record_stream.py
  all hooks passed, no files modified
python ci/tests_fetcher.py --base f1d37eb2   # the merge base
  MODE: subset, 97 test files, both changed test files among them

Before the merge (head d36d9d46, based on e35282bd; pytest 8.4.2 with --forked) the same two files gave the same
counts, and with stage_1_and_2.py from 074c672f (before the last two commits) the two newest tests failed.

The new test on master
test_bucket_accesses_are_ordered_across_hook_streams[False-False]   (cpu_offload=False, overlap_comm=False)
E   AssertionError: assert ['A2 -> B2', 'A2 -> B3', 'B2 -> A4', 'A2 -> D2', 'B2 -> D2', 'B3 -> D2', 'A4 -> D2', 'D1 -> C1'] == []
test_bucket_accesses_are_ordered_across_hook_streams[False-True]    (cpu_offload=False, overlap_comm=True)
E   AssertionError: assert ['D1 -> R3'] == []
test_released_gradient_waits_for_its_reduction[False]                (cpu_offload=False)
E   assert (<FakeStream object> in set() or 0 >= 1)
test_first_bucket_write_waits_for_the_allocating_stream
E   AssertionError: assert [0] == [1]
test_noncontiguous_reduction_waits_for_and_keeps_its_input
E   AssertionError: assert [0] == [1]

X1 -> Y2 reads: the first access on stream X and the second access on stream Y touch the same elements, and Y's
access is not ordered after X's.

Compatibility matrix:

axis cell status
ZeRO stage 2, hooks reduce as they go CPU test with fake streams: red on master, green here
ZeRO stage 1 (reduces through the same reduce_ipg_grads/average_tensor, from reduce_gradients without overlap_comm) same code path; not separately tested
ZeRO stage 3 not touched: __add_grad_to_ipg_bucket copies into the bucket on the reduce stream itself, after waiting on the hook's stream and recording the gradient on it, so the orderings follow stream order there
offload none, overlap_comm off all four orderings: CPU tests
offload none, overlap_comm on oversized producer: CPU test. Buffer reuse (#8366) and the oversized gradient's release (#9031): not changed
offload CPU-offloaded optimizer, with and without overlap_comm unchanged; existing tests and the new CPU test pass. CUDA cases written, not run
offload ZenFlow not touched: _gradient_stream_safety_enabled() is false, and ZenFlow overrides average_tensor
precision bf16 buckets in the tests; the change is dtype-independent fp16/fp32 not separately tested
parallelism single process multi-rank, MoE/expert groups, sequence and pipeline parallelism not run
other contiguous_gradients=false (buffered_reduce_fallback), overlap_comm off producer wait and release: CPU test
other torch.compile, gradient accumulation not run
accelerators CUDA and every other non-CPU accelerator not run. Accelerators with resolves_data_dependency() true are unaffected; the CPU accelerator is one of them

Not validated at all: any accelerator run, multi-rank training, torch.compile, convergence, throughput, peak
memory. Not demonstrated: a corrupted gradient on a device. The hazards are shown from the code and by the CPU test.

Not covered

  • Bucket reuse under overlap_comm without offload when hooks run on several streams: ZeRO-1/2: synchronize IPG buffer reuse per buffer #8366's subject.
  • The fp32 compact partition shared by two communication dtypes. With torch autocast, one parameter group can
    have buckets of two communication dtypes. The first flush that touches the group's compact fp32 partition zeroes all
    of it on its stream; a flush of the other dtype on another stream adds to its own slices of the same partition and
    is not ordered after that zero. A single communication dtype is ordered through the bucket's reuse events.
  • The first fill's writes under overlap_comm without offload, which uses copy_streams and the double buffer.
  • An oversized gradient written through a live alias, without offload. A gradient larger than the bucket is
    reduced from the gradient tensor itself, not from a copy. An in-place write to that tensor through another
    reference before the reduction reads it is not ordered by this PR: in a CPU test on this head the reducer received
    the later value. With offload, or when the gradient fits the bucket, the staged copy is what is reduced.
  • ZenFlow (see the matrix).

Related work and duplicate check

Searched open PRs and issues for "8061", "copy_streams", "reuse_events", "ready_events", "IPG buffer reuse",
"bucket reuse stream", "average_tensor stream", "wait_stream ZeRO", "_offload_gradient_safety_enabled" and "write
after read bucket". No open PR orders the bucket without overlap_comm. Related PRs:

Sibling paths checked: ZeRO-3 (ordered by stream order, above; the bucket copy records the gradient on the reduce
stream), the CPU-offload path (it already covered orderings 1 to 3; it now also gets the allocation event),
ZenFlow (left alone), and the BF16 and fp16 optimizers (by reading the code: bf16_optimizer.py and runtime/fp16/
use no side streams; BF16's gradient hooks accumulate each gradient into that parameter's own fp32 slice, and its
reduction runs after the backward, so there is no shared bucket to order).

AI assistance (Claude) was used to write this change, its tests and this description.

🤖 Generated with Claude Code

@seanbell seanbell changed the title ZeRO-1/2: wait on bucket producer streams without overlap_comm ZeRO-1/2: order gradient bucket reads and rewrites across streams without overlap_comm Nov 20, 2026
@seanbell seanbell changed the title ZeRO-1/2: order gradient bucket reads and rewrites across streams without overlap_comm ZeRO-1/2: order gradient bucket reads, rewrites and releases across streams without overlap_comm Nov 20, 2026
@jeffra
jeffra marked this pull request as ready for review November 23, 2026 22:20
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T22:27:12.267336Z 852e5b6 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 852e5b66ff

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

opt, param, _ = make_optimizer(device="cuda")
@pytest.mark.parametrize("cpu_offload", [False, True])
@pytest.mark.parametrize("bucket_size", [4, 16], ids=["oversized", "bucketed"])
def test_cuda_producer_handoff(overlap, cpu_offload, bucket_size):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Run the stream-ordering fix on an actual accelerator

The commit's Validation section says these CUDA cases were written but never executed, while the reported CPU run cannot exercise the patch because CPU_Accelerator.resolves_data_dependency() returns true and skips the newly added event, wait, and record_stream branches. Because this changes training-loop gradient contents, fake-stream coverage does not establish that the affected no-overlap/offload matrix works with real asynchronous stream APIs; run these cases plus an end-to-end training case on accelerator hardware before merging.

AGENTS.md reference: AGENTS.md:L81-L82

Useful? React with 👍 / 👎.

with get_accelerator().stream(writer):
later.grad = torch.full_like(later, 9)
opt.reduce_independent_p_g_buckets_and_remove_grads(later, 0)
reducer.synchronize()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Wait for the writer stream before the test returns

In this CUDA test, the second hook queues its bucket copy on writer after waiting for the reuse event from reducer; synchronizing only reducer proves that the dependency source completed but does not wait for the downstream copy on writer. The function can therefore tear down and let the allocator reuse the IPG buffer while that copy is still in flight, intermittently contaminating later CUDA tests, so synchronize writer (or flush that final bucket) before returning.

Useful? React with 👍 / 👎.

seanbell and others added 7 commits November 23, 2026 23:24
Gradient hooks copy each gradient into the shared IPG bucket on the hook's
current stream. Without overlap_comm, the reduction then runs on the stream
of whichever hook triggers the flush. deepspeedai#8080 made the reduction wait on every
recorded producer stream, but only with overlap_comm, and only for bucket
copies.

- Record the producer stream in every mode, including for gradients larger
  than reduce_bucket_size, which are reduced in place instead of copied.
- Without overlap_comm, make the reducing stream wait on every recorded
  producer stream other than itself before the reduction reads the bucket.

When all hooks run on one stream nothing changes: the only recorded
producer is the reducing stream itself, so no wait is issued. Accelerators
that resolve data dependencies are unaffected.

Tests: a CPU test drives three gradient hooks on three fake streams and a
final flush on a fourth, and checks that each reduction's stream waited on
the stream that produced its gradients (bucketed and oversized, with and
without overlap_comm); it fails on the previous code. The CUDA handoff test
now also covers bucketed gradients and the non-offload path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Sean Bell <[email protected]>
…overlap_comm

Without overlap_comm, a hook that writes the gradient bucket after a flush
could run on another stream than the flush's reduction, which may not have
read the bucket yet: the reduction is queued behind collectives on its own
stream, for example when one flush reduces more than one process group.
DeepSpeed already orders this with a reuse event recorded after each flush
and waited on before every later bucket copy, together with producer events
the reduction waits on, but only for the CPU-offloaded optimizer.

- Use the existing producer and reuse events whenever overlap_comm and
  ZenFlow are off, not only with CPU offload. Offload mode is unchanged.
- This replaces the copy_streams wait the previous commit added for the
  non-overlap path, so that path and the offload path share one mechanism.
- With overlap_comm, copy_streams keeps recording the producer of an
  oversized gradient.

Tests: a CPU test drives four hooks on three fake streams and a final flush
on a fourth through the real hook, reduce_ipg_grads and average_tensor. The
fake streams track happens-before, and the test fails when two accesses to
the same elements on different streams are unordered. It replaces the
previous commit's producer-wait test and fails on master without offload
(both a reduction before another stream's copy and a rewrite before the
previous reduction). A CUDA test delays the reducing stream and rewrites
the bucket from another stream.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Signed-off-by: Sean Bell <[email protected]>
… done

Without overlap_comm and offload, a flush can reduce a gradient on another
stream than the one that allocated it: an oversized gradient produced by
one hook's stream is reduced by the next hook's flush. A rank that does not
own the gradient releases it right after the flush, and the caching
allocator can then hand its memory to new work on the allocating stream
before the reduction has read it. The same holds for the bucket buffer,
which is released at the end of each backward.

_record_gradient_stream already records the reduced tensor on the reducing
stream, and each incoming gradient on its hook's stream, but only with CPU
offload. Gate it on the same predicate as the producer and reuse events,
renamed to _gradient_stream_safety_enabled since it now covers both.
Offload, overlap_comm and ZenFlow are unchanged; record_stream is a no-op
when the tensor's allocation stream is the recorded one.

Test: an oversized gradient produced on one fake stream is reduced by a
flush on another and released by its non-owner; the test checks that the
reducing stream was recorded on that memory, or that its allocation stream
is ordered after the reduction. It fails on master and on the previous
commit without offload.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Sean Bell <[email protected]>
setup_buckets allocates the gradient bucket on the stream of whichever hook
runs first in a backward. The caching allocator can return a block that a
tensor freed on that stream still has queued work on; stream order protects
that work only from later work on the same stream. Until the first flush
records a reuse event, a hook on another stream writes the new bucket
without waiting on anything.

Record one event on the allocating stream after the buffers are allocated
and use it as every buffer's reuse event, so the first fill's writers wait
on it through the existing reuse wait; the first flush replaces it as
before. This applies where the reuse events are used (offload, or neither
overlap_comm nor ZenFlow) and not on accelerators that resolve data
dependencies.

Test: setup_buckets runs on one fake stream that has queued work, then a
hook on another stream writes the bucket; the test checks that the write is
ordered after that work. It fails on master and on the previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Sean Bell <[email protected]>
Without contiguous_gradients a flush reduces the gradients themselves
(buffered_reduce_fallback, or its fp32-preserving variant) on the flushing
stream. Hooks already record one producer event per stream for the bucket,
but nothing waited on them in this mode, and a rank that does not own a
gradient frees it right after the flush has queued its reduction.

Wait on the bucket's producer events before dispatching either fallback,
and record the reducing stream on each gradient, as the contiguous path
does. The reducing stream is now chosen once at the top of reduce_ipg_grads;
the removed branch picked the same stream in every case.

Test: a gradient produced on one fake stream is reduced without contiguous
gradients by a flush on another stream, on a rank that does not own it; the
test checks that the read is ordered after the producer and that the
reducing stream is recorded on the gradient. It fails on master and on the
previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Sean Bell <[email protected]>
With overlap_comm, reduce_ipg_grads now calls record_stream on an oversized
gradient before reducing it (deepspeedai#9031). The test's fake streams cannot be passed
to Tensor.record_stream, so replace Tensor.record_stream with a no-op instead
of stubbing only _record_gradient_stream, which calls it. record_stream
orders the release of memory, not the accesses this test checks, so the
test's assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Sean Bell <[email protected]>
…e allocation test

test_noncontiguous_reduction_waits_for_and_keeps_its_input required the
reducing stream to be recorded on the gradient. Accept either that or the
allocating stream being ordered after the read, as
test_released_gradient_waits_for_its_reduction does, so any correct release
ordering passes. Removing the fallback's record_stream still fails it.

test_first_bucket_write_waits_for_the_allocating_stream replaces
Tensor.record_stream with a no-op instead of stubbing the optimizer's own
_record_gradient_stream, so only the torch call that cannot take a fake
stream is faked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Sean Bell <[email protected]>
@seanbell
seanbell force-pushed the zero12-producer-stream-wait branch from 852e5b6 to 7f6a3e1 Compare November 23, 2026 23:24
Gxj230958 pushed a commit to Gxj230958/DeepSpeed that referenced this pull request Nov 24, 2026
…s alive from fragment mappings (deepspeedai#9135)

Build the low-precision fragment view in `get_hp_fragment_mapping` from
`lp_param.detach()`, so the mapping keeps the
parameter's storage but not its autograd history. Today the view holds
the parameter's AccumulateGrad node alive for
as long as the mapping lives, which pins the gradient hooks of every
parameter a rank holds a fragment of to the CUDA
stream that was current when the mapping was built. One changed line and
one comment line.

> **Status.** This change, its tests and this description were written
with an AI agent (Claude). The commit
> carries the submitter's `Signed-off-by`. The accelerator test below is
written and has not run (no accelerator was
> available). A maintainer marked the PR ready for review on 2026-11-23;
a reviewer still needs to run that
> test on a device. Maintainers are
> welcome to push to this branch or to take the change over.

## Problem

Line numbers are for `master` `adcabcf9`.

`get_hp_fragment_mapping` (`deepspeed/utils/tensor_fragment.py:394`)
builds

```python
lp_fragment_tensor = lp_param.flatten().narrow(0, lp_frag_address.start, lp_frag_address.numel)
```

with grad mode on. Because `lp_param` requires grad, the view has a
`grad_fn` whose next edge is the parameter's
AccumulateGrad node, and the mapping (`lp_param._hp_mapping`) keeps that
node alive. ZeRO-1/2 (`stage_1_and_2.py:855`)
and the BF16 optimizer (`bf16_optimizer.py:348`) build these mappings at
initialization and rebuild them whenever
`_link_all_hp_params` runs again (checkpoint loads and state reloads,
`stage_1_and_2.py:3920`, `:4094`, `:4114`), so the
node lives for the whole run.

PyTorch records the current stream when it creates an AccumulateGrad
node and runs that node, and the parameter's
post-accumulate-grad hooks, on that stream in every backward that reuses
the node. A node that is released at the end
of each iteration is recreated in the next forward on whatever stream is
current then. A node that is kept alive is
not. So if the current stream at `deepspeed.initialize` (or at a
checkpoint load) differs from the stream later
forwards and backwards run on, the hooks of the parameters this rank
holds a fragment of keep running on the old
stream while all other hooks run on the new one, and PyTorch warns:

```
The AccumulateGrad node's stream does not match the stream of the node that produced the incoming gradient. ...
This mismatch is caused by an AccumulateGrad node created prior to the current iteration being kept alive.
```

In ZeRO-1/2 those two groups of hooks fill and flush one shared gradient
bucket, so the split puts bucket accesses on
two streams; the extra cross-stream wait PyTorch inserts for every
kept-alive node is a cost even where nothing races.
Any library or user code that changes the thread's current stream after
`deepspeed.initialize` (or after a load)
triggers this.

## Change

```diff
-    lp_fragment_tensor = lp_param.flatten().narrow(0, lp_frag_address.start, lp_frag_address.numel)
+    # Detached: autograd history here would keep the parameter's AccumulateGrad node, and its stream, alive.
+    lp_fragment_tensor = lp_param.detach().flatten().narrow(0, lp_frag_address.start, lp_frag_address.numel)
```

Nothing needs the view's autograd history: the mapping reads and writes
`lp_fragment` only through `.data`
(`update_hp`, `update_lp`, `tensor_fragment.py:30-34`), and every other
reader uses `lp_fragment_address`. The detached
view shares the parameter's storage, so `update_lp` still writes the
parameter. Hooks registered with
`register_post_accumulate_grad_hook` (what `register_grad_hook` uses on
torch >= 2.1) are stored on the tensor and
read by whichever AccumulateGrad node runs, so recreating the node each
iteration does not lose them.

Not changed:
- The fp32 master view (`hp_fragment`) also has autograd history, but
its leaf (`single_partition_of_fp32_groups`,
`fp32_groups_flat_partition`) receives its gradient by assignment and is
never reached by a backward, so the node it
retains never runs. Detaching it would change
`zero_optimizer_storage_shard(param).requires_grad` for no behavior.
- On torch < 2.1, `register_grad_hook` registers on an AccumulateGrad
node obtained through `expand_as`. ZeRO-1/2
registers its hooks (`stage_1_and_2.py:724`) before it links the
fragments (`:752`), and the mapping did not keep that
earlier node alive either, so this path is unaffected (by reading; torch
2.0 not run).
- ZeRO-3 does not use these mappings.

This removes one way gradient hooks reach two streams. It does not order
the gradient bucket when hooks run on
several streams for other reasons (for example deepspeedai#8061); that is deepspeedai#9133.

## Tests

In `tests/unit/runtime/zero/test_zero_tensor_fragment.py`:

-
**`test_fragment_mapping_does_not_keep_the_gradient_accumulator_alive`**
(CPU). After `link_hp_params`, two
iterations each tag the AccumulateGrad node they use
(`torch.autograd.graph.get_gradient_edge(param).node`). The test
fails if the second iteration reuses the first one's node. On `master`:
`assert [False, True] == [False, False]` (the
  node created at link time is reused). Passes with this change.
- **`test_gradient_hook_runs_on_the_backward_stream_after_linking`**
(accelerators with streams; skipped where
`resolves_data_dependency()` is true, including CPU). Link on the
default stream, then run a backward under another
stream; the test checks that the post-accumulate-grad hook ran on that
stream. **Written, not executed.** Expected on
  `master`: the hook runs on the default stream.

## Validation

Hardware: CPU only (x86_64, Intel Xeon Platinum 8375C; no accelerator).
Python 3.12, torch 2.15.0+cpu, pytest 8.4.2,
pytest-forked 1.7.5, DeepSpeed's `requirements/requirements.txt`
installed.

```
pytest --forked tests/unit/runtime/zero/test_zero_tensor_fragment.py -k "accumulator_alive or backward_stream_after_linking or owned_fragment"
  this branch:                    3 passed, 1 skipped (the accelerator test)
  master (adcabcf), new tests:   1 failed (test_fragment_mapping_does_not_keep_the_gradient_accumulator_alive), 2 passed, 1 skipped
pytest --forked tests/unit/v1/zero/test_zero2_gradient_safety.py
  this branch:                    56 passed, 2 skipped (includes the two-rank CPU training test)
pytest --forked tests/unit/runtime/zero/test_zero_tensor_fragment.py -k "(none-1- or none-2- or cpu-2-) and not local or bf16_optimizer or Fp32GradAccum"
  this branch:                    36 passed, 17 skipped (ZeRO-1/2 get/set/update and fp32 accumulation on 2 CPU ranks;
                                  the BF16 optimizer cases skip on the CPU accelerator)
pre-commit run --files deepspeed/utils/tensor_fragment.py tests/unit/runtime/zero/test_zero_tensor_fragment.py
  all hooks passed
```

Re-run on the same head with `DS_ACCELERATOR=cpu`, torch 2.15.0+cpu and
pytest 9.2.0 (without `--forked`): the same
counts for all three commands. The new CPU test fails the same way on
`master` `f1d37eb2`, and the branch merges that
`master` without conflict; the first command gives the same result on
the merge.

Not measured: throughput and memory on a device. The change adds no
work; it removes the cross-stream wait described
above. CI: the CPU test runs in the CPU workflow; the accelerator test
is outside `tests/unit/v1`, which the PR-level GPU
test selection covers, so on a GPU it runs only in the nightly full run
after merge or when run by hand.

Compatibility matrix:

| axis | cell | status |
|---|---|---|
| optimizer | ZeRO-1/2 (`link_hp_params` from `stage_1_and_2.py`) | CPU
tests; the two-rank CPU training test in `test_zero2_gradient_safety.py`
passes |
| optimizer | BF16 optimizer (`bf16_optimizer.py`) | same factory; not
separately run |
| optimizer | ZeRO-3 | not touched |
| checkpoint | relink at load (`_link_all_hp_params`) | same factory; no
checkpoint format change |
| torch | >= 2.1 (`register_post_accumulate_grad_hook`) | CPU test |
| torch | 2.0 (node hook fallback) | unaffected by reading; not run |
| accelerators | CUDA and others with streams | accelerator test
written, not run |

No config key, public API or checkpoint content changes.

## Related work and duplicate check

Searched open and closed issues and PRs for "AccumulateGrad",
"AccumulateGrad stream", "kept alive", "stream
mismatch", "lp_fragment detach", "tensor_fragment detach" and
"hp_mapping autograd": nothing reports or changes this.
deepspeedai#9133 orders the ZeRO-1/2 gradient bucket across streams whatever splits
the hooks; the two changes are independent
and either can land first.

AI assistance (Claude) was used to write this change, its tests and this
description.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Sean Bell <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Olatunji Ruwase <[email protected]>
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Nov 24, 2026
Merged via the queue into deepspeedai:master with commit 039bfc9 Nov 24, 2026
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants