Skip to content

Harden ZeRO-1/2 offload gradient storage lifetime and stream ordering - #8632

Merged
sfc-gh-truwase merged 9 commits into
masterfrom
jeffra/913-fixes-master-sync-r2
Oct 2, 2026
Merged

sfc-gh-truwase merged 9 commits into
masterfrom
jeffra/913-fixes-master-sync-r2

Conversation

@jeffra

@jeffra jeffra commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Harden gradient storage lifetime and stream ordering for ZeRO-1/2 with optimizer offload (cpu or nvme). These protections are always on for offload and have no configuration options. They address ownership and synchronization risks found while debugging NaNs under CPU offload.

Changes

  • Oversized-gradient ownership: gradients larger than reduce_bucket_size are cloned into independent storage before reduction. Reduction and the D2H offload copy then read the clone.
  • Producer readiness: every bucket producer records an event, including oversized gradients. Reduction waits on all of them, with or without overlap_comm.
  • Bucket reuse: a contiguous IPG buffer records a reuse event when its consumer finishes, and later producers wait on it before writing into that buffer again.
  • Stream lifetimes: gradient tensors are record_stream'd on the streams that consume them.
  • Offload copy ordering: successive CPU-gradient writes are ordered across streams. Pending offload copies are waited on before CPU accumulator reloads, step(), reset_cpu_buffers, checkpoint loading (legacy and universal), and destroy().
  • The existing overlap_comm barrier (compute stream waits on the reduction stream) is kept. The new events only add ordering on top of it.

Scope

  • Covered: ZeRO-1 and ZeRO-2 with offload_optimizer set to cpu or nvme. Both stages use the same reduce_independent_p_g_buckets_and_remove_grads → copy_grads_in_partition D2H path, and offload already forces contiguous_gradients. Pipeline parallelism and DeepCompile are not excluded.
  • Not covered: ZenFlow, which overrides reduction and offload copies with its own ordering. A warning is logged when ZenFlow is combined with offload.
  • Unchanged: non-offloaded paths and ZeRO-3. Reduction thresholds, communication dtypes, and accumulation semantics are also unchanged.

Cost

Oversized gradients add one gradient-sized allocation and copy. Event tracking adds synchronization overhead and can extend storage lifetimes.

Tests

tests/unit/v1/zero/test_zero2_gradient_safety.py:

  • Unit tests for oversized-copy independence, producer and reuse waits, cross-stream CPU write ordering, the pageable-accumulator wait (default path, no accumulation flag), and waits before step, reset, and checkpoint load.
  • A constructor matrix covering stage, contiguous, and offload device (cpu, nvme, none).
  • Two-rank training against an independent full-batch reference: ZeRO-1/2, with and without offload, overlap_comm, and contiguous_gradients=false.
  • A CUDA stream-handoff test for oversized producers.

Ran locally (macOS, CPU accelerator, 2 ranks): 35 passed, 2 skipped (the CUDA-only tests). A multi-GPU NCCL run of offload + overlap is still pending.

🤖 Generated with Claude Code

…mulation

Protect ZeRO-2 CPU-offload gradients with independent storage for
oversized gradients, per-producer bucket readiness tracking, consumer
lifetime tracking before buffer reuse, and ordered CPU-gradient writes.
These are on by default for ZeRO-2 with CPU optimizer offload.

Add opt-in check_offload_gradients validation of CPU optimizer inputs and
opt-in per-parameter offload gradient accumulation.

When the CPU-offload Muon update rewrites gradients, recompute the grad
norm rather than reusing the one taken by the offload gradient check.

Signed-off-by: Jeff Rasley <jeff.rasley@snowflake.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@jeffra
jeffra force-pushed the jeffra/913-fixes-master-sync-r2 branch from 5e3922e to 4b9a44b Compare September 23, 2026 15:38
Comment thread deepspeed/runtime/zero/stage_1_and_2.py Resolved
Move CPU offload detection into the safety helper and accept partition_grads directly. Update both callers and compatibility tests without changing the eligibility policy.

Validation: 116 tests passed with DS_ACCELERATOR=cpu on Apple M2 Max (64 GiB RAM), including two-rank Gloo training; two CUDA-only tests skipped. All modified-file pre-commit checks passed.
Signed-off-by: Jeff Rasley <jeffra45@gmail.com>
@jeffra
jeffra marked this pull request as ready for review September 24, 2026 02:18

@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: c49a3ce24f

ℹ️ 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".

