Skip to content

ZeRO-3: fix stale and lost gradients of unused parameters - #8981

Merged
xylian86 merged 4 commits into
deepspeedai:masterfrom
xylian86:xinyu/zero3-unused-param-grads
Nov 18, 2026
Merged

xylian86 merged 4 commits into
deepspeedai:masterfrom
xylian86:xinyu/zero3-unused-param-grads

Conversation

@xylian86

@xylian86 xylian86 commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Summary

ZeRO-3 keeps each param's gradient partition across steps and overwrites it only in micro-step 0. A param that
gets no gradient in a step (a skipped branch, an unused expert) therefore keeps its last gradient, and the optimizer
applies it again; ZeRO-1/2 give it a zero gradient. With this PR, a param's first gradient after step() or
zero_grad() overwrites its partition. At the accumulation boundary, the partitions that got no gradient are
zeroed, and with optimizer offload, every partition the optimizer has not received yet is copied to it.

Fixes

Before → after, 1 rank on GH200 (base 2d80cedd2):

  1. A param without a gradient in a step was updated again with its last gradient (SGD, largest weight change:
    2.358e-02 → 0).
  2. With gradient accumulation, a param first used after micro-step 0 added its gradient to the previous step's.
  3. With optimizer offload, the gradient of a param used only in earlier micro-steps never reached the optimizer
    (norm 0 → 0.17340).
  4. With fp16, an inf left in an unused param's partition made every later step overflow (skipped steps: 5 → 1 of
    5).
  5. A param used by two reentrant checkpoint segments kept one of its two gradients if they were in different
    buckets
    (2 ranks, norm 0.10933 → 0.27053).

A param's gradient partition persists across steps, and partition_grads
overwrote it only in micro-step 0. A param that got no gradient in a step
was stepped again with its last gradient. With optimizer offload, the
gradient of a param used only before the boundary micro-step never reached
the optimizer. With fp16, an inf left in an unused param's partition skipped
every later step.

partition_grads now overwrites a partition with the param's first gradient
since the last step() or zero_grad() and adds later ones. At the
accumulation boundary, the partitions of params without a gradient are
zeroed, as ZeRO-1/2 give them zero gradients, and with optimizer offload
the partitions not yet copied to the fp32 gradient are copied. This is
skipped when partition_grads is replaced (SuperOffload, ZenFlow's overlap
step) or recorded no write (DeepCompile writes the partitions itself).
Without optimizer offload, a gradient set with the safe_set APIs counts as
the param's gradient of the window, so it is kept.

Signed-off-by: Xinyu Lian <[email protected]>
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-02T04:19:28.780889Z e8bae05 PR opened
ℹ️ 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: e8bae05e96

ℹ️ 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/stage3.py Outdated
Comment on lines +1517 to +1518
if not written:
return

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 Distinguish DeepCompile from ranks with no local write

When an eager ZeRO-3 rank owns only padding for every parameter used in a window—for example rank 1 of a two-way group when the active branch uses only a one-element parameter—partition_grads records nothing even though that rank owns real shards of other, skipped parameters. Treating an empty written set as proof of DeepCompile returns here, so those skipped shards retain their previous gradient and are stepped again while the peer's shards are zeroed; use an explicit DeepCompile signal rather than the local write count.

Useful? React with 👍 / 👎.

Comment on lines +1511 to +1512
if getattr(self.partition_grads, "__func__", None) is not DeepSpeedZeroOptimizer_Stage3.partition_grads:
return

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 Apply the cleanup to alternate stage-3 partitioners

When SuperOffload is enabled, or ZenFlow's overlap step replaces partition_grads, this new identity guard returns at every boundary. Both replacement implementations still keep the same persistent partition buffer and use micro_step_id == 0 to decide copy versus add (deepspeed/runtime/superoffload/superoffload_stage3.py:136-161 and deepspeed/runtime/zenflow/engine_stage3.py:457-511), so a skipped expert or branch still reuses its old gradient in these supported ZeRO-3 modes; add equivalent write tracking and missing-partition finalization to those paths instead of bypassing them.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Comment thread deepspeed/runtime/zero/stage3.py Outdated
Comment on lines +1556 to +1557
if self.offload_optimizer:
return

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 Preserve safe-set gradients with unmanaged optimizer offload

