Repository navigation
ZeRO-1/2: order gradient bucket reads, rewrites and releases across streams without overlap_comm - #9133
Draft
seanbell wants to merge 5 commits into
Draft
ZeRO-1/2: order gradient bucket reads, rewrites and releases across streams without overlap_comm#9133seanbell wants to merge 5 commits into
seanbell wants to merge 5 commits into
Conversation
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 <noreply@anthropic.com>
…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 <noreply@anthropic.com>
… 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Without
overlap_comm, order the ZeRO-1/2 gradient bucket across streams: the reduction waits for every stream thatproduced 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 thegradients themselves waits for their producers too. This reuses the producer events, reuse events and
record_streamcalls DeepSpeed already makes for the CPU-offloaded optimizer. With
overlap_comm, the existingcopy_streamswait (#8080, for #8061) now also covers the producer of an oversizedgradient.
Problem
Line numbers are for
master40a9f40b, filedeepspeed/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), andaverage_tensorreduces it. Agradient larger than
reduce_bucket_sizeis 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:oversized gradient until the stream that produced it has finished writing it.
has finished reading it. The reduction also writes the reduced values back into the bucket (
buf.copy_(synced)inallreduce_and_copy), so the hook's copy must also come after that write.it, and the next allocation on that stream may reuse it at once, unless
record_streamnamed the other streamsstill 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 onthe allocating stream can overwrite it before the reduction has read it.
setup_bucketsallocates the bucket on the stream of whichever hook runs first in abackward (
:3383). The caching allocator can return a block that a tensor freed on that stream still has queuedwork 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_tensorgroups the bucket's slices by process group (and destination rank),and each group's
allreduce_bucketflattens its slices (:2452) and then runs a collective (:2469) on the reducingstream. 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_fallbackand itsfp32-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:
_offload_gradient_safety_enabled,:234): orderings 1 and 2 use events. Every hookrecords a producer event (
_record_bucket_producer,:1522) that the reduction waits on (:1708-1714). Everyflush 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_commwithout offload: the reduction stream waits on the streams recorded incopy_streams(
:1579-1580,:1715-1727). Oversized gradients are not recorded, so their reduction waits on the flushing hook'sstream instead (
:1724), which need not be the producer's. Buffer reuse is ordered by the double buffer and thecurrent-stream barrier (
:1727); per-buffer reuse ordering is the subject of ZeRO-1/2: synchronize IPG buffer reuse per buffer #8366. The epilogue synchronizes thedevice before releasing the bucket; recording the reduction stream on oversized gradients is the subject of ZeRO-1/2: record reduction stream on oversized gradients under overlap_comm #9031.
overlap_commdefaults to false below stage 3): none of the four. Thereduction runs on the flushing hook's current stream (
:1729) without waiting on any other stream, nothing orders alater 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_streamcalls are gated on_offload_gradient_safety_enabled,but none of the first three hazards depends on offload. Without
overlap_commthe same single buffer, and eachoversized 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
_gradient_stream_safety_enabled(): true with the offload protections (unchanged) or when neitheroverlap_commnor 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. Withoutoverlap_comm, thebucket and oversized gradients are now protected the same way with and without offload.
overlap_comm, record the producer stream incopy_streamsfor oversized gradients too (the recording movesout of the copy branch), so their reduction waits on the stream that produced them.
setup_bucketsallocates the buffers, record one event on the allocating stream and use it as every buffer'sreuse 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.
contiguous_gradients,reduce_ipg_gradswaits on the bucket's producer events before either fallback readsthe 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.pyagainst the merge base, of which 5 are the newhelper and 4 are reworded comments. Tests: 232 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:
overlap_command offload. Per hook: one event record on the hook's stream and, after the firstflush of a backward, one
wait_eventbefore each bucket copy. Per flush: onewait_eventper producer stream andone 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.
ordering that is needed; when hooks run on another stream, their copies now start after the previous flush's
collectives finish.
overlap_comm) andcopy_streams(overlap_commwithoutoffload). The earlier revision of this PR added a third (a
copy_streamswait withoutoverlap_comm); this revisionremoves it in favor of the existing events. Moving
overlap_commto 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_streamis a no-op when the recorded stream is the one that allocated the memory, so a single-streamrun 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=falsenow waits on the producer events it already recorded, before the fallback readsthe gradients.
overlap_command offload, the whole bucketpath (allocation, copies, flushes and write-backs) could run on the existing
reduction_stream, which would wait oneach 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: abehavior 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:test_bucket_accesses_are_ordered_across_hook_streams(replaces this PR's earlier producer-wait test),parametrized over
overlap_commandcpu_offload. It runs the real hook(
reduce_independent_p_g_buckets_and_remove_grads),reduce_ipg_gradsandaverage_tensor. The file'sFakeStreamandFakeEventnow carry a happens-before clock: an event remembers how far each stream had progressedwhen it was recorded, and
wait_event/wait_streammerge 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 thecurrent 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).
masterit fails without offload: withoutoverlap_commwith 8 unordered pairs, including the rewriteB2 -> A4; withoverlap_commwithD1 -> R3(the oversized gradient). The offload cells pass onmasterandhere.
pairs other than
B2 -> A4; with the reuse events left offload-only, it fails with exactlyB2 -> A4.test_released_gradient_waits_for_its_reduction(new), parametrized oncpu_offload. An oversized gradientproduced on one fake stream is reduced by the next flush on another and released by a rank that does not own it.
Tensor.record_streamis replaced by a recorder. The test checks that the memory the reduction read was recorded onthe 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_streamor a stream wait). It failswithout offload on
masterand on this PR's previous commit; the offload case passes on both.test_first_bucket_write_waits_for_the_allocating_stream(new).setup_bucketsruns on one fake stream thathas 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
masterand without this PR's allocation event.test_noncontiguous_reduction_waits_for_and_keeps_its_input(new). Without contiguous gradients, a gradientproduced 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 reducing stream is recorded on the gradient. It
fails on
masterand without this PR's fallback wait.test_cuda_bucket_rewrite_waits_for_reduction(new, CUDA only, parametrized oncpu_offload). It delays thereducing stream with
torch.cuda._sleepbefore the flush reads the bucket, then a hook on another stream writes thesame 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 withoutoffload and
overlap_comm. Written, not executed. Expected onmaster: 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 nowreached 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 8.4.2,
pytest-forked 1.7.5, DeepSpeed's
requirements/requirements.txtinstalled. The branch is based one35282bd;the change applies to
adcabcf9with line offsets only. The two-rank CPU training test in the file ran.The new test on master
X1 -> Y2reads: the first access on stream X and the second access on stream Y touch the same elements, and Y'saccess is not ordered after X's.
Compatibility matrix:
master, green herereduce_ipg_grads/average_tensor, fromreduce_gradientswithoutoverlap_comm)__add_grad_to_ipg_bucketcopies 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 thereoverlap_commoffoverlap_commonoverlap_comm_bucket_events_enabled()is false, and ZenFlow overridesaverage_tensorcontiguous_gradients=false(buffered_reduce_fallback),overlap_commofftorch.compile, gradient accumulationresolves_data_dependency()true are unaffected; the CPU accelerator is one of themNot validated at all: any accelerator run, multi-rank training,
torch.compile, convergence, throughput, peakmemory. Not demonstrated: a corrupted gradient on a device. The hazards are shown from the code and by the CPU test.
Not covered
overlap_commwithout offload when hooks run on several streams: ZeRO-1/2: synchronize IPG buffer reuse per buffer #8366's subject.overlap_commwithout offload: ZeRO-1/2: record reduction stream on oversized gradients under overlap_comm #9031's subject.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.
overlap_commwithout offload, which usescopy_streamsand the double buffer.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.
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 open PRs:overlap_command removes the current-stream barrier there. ThisPR does not change
overlap_comm's reuse ordering. They compose: this PR enables the existing reuse events onlywhen
overlap_commis off, and ZeRO-1/2: synchronize IPG buffer reuse per buffer #8366's per-buffer events apply only when it is on. Rebased on currentmaster,ZeRO-1/2: synchronize IPG buffer reuse per buffer #8366 could also use those
reuse_eventsinstead of adding its own list, by extending_bucket_events_enabled()tooverlap_comm. Both PRs edit thecopy_streamsrecording line, so whichever lands second needs a small rebase.overlap_commonly.overlap_comm. This PR makes the same lifetimeguarantee without
overlap_comm, through_record_gradient_streaminaverage_tensor, which also covers thebucket buffer. ZeRO-1/2: record reduction stream on oversized gradients under overlap_comm #9031 changes the oversized branch of
reduce_ipg_grads, which this PR does not touch, so they donot conflict; with both, every mode that does not resolve data dependencies records the reducing stream on an
oversized gradient.
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).
AI assistance (Claude) was used to write this change, its tests and this description.
🤖 Generated with Claude Code