Comment thread deepspeed/runtime/zero/stage_1_and_2.py Resolved
Comment thread deepspeed/runtime/zero/stage_1_and_2.py Resolved
Keep compute_grad_norm in its original constructor slot ahead of the new offload safety options. Cover both boolean values with positional argument binding regression tests.

Validation: 118 tests passed with DS_ACCELERATOR=cpu on Apple M2 Max (64 GiB RAM), including two-rank Gloo training; two CUDA-only tests skipped. All modified-file pre-commit checks passed.
Signed-off-by: Jeff Rasley <jeffra45@gmail.com>
@sfc-gh-truwase

Copy link
Copy Markdown
Collaborator

Please slim #8632 to the automatic storage/lifetime/ordering fix only: oversized-gradient ownership, producer-ready and bucket-reuse events, stream lifetime tracking, and pending offload-copy ordering/waits. Neither default-false option is required to operate or validate that fix.

Please move accumulate_offload_gradients out: it changes accumulation, reset, checkpoint, memory, and transfer semantics. Default already accumulates across non-boundary backwards; the flag is not required for the wait path.

Please also remove check_offload_gradients: its sentinel/group-norm behavior belongs to #8638, while CPU-gradient scanning and forced BF16 overflow checking are separate diagnostic policy. step() already waits before consume.

Keep all default-path wait coverage, including rewriting the pageable-accumulator test without the accumulation flag. Also resolve the PP/DeepCompile/ZenFlow/NVMe policy explicitly so no supported configuration silently runs the known-unprotected path.

jeffra and others added 2 commits September 24, 2026 09:24
Remove opt-in gradient checking and accumulation options, keeping automatic storage and stream protections for ZeRO-2 optimizer offload. Update documentation and focused tests.

Signed-off-by: Jeff Rasley <jeffra45@gmail.com>
@sfc-gh-truwase

Copy link
Copy Markdown
Collaborator

The slim at 13283f4c6 matches the requested scope: always-on ZeRO-2 CPU/NVMe offload storage and ordering, knobs gone, DeepCompile/PP not silently gated out.

Please rewrite the title/body — they still describe the removed options and DeepCompile/PP exclusions.

Please either include ZeRO-1 + offload (same copy_grads_in_partition D2H path) or document why it is out of scope; the constructor matrix currently pins expected=False. Nits: confirm dropping current_stream().wait_stream(reduction_stream) on the safety+overlap path is intentional; the else: _record_gradient_stream arms in allreduce_and_copy* look like no-ops. A real multi-GPU NCCL run of the offload+overlap path would still help.

ZeRO-1 with optimizer offload uses the same reduce/copy_grads_in_partition
D2H path as ZeRO-2, so enable the protections for it too. Restore the
compute-waits-on-reduction barrier on the protected overlap path so the
events only add ordering on top of existing behavior, and drop the
record_stream fallbacks in allreduce_and_copy* that recorded tensors on
their allocation stream (no-ops).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Jeff Rasley <jeff.rasley@snowflake.com>
@jeffra jeffra changed the title Harden ZeRO-2 CPU-offload gradient storage, synchronization, and accumulation Harden ZeRO-1/2 offload gradient storage lifetime and stream ordering Sep 25, 2026
@sfc-gh-truwase

Copy link
Copy Markdown
Collaborator

The follow-up (81a252984) addresses the last review: ZeRO-1 offload is covered, the overlap wait_stream barrier is kept, the no-op record_stream fallbacks are gone, and the title/body match the diff.

A local multi-GPU NCCL run of offload + overlap is not a merge blocker; CI is sufficient.

@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Sep 30, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 30, 2026
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Oct 1, 2026
@sfc-gh-truwase

Copy link
Copy Markdown
Collaborator

The 10 modal-torch-latest failures are one issue, and it is in the test harness rather than the offload code.

_record_gradient_stream (stage_1_and_2.py) calls tensor.record_stream(stream) whenever offload safety is on and resolves_data_dependency() is False. make_optimizer in test_zero2_gradient_safety.py builds the parameter, its gradient, and the IPG buffer on CPU while using the real get_accelerator(). On CUDA that returns False, so record_stream runs on a CPU tensor, which aten does not implement. On a CPU/MPS accelerator it returns True and the call is skipped, which is why this was green locally. That also explains why only the cpu_offload=True parametrizations fail.

No production path is affected: every tensor reaching the three call sites is accelerator-resident (get_gradient_for_reduction returns the bit16 param.grad; the IPG buffers and temp_grad_buffer_for_gpu_offload are allocated on current_device_name()). The two-rank offload test in the same file passed on the GPU runner.