With managed_gradient_accumulation=false plus CPU or NVMe optimizer offload, a caller can set the gradient of a branch-skipped parameter after the final backward, as documented for safe_set_full_grad and safe_set_local_grad in docs/code-docs/source/zero3.rst:413-434. This return leaves that parameter absent from both tracking sets; Engine.step() then finalizes active offloaded gradients and _fill_missing_grad_partitions() zeroes the skipped partition and copies it over the fp32 value the caller just set, whereas the previous finalize path left that manual gradient intact. Record or synchronize the offloaded safe-set value so finalization does not erase it.

Useful? React with 👍 / 👎.

Copilot AI 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.

🟡 Changes recommended

Critical gradient-finalization defects can overwrite explicit setter writes, preserve stale or erase valid gradients, and exhaust accelerator memory with NVMe optimizer offload.

3 open issues
What changed in this PR

This PR updates ZeRO-3 gradient handling to prevent unused parameters from retaining stale gradients and to preserve contributions across accumulation windows and reentrant checkpoints.

Changes:

  • Tracks partition writes so each parameter’s first gradient overwrites prior contents and later gradients accumulate.
  • Clears missing gradients at accumulation boundaries and forwards pending partitions to offloaded optimizers.
  • Adds regression tests for unused parameters, offload, overflow recovery, gradient setters, checkpointing, and DeepCompile.
File Description
tests/​unit/​v1/​zero/​test_zero3_unused_param_grads.py Adds distributed regression coverage for gradient accumulation and related execution paths.
deepspeed/​runtime/​zero/​stage3.py Tracks gradient writes, fills missing partitions, and coordinates offload and setter handling.

Review effort: Balanced

Comment thread deepspeed/runtime/zero/stage3.py Outdated
Comment on lines +1515 to +1518
# No write recorded: the gradients did not come through partition_grads (DeepCompile writes the partitions
# itself), so the partitions are left as they are.
if not written:
return
Comment thread deepspeed/runtime/zero/stage3.py Outdated
Comment on lines +1542 to +1546
if not get_accelerator().on_accelerator(grad_buffer):
grad_buffer = grad_buffer.to(get_accelerator().current_device_name(), non_blocking=True)
self._offload_grad_partition_at_boundary(param, grad_buffer, offload_fp32_gradients,
offload_fp32_offsets)
self._swap_out_offload_fp32_gradients(offload_fp32_gradients, offload_fp32_offsets)
Comment thread deepspeed/runtime/zero/stage3.py Outdated
Comment on lines +1556 to +1557
if self.offload_optimizer:
return
Review fixes for the previous commit:

- The fill took a rank that wrote no gradient partition in the window
  for DeepCompile and skipped it. A rank whose used params are all
  padding there wrote none and kept the old gradients of its skipped
  params, and a safe_set call under DeepCompile counted as a write, so
  the fill zeroed the compiled gradients. The fill now checks for the
  IPG buckets, through which partition_grads gets the gradients and
  which DeepCompile clears.
- With optimizer offload, the fill (params without a gradient) and the
  unmanaged finalize (all params) copied the window's partitions over a
  gradient set with the safe_set APIs after the param's last gradient.
  They now leave it, as without offload, and the setters record its
  norm for clipping, as safe_set_local_grad already did.
- With NVMe offload, the fill kept the fp32 device copies of all the
  partitions it passed on until it swapped them out at the end. It now
  swaps them out for every reduce_bucket_size param elements, as
  partition_grads does per gradient bucket; the unmanaged finalize
  shares this code.

With the fill no longer skipped when no partition was written, a step()
right after zero_grad() applies zero gradients, not the ones from before
zero_grad(). test_zero_grad[True] of TestZero3ParamPartitioningBase
asserted a nonzero gradient norm there; it now asserts zero.

Signed-off-by: Xinyu Lian <[email protected]>

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

Read at 7848a58b. The DS Adam ops don't build on my machine, so I swapped the new test file's optimizer for torch_adam: True with zero_force_ds_cpu_optimizer: false, and ran it on CPU (gloo): 17 passed (NVMe and the rest skipped) on this branch, and the same 17 fail on master with value mismatches, e.g. step 2: max diff 5.4e-3, and grad norms of 9.32 vs 9.77 in test_set_full_grad_norm. So the stale-gradient cases reproduce on master and are fixed here.

