Repository navigation
[AutoEP] Run staged expert weight gradients with ZeRO-3 - #9115
Merged
Merged
Conversation
PKUWZP
force-pushed
the
autoep-deferred-dw-zero3
branch
from
November 18, 2026 15:35
f51ffa9 to
c76a7ea
Compare
PKUWZP
force-pushed
the
autoep-deferred-dw-zero3
branch
from
November 18, 2026 18:41
c76a7ea to
b708bbf
Compare
PKUWZP
marked this pull request as ready for review
November 18, 2026 18:51
PKUWZP
requested review from
hwchen2017,
loadams,
tjruwase and
tohtana
as code owners
November 18, 2026 18:51
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b708bbfc89
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
PKUWZP
force-pushed
the
autoep-deferred-dw-zero3
branch
2 times, most recently
from
November 18, 2026 22:40
c381ff0 to
e27a91c
Compare
PKUWZP
force-pushed
the
autoep-deferred-dw-zero3
branch
from
November 20, 2026 18:38
e27a91c to
8afaa16
Compare
banxingmjj
pushed a commit
to openanolis/DeepSpeed
that referenced
this pull request
Nov 20, 2026
…ai#9114) Implements the proposal in deepspeedai#9113: an opt-in AutoEP mode that stages the rows of the experts' weight-gradient GEMMs across microbatches and runs those GEMMs once per several backward passes. This PR was written with AI assistance (Claude Code). I have reviewed all of the code line by line and signed off each commit. ## What changes - `deepspeed/moe/ep_experts.py`: new `MoeDeferredDwStaging` (per-expert staging buffers and cursors; gradients are returned by one backward in every period and by the backward that closes an accumulation window; a full buffer runs the GEMMs early and holds the result until then). `_DeferredWeightGradExperts` and `GroupedExperts.forward` take an optional staging object. The dW products are factored into `_grouped_mlp_weight_grads`, shared by the immediate, slot and staged paths. - `deepspeed/module_inject/auto_ep_layer.py`, `auto_ep_config.py`, `auto_ep_presets/base.py`: `deferred_dw_flush_period` and `deferred_dw_rows_per_expert`, validation, and passing the staging object (and unpadded per-expert counts) at the three `self.experts(...)` call sites. - `deepspeed/runtime/engine.py` (core, wiring only): mark the backward that closes an accumulation window so it flushes; refuse an optimizer step with rows still staged; reject unmanaged accumulation, ZenFlow and DeepCompile. - `deepspeed/runtime/zero/stage_1_and_2.py` (core, 4 lines): the gradient hook fires even when the backward delivered no gradient for a parameter in the graph; `reduce_independent_p_g_buckets_and_remove_grads` now returns early in that case instead of dereferencing `None`. - Docs: `docs/_pages/config-json.md`, `docs/code-docs/source/autoep.rst`. ## Duplicate-work check Searched issues and PRs (open and closed) for "tgmm", "deferred dw", "MoeDeferredDwStaging", "weight gradient staging microbatch". The only related work is merged deepspeedai#8739 (`overlap_weight_grad`), which defers dW within a single backward to overlap it with the DeepEP combine; it does not accumulate rows across backward passes. This PR reuses its autograd function rather than adding a second one. Sibling paths checked: the same hook pattern exists in `zero/stage3.py`; it is not changed because this PR does not support ZeRO-3 (the stacked PR deepspeedai#9115 does it). The Triton grouped-GEMM path and the sequential expert loop are rejected by validation. ## 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` was set because the system CUDA toolkit (13.2) differs from PyTorch's. ``` cd tests pytest unit/v1/moe/test_autoep_expert_activation.py -k "TestDeferredDwStaging or TestPresetAndConfig or validated or rejected or rejects or test_slot or needs_the_grouped or create_graph or config_reaches" -> 49 passed, 2 skipped (1 GPU; run before the review fixes below) pytest unit/v1/moe/test_autoep_expert_activation.py -k TestDeferredDwStaging -> 36 passed (1 GPU, bf16; at 6ee0cbb) pytest unit/v1/moe/test_autoep_grad_parity.py -k TestAutoEPDeferredDwParity -> 6 passed (2 GPUs, comm backend, accumulation 4, flush period 3, two optimizer steps; at 6ee0cbb) expert parallel 2, ZeRO 0/1/2: staged vs. unstaged parity expert parallel 1 (both ranks replicate every expert, different data), ZeRO 1/2, 12 rows per expert: ranks flush early in different backwards and still reduce together pytest unit/v1/moe/test_autoep_expert_activation.py unit/module_inject/test_auto_ep_comm.py unit/v1/moe/test_autoep_unit.py -> 382 passed, 50 skipped (CPU, PyTorch 2.10.0+cpu, the version cpu-torch-latest installs; at 6ee0cbb) pytest unit/v1/moe/test_autoep_integration.py -> 7 passed, 3 skipped pytest unit/v1/zero/test_zero.py -k "TestZeroUnbalancedGradients or TestZeroFrozenWeights or TestZero3RepeatForwardLoop" -> 7 passed pytest unit/runtime/test_engine_attribute_delegation.py unit/compile/test_zero3_grad_dtype.py -> 22 passed pre-commit run --files <changed files> -> passed ``` The rows before `pre-commit` other than the first were run before the review fixes and not repeated; those fixes touch only `ep_experts.py`, docs and tests. Not validated: world size 4 with expert parallel 2 (the test machine has 3 GPUs; the 2-rank, expert-parallel-1 test has the same replicated-expert condition), DeepEP backend with staging, optimizer or parameter offload, AutoTP folding (rejected), ZeRO-3 (rejected here, deepspeedai#9115). A full GPU run of `test_autoep_expert_activation.py` hangs on this machine in `TestFusedGateUp::test_matches_separate_with_skewed_and_empty_experts`, which does not use staging, so only the selections above were run on GPU. Commit ids: the branch was rebased onto master `b9896d054` (a README-only change) after these runs. The results labelled 799bd49 / 6ee0cbb were measured on the patch-identical commits 4954ced / ea50751 before that rebase and were not repeated. ## Review fixes - 799bd49: `test_auto_ep_comm.py` builds the layer without `__init__` (Mock stubs and `__new__`), so 14 tests lacked the new `dw_staging` / `_run_experts` and failed on cpu-torch-latest. Test-only. - 6ee0cbb (Codex P1, [thread](deepspeedai#9114 (comment))): a full staging buffer made its rank return expert weight gradients early. Ranks holding replicas of the same experts fill their buffers in different backwards, and ZeRO-2 reduces in the backward that returns a gradient, so the replicas issued mismatched collectives. Reproduced as a hang with 2 ranks, expert parallel 1, ZeRO-2. An early flush now holds its result until the backward that closes the period or the window, so which backward returns gradients depends only on the count of backward passes. A period in which a rank's experts receive no rows now returns a zero gradient instead of none, for the same reason. ## Performance and memory Module-level only: grouped expert MLP forward+backward per microbatch on one H200, bf16, speedup vs. the same module without staging, flush period = accumulation window. | Shape (local experts, hidden, intermediate) | 8 rows/expert | 32 | 128 | 512 | | --- | --- | --- | --- | --- | | 128, 2048, 768, fused gate+up, window 8 | 1.69x | 1.62x | 1.34x | 0.90x | | 32, 7168, 2048, window 8 | 1.91x | 1.80x | 1.54x | 1.03x | | 512, 1024, 512, window 16 | 1.65x | 1.65x | 1.06x | 0.66x | Staging memory for the first shape at period 8: 0.20 / 0.78 / 3.13 / 12.5 GiB per layer per rank. It is a slowdown when experts receive many rows per backward. After a buffer overflows, the layer additionally holds one set of expert-weight-sized gradients until the next flush. These timings predate 6ee0cbb and were not repeated; without overflow the code path they measure is unchanged. Numerics: staged gradients match unstaged ones within bf16 GEMM rounding (max deviation below 1% of the largest gradient element in the engine runs). Against an fp64 reference the staged sum was closer (3.5e-3 vs 5.0e-3 to 6.1e-3 relative L2). ## Backward compatibility Off by default (`deferred_dw_flush_period: 1`). With it off, the only behavior change is the ZeRO-2 hook's early return for a `None` gradient, which previously raised `AttributeError`. --------- Signed-off-by: Zhipeng Wang <zhipeng.rainbowserie@gmail.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
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 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: Zhipeng Wang <zhipeng.rainbowserie@gmail.com>
…ward The deferred expert function saved detached aliases of its weights for the backward. ZeRO-3 releases a module's gathered weights when its forward returns, and the aliases kept every layer's expert weights allocated until that layer's backward ran. It now saves the parameters and reads them in the backward, for which ZeRO-3 gathers them again. The packed gate+up weight stays saved: it is the forward's own copy, and packing it again in the backward made the fused staged path 30% slower at 8 rows per expert. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: Zhipeng Wang <zhipeng.rainbowserie@gmail.com>
PKUWZP
force-pushed
the
autoep-deferred-dw-zero3
branch
from
November 22, 2026 02:51
8afaa16 to
55cf0c8
Compare
delock
approved these changes
Nov 22, 2026
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.
Follow-up to #9114 (stacked on its branch; proposal in #9113): lets
deferred_dw_flush_periodrun 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 headb708bbfc8. The branch has since been rebased onto #9114's review fixes and a review fix added (heade27a91cc9); the results on that head are listed first below.How we support ZeRO-3, and what each part does:
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_gradsnow returns early for aNonegradient, as [AutoEP] Stage expert weight gradients across microbatches #9114 does for ZeRO-2.partition_gradsoverwrote 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. ZeRO-3: fix stale and lost gradients of unused parameters #8981 makes a parameter's first gradient afterstep()overwrite its partition, which is what staging needs. I did not duplicate that fix here.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 CUDAtorch._grouped_mmrequires (RuntimeError: expected data_ptr to be aligned to 16 bytes). On this machine that failed foruse_grouped_mm=truewith ZeRO-3 with or without staging._grouped_mm_weightclones 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; withgate_up_impl="fused"the packed gate+up copy is still kept, see Review fixes).The ZeRO-stage rejection in
auto_ep_config.pyis 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 topartition_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 at6ee0cbb9a, which returns staged gradients in the same backward on every rank, plus the weight-retention fix):The rebase conflicted in
docs/_pages/config-json.mdandtest_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):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), aunit/v1/zero/test_zero.pyZeRO-3 subset (40 passed, 1 skipped), andpre-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_mmon this machine) keeps the rest oftest_autoep_expert_activation.pyfrom running here; the full unit suite was not run.Commit ids: the branch was rebased onto #9114 at
6ee0cbb9a(itself rebased onto masterb9896d054, 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
6ee0cbb9a); reproduced here as a ZeRO-3 hang with that change reverted, and covered by the replicated-expert test for ZeRO 3.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 plaintorch._grouped_mmpath keeps its weights through the views autograd saves and is not changed.Compatibility matrix
commbackendNo 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.