Fix is in the test: default make_optimizer(device=...) to get_accelerator().device_name() (keep the fp32 master partition on CPU, as it already is) and allocate original in test_oversized_copy_is_independent_and_preserves_routing on param.device. That matches real offload layout and actually exercises record_stream on GPU runners. Reproduced all 10 failures on a CPU box by flipping resolves_data_dependency() to False; with that harness change the suite stays green there.

One side note: in async_inplace_copy_grad_to_fp32_buffer_from_gpu, when a dtype conversion happens the recorded tensor is grad_accum, not the converted src_tensor the copy actually reads. Safe today (same stream), but imprecise.

CUDA runners take the record_stream path, which has no CPU kernel. Building those tensors on CPU made the offload cases fail with aten::record_stream.

Signed-off-by: tunji-ruwase_snow <tunji.ruwase@snowflake.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 1, 2026
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Oct 1, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 1, 2026
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Oct 1, 2026
Merged via the queue into master with commit c687df7 Oct 2, 2026
13 checks passed
@sfc-gh-truwase
sfc-gh-truwase deleted the jeffra/913-fixes-master-sync-r2 branch October 2, 2026 00:43
@tohtana tohtana added needs-gpu-test GPU testing is recommended to validate the changes in this PR. and removed needs-gpu-test GPU testing is recommended to validate the changes in this PR. labels Nov 10, 2026
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 23, 2026
…p_comm (deepspeedai#9031)

## Problem

With `overlap_comm=true`, ZeRO-1/2 enqueues gradient reduction on
`reduction_stream` and returns without synchronizing. Parameters larger
than `reduce_bucket_size` skip the contiguous IPG buffer and keep their
own gradient storage (`extra_large_param_to_reduce`). After
`average_tensor()` queues the reduction, ranks that do not own such a
parameter release it immediately:

```python
if not self.is_param_in_current_partition[param_id]:
    if self.overlap_comm and self.contiguous_gradients is False:
        self.previous_reduced_grads[comm_dtype].append(param)
    else:
        self.clear_grad_attribute(param)   # param.grad = None
```

Regular parameters are safe here: their `grad.data` was rebound to the
persistent IPG bucket buffer, so clearing `param.grad` only drops a
reference. Oversized gradients never get that rebinding, so their
storage goes back to the caching allocator while the reduction stream
may still be reading it. The allocator can then reuse it for a tensor
allocated on the compute stream (in our case an activation recomputed by
gradient checkpointing), corrupting the gradient. In our 8-GPU run on
0.19.1 the weights turn NaN at step 3; on master the reduced gradient
holds values up to 3.4e38 (bf16 max) and the update is skipped.

Whether a block is exposed depends on how the gradient reaches the
collective. In the attached reproducer, a gradient that lies inside one
partition is passed to the collective as is, and its block is still
`active_pending_free` after `reduce_ipg_grads()` returns (checked with
`torch.cuda.memory_snapshot()`), so the compute stream cannot get it. A
weight cut by a partition boundary whose lower slice is smaller than
`reduce_bucket_size` behaves differently: `allreduce_and_scatter()`
batches the two slices, `flatten()` copies them on the reduction stream,
and nothing records that stream on the source. This is the case that
gets corrupted in the reproducer. It needs at least 3 ranks, because
with 2 a straddling weight is owned by both and never released.

Environment observed on:

- Model: Qwen2.5-7B-class backbone (hidden_size 3584, intermediate_size
18944, 28 layers), the affected `gate_proj` gradient is 67,895,296
elements, 5.29x `reduce_bucket_size`.
- Hardware: 8 GPUs, PCIe attached, no NVLink, bf16.
- DeepSpeed 0.19.1, PyTorch 2.13 nightly, NCCL 2.30.4, fused AdamW,
gradient checkpointing on, grad clip 1.0.
- ZeRO-2 with `overlap_comm=true`, `contiguous_gradients=true`,
`reduce_scatter=true`, `reduce_bucket_size=auto` (= 12,845,056), no
optimizer/parameter offload.
- The code path is unchanged on master (`b43c383f`), where
`_offload_gradient_safety_enabled` is `False` for this config.

## Still broken on master: NaN becomes a silently frozen run

On master (`b43c383f`, 0.19.10) the race is unchanged. What changed is
the symptom: deepspeedai#8035 (bf16 `check_grad_overflow` on by default) and deepspeedai#8638
(non-finite group norm is treated as overflow) detect the corrupted
gradient and skip the update, so the weights stay finite but the model
stops learning.

Same 8-GPU run, same data order, 40 optimizer steps, only `overlap_comm`
differs:

| | `overlap_comm=false` | `overlap_comm=true` |
|---|---|---|
| skipped updates | 0 / 40 | 39 / 40 (every step after the first) |
| reduced gradients | finite, max abs 0.10 to 0.38 | 380 to 3.0k
non-finite per step after step 1, max finite 3.4e38, `grad_norm=inf` |
| probe weight (`layers.19.mlp.gate_proj`) abs sum | changes on 35 of 39
steps | identical on all 39 later steps |
| mean loss, first 5 / last 5 steps | 1.022 / 0.765 | 1.023 / 1.003 |

The skip discards the update; it does not repair the gradient.

## Why the existing fixes don't cover this

- deepspeedai#7965 records the reduction stream on the reduction result and copy
destination buffers. It does not touch `extra_large_param_to_reduce`,
whose storage is the caller's `param.grad`.
- deepspeedai#8632 clones and `record_stream`s oversized gradients, but only when
`cpu_offload` is enabled (`_offload_gradient_safety_enabled`);
non-offloaded paths are explicitly unchanged.
- deepspeedai#8061 orders the multiple producers of the contiguous IPG bucket,
which oversized gradients bypass.

## Fix

Record the reduction stream on the oversized gradient storage before
handing it to `average_tensor()`:

```diff
@@ -2247,6 +2247,11 @@
                     extra_large_grad_reduc.data = extra_large_grad_reduc_for_average.data.view_as(extra_large_grad_reduc) if (not self.zenflow or self.extra_large_param_to_reduce[comm_dtype].dim() == 1) \
                         else extra_large_grad_reduc_for_average.data.view_as(extra_large_grad_reduc.transpose(0, 1))
 
+                    # Oversized gradients bypass the contiguous IPG buffer, so the
+                    # reduction reads the parameter's own storage, which non-owner
+                    # ranks release right after the reduction is enqueued.
+                    if self.overlap_comm and not get_accelerator().resolves_data_dependency():
+                        extra_large_grad_reduc_for_average.record_stream(self.reduction_stream)
                     self.average_tensor(extra_large_grad_reduc_for_average, comm_dtype)
                     del self.extra_large_param_to_reduce[comm_dtype]
                 else:
```

`extra_large_grad_reduc_for_average` shares storage with `param.grad`,
so the mark lands on the block that `clear_grad_attribute()` later
releases. The guards follow the existing `record_stream` call sites in
this file.

## Cost

One `record_stream` per oversized parameter per step: the block stays
alive until the reduction stream drains instead of being recycled
immediately. Measured on 8 GPUs (bf16, fused AdamW, gradient
checkpointing, 12 steps, `record_stream` applied to the oversized
`param.grad`, same storage as in the diff), against the same run without
it: mean step time 3.542 s to 3.565 s (+0.6%), peak allocated 37.35 GB
in both, peak reserved 45.0 to 46.6 GB per rank without and 45.3 to 45.6
GB with. NaN at step 3 is gone for 3 runs x 30 steps.

## Test plan

A standalone reproducer is attached
([repro_oversized_grad_race.py](https://github.com/user-attachments/files/34519304/repro_oversized_grad_race.py),
3 ranks, `torchrun`). It runs ZeRO-2 with `overlap_comm=true`,
`contiguous_gradients=true`, oversized weights and gradient
checkpointing, and shifts the partition boundary so one weight has a
lower slice below `reduce_bucket_size` (the header prints the slices
DeepSpeed produced). To make the race deterministic it delays the
reduction stream with `torch.cuda._sleep` before the collective, and
`--reuse emulate` makes the compute stream allocate the freed block and
overwrite it, standing in for the recomputed activation. With `--reuse
natural` the allocator is left alone, and this small model stays clean
on unpatched code, so the script shows the missing protection rather
than a natural occurrence.

```
DeepSpeed 0.19.1           : [result] WEIGHTS_NAN, step 1 (reused=2, grad_max_abs 3.3e29)
DeepSpeed 0.19.1 + this fix: [result] CLEAN, 6 steps (reused=0)
master b43c383f (0.19.10)  : [result] GRADIENTS_CORRUPTED, 6/6 updates skipped (grad_norm=inf, loss flat)
```

Signed-off-by: miaTian99 <1194695379@qq.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: pengdurice <pengduhit@gmail.com>
Co-authored-by: Hongwei Chen <33092912+hwchen2017@users.noreply.github.com>
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.

5 participants