@pengdurice pengdurice mentioned this pull request Nov 7, 2026
@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 10, 2026
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 13, 2026
# ZeRO-3 CPU offload: apply the clip factor and write the bf16 copy
inside the CPU Adam pass

**Builds on:** deepspeedai#8840 (merged).
**Part of:** deepspeedai#8672 (Q4 2026 roadmap), "Enable training of large scale
models".

## Summary

With the optimizer offloaded to the CPU, ZeRO-3's step on master makes
three passes over every CPU sub-group:

1. multiply every fp32 gradient by the clip and loss-scale factor in
place (`grad.mul_`), even when the factor is 1;
2. run `DeepSpeedCPUAdam` (reads gradients, parameters and both moments;
writes parameters and both moments);
3. copy the fp32 master to the device and cast it there to bf16 (deepspeedai#8840):
twice the bytes of the bf16 result over
PCIe, into an fp32 device temporary the size of the sub-group (3.73 GiB
at the default `sub_group_size` of 1e9).

This PR folds 1 and 3 into 2. The CPU Adam kernel multiplies each
gradient by the factor as it loads it. With
`pin_memory` on and a bf16 device partition, it also writes the bf16
copy of each updated piece into one of two pinned
buffers, and the buffer is copied to the device while the next piece is
updated. Parameters after training, and
gradients read after `step()`, are bitwise equal to master.

## The change

| File | Lines | What |
|---|---|---|
| `csrc/includes/cpu_adam.h` | +74 -1 | `_grad_scale`, `_params_copy`,
`set_grad_scale`, `set_params_copy`, `params_copy_for`: the step
multiplies each loaded gradient by the factor and, when a copy buffer is
set, stores the updated parameter in bf16 there |
| `csrc/includes/sve.h` | +4 -1 | the SVE path takes the factor |
| `csrc/adam/cpu_adam_impl.cpp` | +131 | `ds_adam_step_scaled`,
`ds_adam_step_scaled_copy`, `ds_adam_copy_supported`,
`ds_adam_grad_scale_supported`, `ds_adam_block_numel` |
| `csrc/adam/cpu_adam.cpp` | +17 | bindings `adam_update_scaled`,
`adam_update_scaled_copy`, `adam_copy_supported`,
`adam_grad_scale_supported`, `adam_block_numel` |
| `deepspeed/ops/adam/cpu_adam.py` | +62 -4 | `step(closure=None,
grad_scale=1.0, bf16_copy=None)`: `bf16_copy=(piece_numel, before_piece,
after_piece)` updates each parameter piece by piece; `before_piece`
returns the bf16 buffer for the piece and `after_piece` starts its copy.
The piece size is rounded down to a multiple of the kernel's widest
vector block (128 floats with AVX512), so every element takes the vector
path. `copy_supported()`, `grad_scale_supported()` |
| `deepspeed/runtime/zero/stage3.py` | +143 -10 |
`_grad_scale_for_cpu_adam` passes the factor to CPU Adam instead of
`mul_` for CPU sub-groups; `_cpu_adam_step_and_copy_back` runs the
pieces into two pinned bf16 buffers of 2^26 elements, waits for the
previous copy out of a buffer before refilling it, and waits for the
last piece before returning (the next forward's all-gathers do not wait
for this stream); `_apply_deferred_grad_scale` (below) |
| `tests/unit/ops/adam/test_cpu_adam.py` | +106 | kernel tests below |
| `tests/unit/v1/zero/test_zero.py` | +218 | ZeRO-3 tests below;
`TestZero3OffloadPinnedCopyBack` turns off the fused copy-back |

**Gradients that are not overwritten.** On master the offloaded fp32
gradient buffer is not cleared between steps.
A parameter that gets no gradient in a window (a skipped branch, an
expert with no tokens) keeps its older gradient,
the step reads it again, and the in-place `mul_` multiplies it by every
step's factor. Because the fused step does not
write the scaled gradient back, each fused sub-group records its factor.
At the start of the next `step()` (before the
overflow check), the slices that the new window did not overwrite are
multiplied by it, which is the multiply master
did. Every function that reads or sets offloaded fp32 gradients
(`safe_get_full_grad`, `safe_get_local_grad`, the set
functions, `get_fp32_grad_partitions`,
`update_fp32_grad_for_param_vectorized`) applies a recorded factor
first. When
every parameter gets a gradient, this multiplies nothing.

**Where the fused path runs.** The clip factor is fused for CPU
sub-groups with float32 gradients and master weights,
with DeepSpeed's bf16 or fp16 (including the dynamic loss scale) and
`pin_memory` on or off. It is not used with a
torch GradScaler, ZenFlow, NVMe offload or Muon, or on the RVV build
(its kernel has no factor;
`grad_scale_supported()` is false). The bf16 copy also needs
`pin_memory` on, a bf16 device partition and a CPU Adam
build with a bf16 store (AVX512, NEON and the scalar loop; AVX2, SVE and
RVV keep the copy of deepspeedai#8840). SuperOffload
overrides `step()` and is not affected. No configuration key changes.

## Measured

Qwen2.5-32B, real weights, PG-19 rows of 8,192 tokens, 1 node x 8 H200,
ZeRO-3, all of the optimizer offloaded to the
CPU (`pin_memory` on), fp32 Adam states, bf16, activation checkpointing,
12 OpenMP threads per rank. Master and this PR
alternate in one job on the same node; each run is 2 warm-up and 6
measured steps, and the time is the mean of the 6.

| Run | Master | This PR | Change |
|---|---|---|---|
| 1 | 9.445 s per step | 9.077 s | −3.9% |
| 2 | 9.544 s | 9.213 s | −3.5% |
| 3, with `wall_clock_breakdown` | 9.910 s | 9.532 s | −3.8% |

- Losses: equal at step 1 (0.022649) in all six runs. From step 2 they
differ in the 4th to 6th digit, by as much as
the two master runs differ from each other (step 8: master 1.746211,
1.746275, 1.746414; this PR 1.746454,
  1.746391, 1.746197).
- `optimizer_step` timer (rank 0, run 3, mean of the measured steps):
4414 ms on master, 4281 ms with this PR. It varies
between steps from 4125 to 4686 ms on master and from 3737 to 4719 ms
with this PR.
- Peak device memory during a step: 34,658,109,952 bytes in all six
runs. In this configuration the fp32 device
  temporary of master's copy-back does not set the peak.
- Pinned host memory: the two bf16 buffers add 256 MiB per rank,
allocated at the first fused copy-back.

Earlier measurement, on the first version of this PR stacked on the
first version of deepspeedai#8840 (master 5f266e2, before
deepspeedai#8840 dropped its staging buffers): GLM-5.2, real weights, 65,536-token
rows, 1 node x 8 H200, first 8 layers, 20% of
the optimizer on the GPU: 15.95 s per step before, 14.61-14.67 s with
both halves fused; 8 nodes x 8 H200, all 78
layers: 147.16 s before, 143.61 s after.

## Tests

| Test | Checks |
|---|---|
| `test_cpu_adam_grad_scale_matches_scaling_in_place` |
`step(grad_scale=f)` gives bitwise the parameters and moments of
`grad.mul_(f)` then `step()` |
| `test_cpu_adam_bf16_copy_matches_step` | `step(bf16_copy=...)` with
pieces of 1,000 elements (not a multiple of the vector block) and
524,289-element tensors gives bitwise the result of one `step()`, and
the bf16 copies equal `param.to(torch.bfloat16)` |
| `test_cpu_adam_bf16_copy_runs_step_hooks` | `step(bf16_copy=...)` runs
the optimizer's step pre- and post-hooks, and a torch `StepLR` built on
it gives no "`lr_scheduler.step()` before `optimizer.step()`" warning |
| `TestZero3CpuAdamGradScale` (2 ranks; clip 1e-3 and 1e6; ratio 1.0 and
0.5; `pin_memory` on and off) | ZeRO-3 with CPU offload: parameters
after 3 steps, and gradients read with `safe_get_full_grad` after them,
bitwise equal to the in-place path; the fused path ran; factor below 1
when clipping, 1 otherwise |
| `TestZero3CpuAdamCopyBack` (2 ranks; ratio 1.0 and 0.5; skipped on the
CPU accelerator) | pieces of 1,000 elements reuse both buffers many
times per step; parameters bitwise equal to the separate passes; the
fused copy-back ran |
| `TestZero3CpuAdamUnusedLayer` (2 ranks; `pin_memory` on and off) | a
layer used only in step 0: every sub-group takes the fused path, and
parameters and gradients after 3 steps are bitwise equal to the in-place
path |
| `TestZero3CpuAdamFp16Overflow` (2 ranks) | fp16 with a dynamic loss
scale and an inf loss in step 0: the step is skipped and the loss scale
lowered on both paths, and the parameters after the later fused steps
are bitwise equal |

`TestZero3CpuAdamUnusedLayer` fails if the recorded factor is dropped
without the multiply: the unused layer's
parameters then differ by up to 9.766e-04, and the gradients read after
the last step by up to 5.429e-01 (2 H200;
4.961e-01 on the CPU accelerator with 2 ranks); the other layers'
parameters stay bitwise equal.

`TestZero3OffloadPinnedCopyBack` (from deepspeedai#8840) counts the calls of
deepspeedai#8840's copy. It now turns off the fused copy-back,
because on AVX512 every bf16 CPU sub-group would take it; the fused
copy-back is tested by `TestZero3CpuAdamCopyBack`.

Hardware: 1 node of 8 NVIDIA H200 (driver 580.126.09), Intel Xeon
Platinum 8488C (AVX512), torch 2.8.0+cu126,
pytest 9.1.1:

```
pytest unit/ops/adam/test_cpu_adam.py                                   # 138 passed, 5 skipped
pytest unit/v1/zero/test_zero.py                                        # 120 passed, 1 skipped, 3 failed (*)
pytest unit/v1/zero/test_zero.py::TestZero3OffloadPinnedCopyBack \
       unit/v1/zero/test_zero.py::TestZero3CpuAdam*  (4 classes)        # 15 passed, after the fix (*)
pytest unit/v1/zero/test_invalid_grad_norm.py                           # 18 passed
pytest unit/runtime/zero/test_zero_offloadpp.py unit/v1/pin_memory/     # 53 passed, 1 skipped
pytest unit/runtime/zenflow/test_zf.py                                  # 95 passed
```

(*) The 3 failures were in the tests: `TestZero3OffloadPinnedCopyBack`
[1.0] and [0.5] (above), and
`TestZero3CpuAdamFp16Overflow`, which expected the first overflow to
lower the loss scale although the default
`hysteresis` is 2; it now sets `hysteresis: 1`. Only test files changed
after that run.

After merging master `af5198984` into the branch (it brings deepspeedai#8974, which
changes `cpu_adam.py`), on the same hardware:
`test_cpu_adam.py`, `test_invalid_grad_norm.py` and the five ZeRO-3
classes above: 177 passed, 5 skipped.

The 5 skips in `test_cpu_adam.py` are the file's own fp16 cases. CPU
accelerator (`DS_ACCELERATOR=cpu`, 2 ranks,
gloo): `test_cpu_adam.py`, `test_invalid_grad_norm.py` and the five
ZeRO-3 classes: 160 passed, 16 skipped (fp16 and
copies to a device). `pre-commit run --files` passes on every changed
file.

## Compatibility

| Cell | Validated |
|---|---|
| ZeRO-3, CPU optimizer offload, bf16, `pin_memory` on and off, all of
the optimizer on the CPU (ratio 1.0) and half (0.5) | yes (tests;
Qwen2.5-32B on 1 node) |
| fp16 with a dynamic loss scale, including an overflow step | yes
(test) |
| Parameters without a gradient in a step | yes (test) |
| AVX512 build (Intel Xeon Platinum 8488C, the H200 nodes) | yes |
| NEON / SVE builds, AVX2-only CPUs | no (AVX2 and SVE have no bf16
store in this kernel, so `copy_supported()` is false and the copy keeps
the path of deepspeedai#8840; the clip factor is fused on every build except RVV) |
| RVV | no; `grad_scale_supported()` is false there, so both halves keep
the master path |
| GradScaler, NVMe offload, ZenFlow, Muon, SuperOffload | path unchanged
by design |
| ZeRO-1 / ZeRO-2 | not touched |

## Related pull requests

- deepspeedai#8719 (ReFlow) also fuses the gradient scaling into its CPU kernels
and writes bf16 parameters without a separate
pass, in separate kernels with asynchronous scheduling. This PR puts the
two synchronous parts into the default
`DeepSpeedCPUAdam` path and does not schedule anything asynchronously,
so it does not depend on deepspeedai#8719 or replace it.
- deepspeedai#8981 zeroes the gradients of parameters that got none in a window.
All of its writes to the offloaded fp32 gradients
go through `_offload_grad_partition_at_boundary`, which records them
here, so with both PRs every slice is overwritten
in each window and the deferred multiply does no work. The two PRs edit
neighbouring lines in `stage3.py`.
- deepspeedai#8970 changes `unscale_and_clip_grads` for bf16/fp16 gradients only;
the fused path is fp32 only. Textual conflict of
two lines (this PR moves the factor computation into
`_combined_grad_scale`).

## AI assistance

This change, its tests and this description were prepared with AI
assistance (Claude).

---------

Signed-off-by: pengdurice <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 2026
@xylian86
xylian86 enabled auto-merge November 18, 2026 08:53
@xylian86
xylian86 added this pull request to the merge queue Nov 18, 2026
Merged via the queue into deepspeedai:master with commit daf175b Nov 18, 2026
19 checks passed
@xylian86
xylian86 deleted the xinyu/zero3-unused-param-grads branch November 18, 2026 09:38
PKUWZP added a commit that referenced this pull request Nov 18, 2026
ZeRO-3's gradient hook now skips a parameter the backward delivered no
gradient for, and the grouped-GEMM expert paths copy a weight that ZeRO-3
gathered to an address torch._grouped_mm does not accept. The deferred
expert function saves detached aliases of the weights, since ZeRO-3 swaps a
parameter's data after the forward.

Correct accumulation across windows additionally needs a parameter's first
gradient of a window to overwrite its ZeRO-3 gradient partition, which
#8981 provides.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
PKUWZP added a commit that referenced this pull request Nov 18, 2026
ZeRO-3's gradient hook now skips a parameter the backward delivered no
gradient for, and the grouped-GEMM expert paths copy a weight that ZeRO-3
gathered to an address torch._grouped_mm does not accept. The deferred
expert function saves detached aliases of the weights, since ZeRO-3 swaps a
parameter's data after the forward.

Correct accumulation across windows additionally needs a parameter's first
gradient of a window to overwrite its ZeRO-3 gradient partition, which
#8981 provides.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Zhipeng Wang <[email protected]>
LiRunGuo added a commit to LiRunGuo/DeepSpeed that referenced this pull request Nov 19, 2026
… partitions again

Upstream deepspeedai#8981 zeroes, at each accumulation boundary, the gradient
partitions that the window did not write. It finds them from a list of
the parameters with data in this rank's partition
(_params_with_grad_partition), which ZeRO-3 makes once. The list depends
on the layout, and a re-partition kept it: a parameter that had only
padding on a rank before and has data there after was left out, and when
it got no gradient in a window, the rank applied its last gradient again.
With gradient clipping (on by default), that gradient also enters the
global norm, so every parameter's update changes. The install now resets
the list (when the optimizer has one), and ZeRO-3 makes it again at the
next boundary.

test_unused_parameter_after_a_change: a two-element parameter, with data
on ranks 0 and 1 of four, moves to ranks [2, 3] (data on both), which
train a step that uses it and one that does not; the engine must match
one that stays on four ranks. On this branch merged with master the test
fails without the reset and passes with it; on the branch's own base,
before deepspeedai#8981, it passes either way.

Signed-off-by: RunguoLi <[email protected]>
github-merge-queue Bot pushed a commit that referenced this pull request Nov 22, 2026
Follow-up to #9114 (stacked on its branch; proposal in #9113): lets
`deferred_dw_flush_period` run with ZeRO stage 3.

This PR was written with AI assistance (Claude Code). I have reviewed
the code line by line, wrote part of it and signed off the commit. It
depends on #8981, which is now merged; the branch is rebased onto it and
the results below were measured on the`c76a7ea55`, which has the same
tree as the then signed-off head `b708bbfc8`. The branch has since been
rebased onto #9114's review fixes and a review fix added (head
`e27a91cc9`); the results on that head are listed first below.

## How we support ZeRO-3, and what each part does: 

1. **Gradient hook with no gradient** (this PR, `zero/stage3.py`, core,
4 lines). On a backward that stages, the expert weights are in the graph
but get no gradient, and the per-parameter hook still fires.
`reduce_independent_p_g_buckets_and_remove_grads` now returns early for
a `None` gradient, as #9114 does for ZeRO-2.
2. **Stale accumulation buffer** (not in this PR; fixed by #8981,
merged). `partition_grads` overwrote a parameter's gradient partition
only in micro step 0 and added afterwards. A staged expert weight gets
its first gradient of a window in a later micro step, so it was added
onto the previous window's gradient. #8981 makes a parameter's first
gradient after `step()` overwrite its partition, which is what staging
needs. I did not duplicate that fix here.
3. **Unaligned weights** (this PR, `moe/ep_experts.py`). ZeRO-3 hands a
module its weights as slices of a gathered buffer that need not start on
the 16-byte boundary the CUDA `torch._grouped_mm` requires
(`RuntimeError: expected data_ptr to be aligned to 16 bytes`). On this
machine that failed for `use_grouped_mm=true` with ZeRO-3 with or
without staging. `_grouped_mm_weight` clones a weight only when it is
unaligned; the plain, fused gate+up and deferred paths use it. The
deferred function saves the parameters and derives the aligned weights
again in the backward, for which ZeRO-3 gathers them, so the gathered
weights are not kept allocated between a layer's forward and its
backward (e27a91c; with `gate_up_impl="fused"` the packed gate+up copy
is still kept, see Review fixes).

The ZeRO-stage rejection in `auto_ep_config.py` is removed and the docs
updated.

## Open design question

#8277 solved the same alignment failure for ZeRO-1/2 by padding the flat
buffer (`zero_optimization.parameter_alignment`), explicitly without
copying misaligned parameters. Item 3 here takes the other route for
ZeRO-3: a weight-sized copy per forward, only when a gathered weight is
unaligned. Extending the padding to ZeRO-3's gathered buffers would
avoid the copy but is a larger change to `partition_parameters.py`.
Maintainers should choose; item 3 can be dropped from this PR if padding
is preferred.

## Duplicate-work check

Searched open and closed issues/PRs for "deferred dw", "tgmm", "expected
data_ptr to be aligned", "grouped_mm data_ptr aligned 16 bytes",
"partition_grads micro_step_id stale gradient". Found #8981 (covers item
2; not duplicated, since merged) and #8276/#8277 (alignment for ZeRO-1/2
only; see above). Sibling paths: the ZeRO-2 hook guard is in #9114;
ZeRO-1/2 passed the same two-window parity test without further changes.

## Tests run

Hardware: 3x NVIDIA H200 (143 GiB), driver 595.112.07, PyTorch
2.8.0+cu129, Python 3.12, `DS_SKIP_CUDA_CHECK=1` (system CUDA toolkit
13.2).

On `e27a91cc9` (rebased onto #9114 at `6ee0cbb9a`, which returns staged
gradients in the same backward on every rank, plus the weight-retention
fix):

```
pytest unit/v1/moe/test_autoep_grad_parity.py -k TestAutoEPDeferredDwParity
    -> 8 passed (2 GPUs, comm backend, accumulation 4, flush period 3, two optimizer steps)
       expert parallel 2, ZeRO 0/1/2/3: staged vs. unstaged parity
       expert parallel 1 (both ranks replicate every expert, different data), ZeRO 1/2/3, 12 rows per expert:
       ranks flush early in different backwards and still reduce together
       plus the step() guard
pytest unit/v1/moe/test_autoep_expert_activation.py -k "TestDeferredDwStaging or slot or overlap"
    -> 48 passed (1 GPU, bf16)
pytest unit/v1/zero/test_zero3_unused_param_grads.py
    -> 21 passed, 7 skipped (2 GPUs)
pytest unit/v1/moe/test_autoep_expert_activation.py unit/module_inject/test_auto_ep_comm.py unit/v1/moe/test_autoep_unit.py
    -> 387 passed, 50 skipped (CPU, PyTorch 2.10.0+cpu)
pre-commit run --files <changed files>
    -> passed
```

The rebase conflicted in `docs/_pages/config-json.md` and
`test_autoep_grad_parity.py`; beyond resolving them, this PR now runs
#9114's replicated-expert test under ZeRO-3 as well, since ZeRO-3 also
reduces a gradient in the backward that returns it. The results below
were not repeated on this head.

Rerun on `c76a7ea55` (rebased onto master with #8981):

```
pytest unit/v1/moe/test_autoep_grad_parity.py -k DeferredDw
    -> 5 passed: staged vs unstaged gradients for ZeRO 0/1/2/3, plus the step() guard
       (2 GPUs, expert parallel 2, accumulation 4, flush period 3, two optimizer steps)
pytest unit/v1/moe/test_autoep_expert_activation.py -k DeferredDwStaging
    -> 39 passed (1 GPU; includes the new unaligned-weights test)
pytest unit/v1/zero/test_zero3_unused_param_grads.py
    -> 21 passed, 7 skipped (the tests added by #8981)
pytest unit/module_inject/test_auto_ep_comm.py
    -> 65 passed, 3 skipped, 6 failed; the same 6 fail on unmodified master here
       (this torch build has no CPU `torch._grouped_mm`)
```

A single-GPU ZeRO-3 script over optimizer steps with flush periods 2/3/4
gave staged gradients within 0.8% of the largest unstaged gradient
element (bf16 rounding). Before #8981 the same script gave 198%, and the
ZeRO-3 case of the parity test failed at the second window.

Run before the rebase and not repeated on this head:
`unit/v1/moe/test_autoep_integration.py` (7 passed, 3 skipped), a
`unit/v1/zero/test_zero.py` ZeRO-3 subset (40 passed, 1 skipped), and
`pre-commit run --files <changed files>` (passed; the rebase did not
change this PR's diff).

Known gaps: the same pre-existing hang as in #9114 (zero-row groups in
`torch._grouped_mm` on this machine) keeps the rest of
`test_autoep_expert_activation.py` from running here; the full unit
suite was not run.


Commit ids: the branch was rebased onto #9114 at `6ee0cbb9a` (itself
rebased onto master `b9896d054`, a README-only change) after these runs.
The results labelled e27a91c were measured on the patch-identical
commit c381ff0, whose tree differs only in that README line, and were
not repeated.

## Review fixes

- Codex P1
([thread](#9115 (comment))):
staged gradients returned on only some ranks of a ZeRO-3 partition
group. Fixed in #9114 (`6ee0cbb9a`); reproduced here as a ZeRO-3 hang
with that change reverted, and covered by the replicated-expert test for
ZeRO 3.
- Codex P2 (e27a91c): the detached weight aliases kept gathered expert
weights allocated until the backward. In a probe emulating ZeRO-3's
release (8 experts, 96 MiB of bf16 weights, one H200), the staged path
kept 98 MiB after the release before the fix and 2 MiB after it with
separate gate/up. With `gate_up_impl="fused"` it keeps 66 MiB, because
the packed gate+up copy is still saved: packing it again in the backward
made the fused staged forward+backward 30% slower at 8 rows per expert
(2.16 -> 2.82 ms per microbatch; 128 experts, hidden 2048, intermediate
768). With the copy kept, timings were unchanged for both variants. The
plain `torch._grouped_mm` path keeps its weights through the views
autograd saves and is not changed.

## Compatibility matrix

| Cell | Status |
| --- | --- |
| ZeRO 3, bf16, expert parallel 1 and 2, `comm` backend | validated
(parity test above; expert parallel 1 by the 2-rank replicated-expert
test and the single-GPU script) |
| ZeRO 0 / 1 / 2 | re-validated by the same parity test |
| ZeRO-3 optimizer / parameter offload, NVMe, hpZeRO, quantized
gradients with staging | not validated |
| DeepEP backend, sequence parallel, multi-node | not validated |

No end-to-end throughput, peak-memory or convergence measurements were
made for this PR; the module-level numbers under Review fixes are the
only ones. Item 3 adds a `data_ptr()` check per weight per forward on
the grouped-GEMM paths and, under ZeRO-3 with an unaligned gathered
weight, a weight-sized copy per forward; its cost was not measured.

---------

Signed-off-by: Zhipeng Wang <[email protected]>
Co-authored-by: Claude Fable 5.2 <[email protected]>
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