Skip to content

Overlap AutoEP's expert weight gradients with the DeepEP backward combine - #8739

Merged
tohtana merged 9 commits into
deepspeedai:masterfrom
yh0903:yh0903/autoep-overlap-weight-grad
Nov 15, 2026
Merged

tohtana merged 9 commits into
deepspeedai:masterfrom
yh0903:yh0903/autoep-overlap-weight-grad

Conversation

@yh0903

@yh0903 yh0903 commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

The fused gate+up prerequisite, #8733, has merged. This branch is synchronized with current master and retains only the backward-overlap feature delta; no force-rewrite of the earlier submitted commits is required.

In AutoEP's DeepEP backward, the experts compute their input gradient (dX) and their weight gradients (dW). DeepEP's combine then sends dX back to the token ranks. dW and the combine are independent, yet they run serially: a grouped GEMM's backward computes dX and dW together, and only then does the dispatch backward start the combine. In a kernel profile of Qwen3-30B-A3B on 8 H100s, DeepEP ran concurrently with no compute kernel at all.

This adds an opt-in expert_parallel.overlap_weight_grad, which runs the combine and the dW GEMMs side by side.

Change

  • GroupedExperts.forward takes an optional ExpertWeightGradSlot.
    • With a slot, _DeferredWeightGradExperts runs the same forward as the torch._grouped_mm path, for separate or fused gate+up and every registered activation.
    • Its backward returns dX at once and leaves the dW GEMMs in the slot.
    • The GEMMs are the products autograd forms for torch._grouped_mm (_grouped_mm_mat1_backward, _grouped_mm_mat2_backward).
  • The DeepEP dispatch takes the expert weights as extra inputs. Its backward:
    1. launches the dX combine with async_with_compute_stream=True;
    2. runs the slot's dW GEMMs on the compute stream;
    3. waits on the combine's event;
    4. returns dW through autograd, so ZeRO's gradient handling is unchanged.
  • SM carveout:
    • torch._grouped_mm launches persistent kernels sized to every SM, which leaves the combine nowhere to run.
    • The dW GEMMs are therefore launched with comm_num_sm SMs withheld through torch._C._set_sm_carveout_experimental.
    • The previous carveout is restored even if the GEMMs raise.
    • The pending combine's event is waited on in a finally block as well, so a dW error does not leave the queued communication unaccounted for.
  • Activation backward:
    • The activation registry gains optional standalone backward functions for the fused kernels. swiglu provides them, via new swiglu_backward and swiglu_packed_backward, which the existing autograd functions now also call.
    • Forms without them are recomputed and differentiated, so the deferred path always matches the forward that ran.
  • The default, off, keeps the existing path.
  • Master's per-layer checkpoint-dispatch replay and exact-size buffer-slice optimization are retained. Overlap slots are separate per invocation and do not replace replay handles.
  • The deferred custom backward is first-order only: create_graph=True raises rather than returning an incomplete derivative.
  • overlap_weight_grad is rejected, rather than ignored, unless all of these hold:
    • comm_backend="deepep" with autoep_size > 1;
    • use_grouped_mm=true, and the experts do not select the Triton grouped GEMM;
    • ZeRO stage 1 or 2, explicitly rejecting both stage 0 and stage 3;
    • PyTorch provides both the SM carveout getter and setter APIs.
  • Docs: autoep.rst and the config reference.

Tests

  • CPU, TestDeferredExpertWeightGrad:
    • Output, input gradient and w1/w2/w3 gradients match the plain path's values exactly in the tested CPU cases, for every activation, separate and fused gate+up, FP32 and BF16, with weight gradients immediate or deferred, including an empty expert. This does not assert universal bit-pattern equivalence.
    • Also: slot lifecycle errors, the torch._grouped_mm requirement, and config validation for every rejected setting.
  • CPU, TestWeightGradOverlap, the route against a DeepEP contract buffer:
    • Exact numerical agreement with the serial backward in the tested CPU cases, separate and fused gate+up, with no checkpointing, reentrant and non-reentrant checkpointing, now composed with upstream's replay coordinator.
    • The order is async combine, then dW with comm_num_sm withheld, then wait.
    • The carveout is restored, including on error.
    • A dW exception still waits for the async combine before propagating; it does not widen optimizer/backend support.
  • GPU, H100, 402 passed:
    • test_overlapped_weight_gradients_match_the_serial_backward, on 4 GPUs with DeepEP, uniform and skewed routing, separate and fused gate+up: input and every parameter gradient within 1e-2 relative L2, the shared parity checks, and no leaked carveout.
    • The CUDA bitwise check with the Triton kernels.
    • swiglu_backward and swiglu_packed_backward bitwise against autograd.
    • The rest of the DeepEP parity, AutoEP unit and activation suites.
    • Not part of this change: the 2 failures are TestMiniMaxM3Block::test_replaced_block_matches_hf_block. That preset needs Transformers >= 5.15.0, and the image has 5.12.0.
  • End to end, Qwen3-30B-A3B on 8 H100s:
    • Setup: expert parallel size 8, micro-batch 4, 16 accumulation steps, sequence length 4096, DeepEP, reentrant checkpointing, fused gate+up, 30 steps with 10 warmup.

    • Measured with an equivalent benchmark patch on our benchmark base: the same deferral, async combine and carveout.

    • Two pairs in one job:

      Arm Mean step
      Serial backward 21,569.5 ms
      Overlap without the carveout 21,418.5 ms (-0.70%)
      Overlap with the carveout 21,097.3 ms (-2.19%)
    • A kernel profile showed DeepEP running alongside grouped GEMMs for 1,325 ms of the step, against none before.

    • Step-1 loss identical. Later losses agree within same-arm repeat noise.

    • Peak allocated memory unchanged; reserved memory about 0.7 GB higher.

    • A follow-up sweep in one job: withholding more SMs than DeepEP uses (24 with comm_num_sm=12) was 0.9% slower. That supports tying the carveout to comm_num_sm.

    • The overlap's gain depends on how much backward communication is left to hide. A second job separated the SM budget from the overlap:

      Arm Mean step
      Serial backward, comm_num_sm=12 21,569.9 ms
      Serial backward, comm_num_sm=20 20,942.6 ms
      Overlap, comm_num_sm=20 20,696.9 ms (-1.17% vs serial at 20)
      Overlap, comm_num_sm=28 20,638.8 ms

      On this single node, more DeepEP SMs speed up every DeepEP call regardless of this option. The overlap saves 472 ms at 12 SMs and 246 ms at 20.

Review follow-up

  • The ZeRO-0 feedback is addressed by failing closed: zero_stage not in (1, 2) is rejected while the disabled default still permits the ordinary stage-0 path.
  • The engine now passes its actual ZeRO stage into that validator. Previously it omitted the keyword, so tightening the validator alone would incorrectly treat every optimizer as stage 0; both direct-config and engine-wiring cases cover stages 0/1/2/3.
  • Master synchronization preserves the already merged numerical-reference policy, packed-kernel input-device/stream guard and higher-order rejection. Extracted standalone backward helpers use the input device rather than whichever CUDA device happens to be current.
  • The real-DeepEP comparison now reads trainable accumulated gradients through safe_get_full_grad before engine.step(), including stage-2 cases where param.grad is released. It does not accept an empty expert-gradient dictionary as proof of parity.
  • Prior targeted H100 acceptance: 40 passed, 0 skipped, on an 8x NVIDIA H100 80GB HBM3 host (distributed cases use four ranks), driver 580.159.04, torch 2.10.0.2/CUDA 13.0, Triton 3.6.0 and transformers 5.12.0. It covers both supported ZeRO stages, uniform/skewed routing, separate/fused gate+up, replay composition, standalone helper device selection and every trainable gradient before clipping. The 1e-2 relative-L2 criterion is unchanged.
  • On Apple M4 Pro CPU with torch 2.14.1, the comm suite passes 66/66 in forked mode; targeted config/folding/activation checks pass. Removing only the three guards reproduces all four expected failures (ZeRO 0 accepted, missing event wait, and separate/fused incomplete higher-order derivatives). CPU mocks are not presented as physical DeepEP validation.
  • Existing 402-passing-case H100 and E2E results above are reused, not described as fresh broad-hardware or full-training validation. The new follow-up retains the old numerical thresholds and performs no throughput sweep.
  • The activation-weighting child, AutoEP: opt-in routing weights inside the expert activation #8748, is reviewed after this parent and remains a separate opt-in feature; its shifted-rounding semantics are not part of this PR.

AI assistance was used for review and test preparation. The human author reviewed the exact task-specific diff before signoff/publication. This updates an existing PR rather than opening a duplicate feature implementation.

DCO, test collection and changed-files pre-commit passed on the published head. Full GPU CI and infrastructure smoke jobs were skipped; they are not described as a full GPU CI run. On-device evidence for this review follow-up is the targeted H100 execution above.

Latest review follow-up

Applied the requested minimal test-double repair: record_validate accepts and records zero_stage, and the existing sequence-parallel engine test asserts the actual stage is 0. It no longer rejects the engine's keyword argument, and it would still catch missing stage forwarding instead of silently ignoring it. The original test reproduced TypeError: ... unexpected keyword argument 'zero_stage' before the repair.

Synchronized with master to resolve the test-fixture import conflict. The worker-only fixture retains both this PR's standalone SwiGLU backward helpers and master's merged clamped activation helpers and tests. The only manual edits in this follow-up are in those two test files; no manual kernel, autograd, scheduling, numerical-threshold or default changes were made. The activation-weighting child remains separate.

Validation on 1x Apple M4 Pro CPU, macOS 26.7, Python 3.11.15, Torch 2.14.1, pytest 9.1.1; CUDA and accelerator driver are not applicable:

  • Configuration, deferred expert gradients, ZeRO stage 0/1/2/3 engine wiring, and complete comm/replay coverage: 159 passed, 8 CUDA-only skipped, 49 subtests passed. The repaired sequence-parallel test passes.
  • The repaired test also passes under --forked. Three selected SwiGLU cases reach the merged worker fixture and skip explicitly because CUDA/Triton is unavailable; this is import/worker coverage, not kernel execution.
  • All 155 SwiGLU cases collect, including both standalone backward and clamped forms. Changed-files pre-commit passes for all 14 files in the final PR delta.

CPU reproduction command, from the repository root:

DS_ACCELERATOR=cpu PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONDONTWRITEBYTECODE=1 \
  python -m pytest -q -p no:cacheprovider \
  tests/unit/v1/moe/test_autoep_unit.py::TestAutoEPConfig \
  tests/unit/v1/moe/test_autoep_expert_activation.py::TestDeferredExpertWeightGrad \
  tests/unit/v1/moe/test_autoep_expert_activation.py::TestFusedGateUp::test_overlap_weight_grad_settings_are_validated \
  tests/unit/v1/moe/test_autoep_expert_activation.py::TestFusedGateUp::test_overlap_weight_grad_rejects_the_triton_grouped_gemm \
  tests/unit/v1/moe/test_autoep_expert_activation.py::TestFusedGateUp::test_engine_passes_the_actual_zero_stage_to_overlap_validation \
  tests/unit/module_inject/test_auto_ep_comm.py

The prior H100 and E2E results above are reused evidence for the overlap implementation, not a new device run of this merged tree. GPU integration, throughput, memory and convergence experiments were not repeated for this test-only review repair and import-conflict resolution. No additional ZeRO/offload/TP/PP or hardware combinations are claimed.

yh0903 and others added 3 commits October 3, 2026 01:11
AutoEP's grouped experts run the gate and up projections of the same input
as two grouped GEMMs, and in the backward pass add the two input-gradient
GEMM results. expert_parallel.gate_up_impl="fused" concatenates w1 and w3
on each call and runs one torch._grouped_mm with twice the output columns.
A single input-gradient GEMM then accumulates both projections in FP32.

The activation reads the two halves of the packed output in place: swiglu
through a new Triton kernel, swiglu_packed, with the same FP32 math as the
existing swiglu kernel; the other registered forms through their eager
expression on views. Parameters keep the separate w1/w3 layout, so
checkpoints, expert tensor parallelism and optimizer state are unchanged.

The default, "separate", keeps the existing path. "fused" is rejected when
the experts would not run torch._grouped_mm.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: yh0903 <helloyu0903@gmail.com>
…bine

In the DeepEP backward, the experts' input gradient is combined back to the
token ranks while their weight gradients are independent of it, yet a
grouped GEMM's backward computes both before the combine starts.

With expert_parallel.overlap_weight_grad, the experts' backward returns
the input gradient first and leaves its weight-gradient GEMMs in an
ExpertWeightGradSlot. The DeepEP dispatch, which takes the expert weights
as extra inputs, launches its backward combine asynchronously, runs those
GEMMs on the compute stream with comm_num_sm SMs withheld through
PyTorch's SM carveout so the combine has room to run, waits on the combine
and returns the weight gradients through autograd. The GEMMs are the
products autograd forms for torch._grouped_mm, so gradients are those of
the serial backward.

The activation registry gains optional standalone backward functions for
the fused kernels, provided for swiglu; forms without one are recomputed
and differentiated. The option is rejected unless comm_backend is deepep
with autoep_size > 1, the experts run torch._grouped_mm, ZeRO stage is 1
or 2, and the SM carveout API exists.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: yh0903 <helloyu0903@gmail.com>
…e grouped GEMM in the DeepEP case

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: yh0903 <helloyu0903@gmail.com>

@0z5a 0z5a 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.

The documented contract here says overlap_weight_grad is supported with ZeRO stage 1 or 2, but the validation only rejects stage 3, so ZeRO-0 currently passes through.

Could we either explicitly reject zero_stage not in (1, 2), or add ZeRO-0 correctness coverage and document it as supported? Since this path reroutes expert dW through the dispatch autograd node, I'd prefer failing closed for an unvalidated optimizer path.

banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Oct 12, 2026
…dai#8733)

AutoEP's grouped experts run the gate (`w1`) and up (`w3`) projections
of the same routed rows as two grouped GEMMs. In the backward pass, they
compute two input-gradient GEMMs and add the two BF16 results. This adds
an opt-in `expert_parallel.gate_up_impl="fused"`, which runs both
projections as one `torch._grouped_mm` over the two weights,
concatenated on each call.

### Change

- `GroupedExperts(gate_up_impl="fused")` concatenates `w1` and `w3` per
call and runs one grouped GEMM with `2 * hidden_dim` output columns.
- The backward pass therefore has one input-gradient GEMM, which
accumulates both projections in FP32, and no separate addition.
- The activation reads the two halves of the packed output in place:
- `swiglu` uses a new Triton kernel, `swiglu_packed`, with the same FP32
math as the existing `swiglu` kernel.
- The other registered forms (`geglu_tanh`, `swiglu_clamped`,
`swiglu_oai`) run their eager expression on views of the halves.
  - New forms can register a `packed_fused_fn`.
- The parameters keep their separate `w1`/`w3` layout. Checkpoints,
universal checkpoints, expert tensor parallelism and optimizer state,
including Muon's per-expert treatment, are unchanged.
- The default, `"separate"`, keeps the existing path.
- `"fused"` is rejected rather than ignored when the experts would not
run `torch._grouped_mm`:
- `use_grouped_mm=false`, at config validation and in `GroupedExperts`;
- devices that select the Triton grouped GEMM, unless
`disable_triton_grouped_mm=true`.
- Docs: `autoep.rst` and the config reference.

### Numerical and autograd contract

The forward expression and parameter-gradient semantics are unchanged.
Exact output/weight-gradient equality is an observation in the tested
H100 cases, not a guarantee across GEMM shapes, implementations or
hardware. The input gradient can differ because it is accumulated in one
FP32 GEMM rather than as two rounded BF16 results added. The FP64
regression now uses the same represented BF16 weights as the tested
paths, rather than the original pre-quantization FP32 weights; its
existing relative-L2 bound (fused error <= 1.05 * separate error) is
unchanged. This is not a universal accuracy-improvement or
bitwise-equivalence claim.

Cross-GEMM output and parameter-gradient assertions now use the existing
grouped-GEMM BF16 policy (`rtol=0.02`, `atol=0.02 *
max(abs(reference))`) rather than zero tolerance. The
skewed/empty-expert forward and smooth-form parameter gradients use the
independent FP64 reference. Clamped-form parameter gradients use an
independent dense BF16 reference, because rounding a projection across a
clamp boundary changes its derivative discontinuously; the bound is not
enlarged to absorb those discontinuities. The input-gradient relative-L2
comparison is unchanged. The multi-step test uses the same policy for
comparisons across algorithms, while saved/reloaded parameters,
optimizer momentum tensors and parameter-group configuration must still
match exactly. Exact parity checks between the two implementations of
the same elementwise SwiGLU kernel remain unchanged.

The packed SwiGLU Triton path has first-order gradients only:
`create_graph=True` raises rather than silently dropping its second
derivative. Forward and backward select the input's CUDA device and its
current stream, restoring the caller's current device. The eager
expressions for the other activation forms and the default separate path
are unchanged.

### Tests

- CPU, `TestFusedGateUp` in
`tests/unit/v1/moe/test_autoep_expert_activation.py`:
- packed versus separate halves for every registered form, forward and
backward;
  - only `swiglu` has a packed kernel;
  - the default is unchanged;
- unsupported settings are rejected (bad value, `use_grouped_mm=false`,
Triton grouped GEMM path), at config validation and in `GroupedExperts`;
- the config reaches the replaced experts, whose parameters remain `w1`,
`w2`, `w3`.
- Earlier GPU evidence, on one H100 (305 passed):
`test_swiglu_triton.py`, `test_autoep_expert_activation.py` and
`test_autoep_unit.py`.
- `swiglu_packed` matches the existing `swiglu` kernel's values exactly,
forward and backward (`rtol=0`, `atol=0`, not a signed-zero bit-pattern
assertion). Covered: FP32/FP16/BF16, odd widths, 3-D inputs, empty
inputs, non-contiguous input, and an odd last dimension (rejected).
- The fused path joins `test_grouped_gemm_paths_match_the_for_loop` for
every form.
- New `test_matches_separate_with_skewed_and_empty_experts`, for every
form, with an empty expert and unaligned rows:
- output and `w1`/`w2`/`w3` gradients match exactly in the tested
shapes;
- the original relative-L2 FP64 error comparison is retained with the
corrected represented-weight reference described above.
- Not part of this change: the 2 failures are
`TestMiniMaxM3Block::test_replaced_block_matches_hf_block`. That preset
requires Transformers >= 5.15.0, and the image has 5.12.0.
- The shipped `GroupedExperts`, one H100, Qwen3-30B-A3B per-rank expert
shape (131,072 routed rows, hidden 2048, expert hidden 768, 16 local
experts, BF16):

  | Per call (ms) | Forward, no grad | Forward | Backward | Total |
  |---|---:|---:|---:|---:|
  | `"separate"` | 2.149 | 2.292 | 4.857 | 9.298 |
  | `"fused"` | 2.224 | 2.236 | 4.321 | 8.781 |

Output and all weight gradients matched exactly; the input gradient
differed by 2.9e-3 relative.
- End to end, Qwen3-30B-A3B on 8 H100s:
- Setup: expert parallel size 8, micro-batch 4, 16 accumulation steps,
sequence length 4096, DeepEP, reentrant activation checkpointing, BF16
parameters and Adam state, 30 steps with 10 warmup.
- Measured with an equivalent benchmark patch on our benchmark base: the
same concatenation and the same packed SwiGLU kernel.
- Separate 22,018.8 / 22,018.5 ms against fused 21,601.2 / 21,608.4 ms,
in two pairs in the same job: **-414 ms (-1.9%)**.
- Step-1 loss identical. Later losses agree within same-arm repeat
noise.
- Peak allocated memory unchanged; reserved memory about 0.4 GB higher.

### Review follow-up validation

- Current-master targeted validation on NVIDIA H100 80GB HBM3, torch
2.10/CUDA 13.0, Triton 3.6.0 and transformers 5.12.0: **83 passed, 0
skipped** (the full 63-case SwiGLU file plus 20 `TestFusedGateUp`
cases). The SwiGLU file also passed **63/63 with no skips under `pytest
--forked`**. Cross-device cases used two GPUs; the lifecycle cases use
the actual native grouped GEMM.
- With only the same new tests applied to the prior runtime, all four
focused guards fail as intended: both FP16/BF16 cross-device cases
reproduce Triton's inaccessible-pointer error, and both FP32/BF16
higher-order cases fail because `create_graph=True` was not rejected.
This verifies the actual root causes, not an unrelated collection or
test-API failure.
- Regressions cover strided packed inputs and upstream gradients,
two-device/current-stream selection and caller restoration, explicit
higher-order rejection, the corrected FP64 reference, and two SGD
updates with two accumulation micro-batches per step. All four
activations run with and without reentrant recomputation; a
model/optimizer state-dict round trip between updates keeps the separate
`w1`/`w2`/`w3` names and shapes and checks the next update against the
independent separate path.
- The SwiGLU test file imports its runtime in the worker, not during
collection, so its Triton driver probe is deferred until after `pytest
--forked` starts the worker.
- The follow-up changes launch-device selection and unsupported-autograd
handling, not the GEMM implementation, kernel arithmetic, launch
configuration, default or parameter layout. The earlier local and E2E
performance evidence is reused without retiming; the historical
percentages are not new measurements of these guards.

### AI review follow-up

- Changed tests and documentation only; the runtime is byte-identical to
the previous validated head.
- The numerical-contract comment is addressed by the reference/tolerance
policy above, plus a regression that accepts a single BF16
representable-step change but rejects a clearly incorrect value. On
NVIDIA H100 80GB HBM3, torch 2.10/CUDA 13.0, Triton 3.6.0 and
transformers 5.12.0, the focused fused-gate-up/grouped-GEMM suite passed
**33/33 with no skips**.
- A synthetic one-ULP perturbation of the fused down-GEMM output passed
all **12/12** reference/lifecycle cases with the contract-level checks;
the old exact checks failed all **12/12** under the same perturbation.
An independently injected 25% output/gradient error was rejected by all
**four** reference cases. These are small test controls, not new
GEMM-backend or performance measurements; they demonstrate that
legitimate rounding is allowed without accepting an incorrect
computation.
- The DCO comment was checked against the actual GitHub PR commit list
and local ancestry: every PR commit has the configured author's
`Signed-off-by` trailer, and DCO passes. The SHA cited in that comment
is not in the PR and is not found by GitHub's commit API, so no commit
amendment or history rewrite is needed.

### CI and scope

DCO, test collection and changed-files pre-commit passed on the
published follow-up. Full GPU CI and infrastructure-smoke jobs were
skipped on the PR event; they are not reported as full GPU CI
acceptance. The targeted H100 runs above provide the device evidence for
this follow-up.

This branch inherits recent upstream `master`. The backward-overlap
child (deepspeedai#8739) remains a separate stacked PR and is
not included here; no recompute-skip, buffer-slice,
row-weighting-activation or communication optimization is added by this
PR.

The new optimizer round trip is a focused SGD test, not an independent
qualification of every optimizer, expert-TP/universal-checkpoint
combination, ZeRO stage or accelerator. The E2E evidence covers one
model/configuration on H100, not long-run convergence or a universal
speedup.

---------

Signed-off-by: yh0903 <helloyu0903@gmail.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Preserve merged gate-up, checkpoint replay and exact-size buffer behavior. Enforce ZeRO stages 1/2 and forward the actual engine stage into validation; keep the disabled default unchanged. Restore SM carveout and wait for the async combine even if dW fails, reject incomplete higher-order derivatives, and retain input-device standalone backward launches.

Read accumulated parameter gradients before clipping in the real stage-1/2 regression rather than accepting released param.grad as missing coverage. The human author reviewed this exact staged tree before signoff; targeted H100 acceptance and CPU controls passed without a new performance sweep.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: yh0903 <helloyu0903@gmail.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 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-10-13T03:19:57.663917Z b016772 Draft marked ready
ℹ️ About Codex in GitHub

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

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

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

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.

🔵 Needs a closer look

The distributed asynchronous autograd scheduling and private PyTorch SM-carveout integration warrant final human review despite extensive targeted testing.

0 open findings

What changed in this PR

Adds opt-in overlap of AutoEP expert weight-gradient GEMMs with DeepEP’s backward combine, building on the merged fused gate/up work while keeping activation weighting separate.

Changes:

  • Adds deferred expert weight-gradient computation with async DeepEP combine and SM carveout.
  • Validates supported DeepEP, grouped-GEMM, ZeRO, and PyTorch configurations.
  • Adds activation backward helpers, documentation, and CPU/H100 coverage.
File Description
deepspeed/​moe/​ep_experts.py Implements deferred expert weight gradients.
deepspeed/​module_inject/​auto_ep_comm.py Overlaps combine with gradient GEMMs.
deepspeed/​module_inject/​auto_ep_config.py Validates overlap requirements.
deepspeed/​module_inject/​auto_ep_layer.py Connects overlap to AutoEP routing.
deepspeed/​module_inject/​auto_ep_presets/​base.py Adds the configuration option.
deepspeed/​ops/​triton_ops/​swiglu_triton.py Exposes standalone SwiGLU backward helpers.
deepspeed/​runtime/​engine.py Passes the actual ZeRO stage.
docs/​code-docs/​source/​autoep.rst Documents behavior and performance.
docs/​_pages/​config-json.md Documents the configuration field.
tests/​unit/​module_inject/​test_auto_ep_comm.py Tests scheduling, recovery, and checkpointing.
tests/​unit/​v1/​moe/​test_autoep_deepep_parity.py Tests real DeepEP gradient parity.
tests/​unit/​v1/​moe/​test_autoep_expert_activation.py Tests deferral and validation.
tests/​unit/​v1/​ops/​triton_ops/​test_swiglu_triton.py Tests backward helper parity and device selection.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@yh0903

yh0903 commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

The documented contract here says overlap_weight_grad is supported with ZeRO stage 1 or 2, but the validation only rejects stage 3, so ZeRO-0 currently passes through.

Could we either explicitly reject zero_stage not in (1, 2), or add ZeRO-0 correctness coverage and document it as supported? Since this path reroutes expert dW through the dispatch autograd node, I'd prefer failing closed for an unvalidated optimizer path.

Thanks @0z5a. Overlap now explicitly rejects ZeRO 0/3 and accepts only stages 1/2, with the engine forwarding its actual stage to validation. Error paths restore the carveout and wait for the pending async combine!

@tohtana tohtana left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Hi @yh0903,
Thank you for submitting this PR!

I wasn't able to run this with real DeepEP setting, but the code change overall looks good.
One small change I want to request: the engine now passes zero_stage to the AutoEP config validator, but an existing validator test func rejects that keyword. A minimal signed test-only repair would be like commit e452d350.

Retain the merged clamped activation kernels and tests while resolving the worker-fixture imports as a union with the standalone backward helpers. Keep both sets of imports inside the worker, preserving fork-safe collection.

Accept and record zero_stage in the existing sequence-parallel validator test double and assert the actual stage is forwarded. This fixes the reproduced unexpected-keyword failure without changing the product runtime or weakening existing assertions.

The human author reviewed the exact staged tree before signoff. Targeted CPU configuration, deferred-gradient, engine and comm/replay checks and changed-files pre-commit passed. Reuse earlier device evidence without claiming a fresh GPU or end-to-end run.

Signed-off-by: yh0903 <helloyu0903@gmail.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@yh0903

yh0903 commented Oct 27, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, Masahiro! Applied the minimal test-double repair you suggested in 894a116. record_validate now accepts and records zero_stage, and the existing sequence-parallel test explicitly asserts that the engine forwards stage 0. Existing sequence-parallel assertions and ZeRO stage 0/1/2/3 coverage are preserved.

Also synchronized with master, resolving the SwiGLU fixture conflict by retaining both the standalone backward and clamped activation helpers inside the worker-only fixture. This follow-up introduces no manual product-runtime changes.

@0z5a 0z5a 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.

Re-checked at 894a1162, following up on my comment at 56dac2a0.

My point is addressed. overlap_weight_grad now rejects every ZeRO stage other than 1 and 2. The engine forwards its real stage, and a caller that passes no stage gets 0, so it fails closed. The parametrized engine test pins this.

On CPU (gloo), the AutoEP expert, comm and unit tests and the SwiGLU Triton tests pass at this head: 327 passed, and the rest skip because they need CUDA or Triton. That run includes TestWeightGradOverlap, which shows serial and overlapped backward bitwise equal with reentrant and non-reentrant checkpointing, and the plain-vs-deferred expert comparison. I also merged this branch with #8829, which touches the same AutoEP config and engine setup; there are no conflicts, and the combined tests pass.

One non-blocking point, inline below. With frozen expert weights, the overlapped backward still computes every expert weight gradient, and autograd then drops them.

grad_gate, grad_up = _expert_activation_backward(grad_h, gate, up, *ctx.activation)
grad_x = torch._grouped_mm(grad_gate, w1c, offs=offsets) + torch._grouped_mm(grad_up, w3c, offs=offsets)

def weight_grads():

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.

weight_grads() always forms all three dW GEMMs, and auto_ep_layer.py:913 always passes w1, w2 and w3 to the dispatch. When some expert weights don't require grad, which AutoEP supports since repacking keeps the source's requires_grad, the overlap path computes their gradients and the dispatch backward returns them to inputs that don't need them, so autograd drops them. The serial path skips them. On CPU, counting aten::_grouped_mm over a step with all experts frozen: 9 vs 6 for separate gate/up, 6 vs 4 for fused. The gradients are bitwise equal, so it's only wasted work. Checking ctx.needs_input_grad[2:5] in weight_grads() (returning None for the frozen ones), or passing only the trainable weights at the call site, would skip them. With gate_up_impl="fused", grad_w1 and grad_w3 come from one grad_w13 GEMM, so that one can be skipped only when both are frozen.

banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 7, 2026
…speedai#8823)

AutoEP + AutoTP folding gives TP peers different routed experts.
ZeRO-1/2 currently filters non-TP expert parameters to TP rank zero when
computing the clipping norm, then applies the ordinary expert-norm
averaging path. This can omit expert owners and produce an incorrect
clipping coefficient even when reconstructed logical gradients are
correct.

Compute folded expert norms over the actual expert-DP partition group
and EP owner group, without another TP sum or expert-norm average. Only
groups tagged with the AutoEP expert placement family use this path.
Dense groups and native MoE groups retain their existing reductions and
native expert-norm averaging, including when native ETP and AutoEP
groups coexist. ZeRO-3 is unchanged and is checked as a sibling
reference. The existing folding contract rejects optimizer/parameter
offload.

Refs deepspeedai#8672 and deepspeedai#8670. The live duplicate check found no open PR fixing
this ZeRO-1/2 folding path. deepspeedai#8476, deepspeedai#8478 and deepspeedai#8691 address FP32/ZeRO-0
clipping in `runtime/utils.py`; they do not change the partitioned
optimizer reductions fixed here. deepspeedai#8739 implements DeepEP weight-gradient
overlap and does not change these norm reductions.

### Final change

This PR contains three files:

- `deepspeed/runtime/zero/stage_1_and_2.py`: correct the folded expert
clipping reductions.
- `tests/unit/v1/moe/test_autoep_autotp_sharded_attention.py`:
reconstruct full logical gradients and FP32 master parameters, then
compare an actual SGD update against an unsharded ZeRO-0 reference
across all 45 parameter families. Thresholds of 0.5 and 2.0 times the
reference norm cover active clipping and an inactive control. Snapshots
are cloned before in-place updates; distributed diagnostics finish
before assertions.
- `docs/code-docs/source/autoep.rst`: document expert ownership and the
reduction contract.

The sharded-attention regression supports 4- and 8-rank TP2/EP4
configurations, ZeRO-1/2/3 and ZeRO-3 `zero.Init`. An additional
two-rank analytic SGD regression covers native ETP alone and mixed
native ETP/folded AutoEP groups at ZeRO-1/2.

### Incremental review

[Incremental review report and
validation](deepspeedai#8823 (comment))
· [diff from the reviewed
head](deepspeedai/DeepSpeed@352ee55...fb5d0e5).

The correction preserves native ETP reductions alongside folded AutoEP.
**On the correction commit, 8 positive cases passed on 2 H100 GPUs, and
2 published-head negative controls failed as expected.** ZeRO-1/2
optimizer cases validate native norm 5, mixed norm 13 and the actual
clipped-SGD updates; TP2/EP2 tiny GLM4-MoE active/inactive clipping
cases validate all 45 parameter families against an unsharded reference.
The old mixed cases produce partial norms 12.369317 / 12.649111 instead
of 13. These runs used FP32, TF32 disabled, Torch 2.12.1+cu130 / CUDA
13.0, Transformers 5.15.1 and driver 595.91.07. Changed-file pre-commit
checks and independent archive/report readback passed; owned workers and
locks closed. The report records the exact execution method and CPU
diagnostic separately. The 8/16-GPU results below belong to the original
submitted head.

### Original submitted-head validation

The original submitted three-file diff at
`352ee55cd14f77f30e5170939c7e60c4d4bd7754` was tested on source based on
`1c862f7df93f0345b977c67f5408d967b94bf4ae`. The extended finite workload
used **16 NVIDIA H100 GPUs across four nodes**, random tiny GLM4-MoE,
FP32 with TF32 disabled, Torch 2.12.1+cu130, CUDA 13.0 and Transformers
5.15.1. The original receipt did not capture the NVML driver package
version.

| Coverage | Final result |
|---|---|
| Clipping and initialization | TP2/EP4 and TP2/EP8, ZeRO-1/2/3,
active/inactive clipping and ZeRO-3 `zero.Init` passed. An unfixed
ZeRO-2 control failed the norm/update oracle. |
| Routing and topology | Rotating hotspots, idle expert owners, GAS4,
and TP4/EP16 with 16 experts and ZeRO-3 `zero.Init` passed. |
| Communication | Overlap off/on and small-bucket configurations with
actual repeated/oversize flushes passed. |
| Save and resume | Continuous four-update training matched save after
two updates, process exit and new-process resume through four updates,
including parameters, momentum 0.9, losses and WarmupLR state. |
| Sustained training | 200 actual updates across four 50-update routing
stages passed the reference loss, gradient and update checks. Late live
allocated-memory spread stayed below 64 MiB for this tiny model. |
| Independent readback | All 28 cases, 448 rank packets and 247,635 raw
arrays from the 16-GPU workloads passed separate NumPy arithmetic and
complete archive checksum verification. |
| Source checks | All applicable changed-files pre-commit hooks passed,
including yapf, flake8, codespell, license and accelerator/distributed
import checks. `git diff --check` and a clean three-way merge check
against current upstream master passed. |

The extended distributed drivers used the same contributed reference
helpers. An additional 8-H100 clipping matrix passed 16 cases and 28,800
raw arrays. All owned GPU workers and contexts closed, the original GPU
locks were released, and complete outputs were archived.

Idle-owner checks exclude alignment padding using the frozen permutation
formula `ceil((n_tokens + E_local*8)/8)*8`; equality to `E_local*8`
proves zero actual received rows. The original finalizer's incorrect
padding assertion and failed scheduler status are preserved in the
private evidence. The separate corrected reader passed against the same
completed workload and unchanged numerical tolerances.

These results establish tiny-model correctness, optimizer-state
continuity and bounded-run stability. They do not establish
pretrained-model convergence, a speedup, BF16/FP16 or Muon behavior,
offload, PP/SP, DeepEP overlap, or completion of every Q4 roadmap item.

Reproduce the contributed regression and source checks:

```sh
pytest --forked -q tests/unit/v1/moe/test_autoep_autotp_sharded_attention.py \
  -k TestShardedAttentionClippedUpdate
pre-commit run --files deepspeed/runtime/zero/stage_1_and_2.py \
  tests/unit/v1/moe/test_autoep_autotp_sharded_attention.py \
  docs/code-docs/source/autoep.rst
```

AI assistance was used for implementation, test preparation and
incremental review. The human submitter reviewed the original
submission, confirmed its test results, and authorized this follow-up
correction and DCO sign-off.

---------

Signed-off-by: 0z5a <dezhen.lu@student.uni-tuebingen.de>
Co-authored-by: pengdurice <pengduhit@gmail.com>
@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 10, 2026
yh0903 and others added 2 commits November 10, 2026 16:45
Use autograd input-gradient requirements to omit dW work for frozen expert weights and return None, while retaining dX and active parameter gradients. Keep the fused gate/up dW GEMM whenever either projection is trainable.

Compare frozen-weight GEMM counts with the serial path and explicitly verify native DeepEP ElasticBuffer in model parity. Existing optimizer support, numerical bounds, scheduling and defaults are unchanged.

The human author reviewed the exact four-file diff before signoff. Focused H100 validation passed 40 cases on the public parent and 16 on this repair source tree, with source seals and JUnit counts verified. CPU regressions and changed-files pre-commit passed; no new throughput or convergence sweep was run.

Signed-off-by: yh0903 <helloyu0903@gmail.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@pengdurice

Copy link
Copy Markdown
Contributor

@yh0903 lgtm for now conditional on addressed the pending reviews from other folks.

@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 2026

@tohtana tohtana left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Sorry for the delay! This looks good now.

Signed-off-by: Masahiro Tanaka <tanaka.masahiro@gmail.com>
@tohtana
tohtana enabled auto-merge November 14, 2026 21:47
@tohtana
tohtana added this pull request to the merge queue Nov 14, 2026
@tohtana
tohtana removed this pull request from the merge queue due to a manual request Nov 14, 2026
Preserve both expert weight-gradient overlap and recompute-combine skipping. Retain multi-step parity coverage and full-gradient collection for ZeRO stage 2, and avoid shadowing the checkpoint import in the overlap test.

Signed-off-by: Masahiro Tanaka <tanaka.masahiro@gmail.com>
tohtana pushed a commit to yh0903/DeepSpeed that referenced this pull request Nov 14, 2026
## Summary

Add opt-in `expert_parallel.skip_recompute_combine` for AutoEP's DeepEP
route. In supported Hugging Face per-decoder-layer **reentrant**
checkpointing, the recomputed MoE output is used only by the residual
add and is discarded by the checkpoint. The route records post-expert
row weighting and combine backward without executing those forward
operations; dispatch, expert compute and all required backward transfers
still run. Default behavior is unchanged.

This is the existing skip-combine PR, not a duplicate implementation. It
remains distinct from the non-reentrant layout replay merged in
deepspeedai#8731. The branch preserves that replay, the fused
gate+up defaults from deepspeedai#8733, and the independent
exact-size buffer checks from deepspeedai#8747. AI assistance
was used for finalization, with author review before submission.

## Supported contract

- `comm_backend="deepep"`, `autoep_size > 1`, BF16 dispatch; eager and
fused row weighting, at their unchanged `score_apply` boundary.
- Supported decoder presets: `deepseek_v2`, `deepseek_v3`, `minimax_m3`,
`mixtral`, `qwen3_5_moe`, `qwen3_moe`, checked against Transformers
5.12.0 modeling code.
- The recompute guard checks the attached decoder layer's current state
and checkpoint configuration: `training=True`,
`gradient_checkpointing=True` and the standard Torch checkpoint partial
with `use_reentrant=True`. An eval-mode decoder does not run its own
Hugging Face checkpoint, so an outer reentrant recompute is rejected
rather than recording a NaN output. Ordinary eval forwards are
unchanged. Transformers 5 defaults to non-reentrant, so explicitly use
`gradient_checkpointing_kwargs={"use_reentrant": True}`.
- Any non-null `moe_layer_pattern` is rejected during configuration
validation when the skip is enabled, even with an explicit or
automatically selected supported preset, a pattern matching the preset,
or an empty string. Leave the pattern unset or disable the skip;
custom-pattern support is unchanged with the option off.
- Other checkpoint APIs, non-reentrant checkpointing with this flag and
unsupported presets are outside the supported contract. Without
recomputation, the ordinary path runs.
- The skip requires that the MoE output has no value-dependent consumer
in the recompute. The combined sentinel is NaN; an invalid consumer can
produce non-finite values or gradients, but the sentinel is **not** a
general runtime proof that arbitrary wrappers, hooks or patched decoder
graphs are safe.

## Finalization

Resolved the upstream conflicts without dropping replay or buffer
behavior. Both normal and recorded combines now share their
backward-context setup, including transferring the pending dispatch
entry from the exchange to the consuming autograd node. Otherwise the
recorded path could retain a stale entry and attempt to replay the
previous step's routing in a later reentrant backward.

The CPU reproducer fails before the context fix with `activation
checkpointing recomputed a different routing`. The new regression
performs three successive steps with changing routes and compares
outputs, input/router/expert gradients and required transfers for both
pre/post score application.

The single CUDA weighting test now runs in a fresh `DistributedTest`
worker, retaining its actual fused/recorded-backward comparison rather
than allocating CUDA from an ordinary forked unittest. The existing
real-DeepEP skip parity cases run two steps per model. The one-step test
helper's defaults and original tolerances remain unchanged.

### Review follow-up

Following the review, reject pattern overrides before model conversion.
Applying an override preserves the supported preset name but can select
a different decoder parent, so a preset-name whitelist cannot establish
the residual-only output-consumer contract. The fix is a four-line
configuration guard, not a decoder-graph validator or a runtime
fallback.

Six parametrized cases cover automatic and explicit preset selection, a
custom parent, the preset's own pattern and an empty pattern. Each also
checks that disabling the skip or leaving the pattern unset remains
accepted. Both configuration references document the restriction. The
kernels, recorded backward, supported execution paths and numerical
thresholds are unchanged.

### Training-state guard follow-up

The decoder must actually be checkpointing, not merely configured to
checkpoint. Hugging Face enables the per-layer checkpoint only when
`gradient_checkpointing` and `training` are both true. Without the
training-state check, an eval decoder under an outer reentrant
checkpoint can feed the recorded NaN into a value-dependent consumer
such as `y * y`. The original guard was reproduced on CPU with finite
forward output but non-finite input, router and expert gradients, for
both pre and post score application.

The guard now fails closed in that invalid recompute. A faithful decoder
harness uses actual Torch nested reentrant checkpoints: training-mode
output and every input/router/expert gradient match the unskipped CPU
reference, eval-mode outer recomputes raise, and ordinary train/eval
forwards retain the full route unchanged. The kernel, backward and
numerical thresholds are unchanged.

The latest master merge preserves the maintainers' existing merge
commits and resolves only the import conflict by retaining `math`,
`weakref` and `partial`. The lightweight `__new__` test layer explicitly
initializes the optional overlap flag to its disabled default for
eventual merge compatibility; the independent overlap feature from
deepspeedai#8739 is not imported into this PR.

## Testing

Latest training-state guard validation: **145 passed, 1 CUDA test
skipped, 58 subtests passed**, on **1x Apple M4 Pro CPU**, macOS 26.7,
Python 3.11.15, Torch **2.14.1**, pytest 9.1.1; CUDA and accelerator
driver are not applicable. This covers the complete comm/replay suite,
configuration tests and supported decoder attachment. The same selector
previously reported **139 passed, 1 skipped, 52 subtests passed** for
the earlier pattern-guard follow-up:

```bash
DS_ACCELERATOR=cpu PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONDONTWRITEBYTECODE=1 \
  python -m pytest -q -p no:cacheprovider \
  tests/unit/module_inject/test_auto_ep_comm.py \
  tests/unit/v1/moe/test_autoep_unit.py::TestAutoEPConfig \
  tests/unit/v1/moe/test_autoep_unit.py::TestModelDetectionAndReplacement::test_skip_recompute_combine_attaches_each_layer_to_its_decoder_layer
```

The skipped case requires CUDA and Triton for recorded fused weighting;
its existing device evidence is listed below. The newly affected
nested-checkpoint and ordinary-forward train/eval tests also pass under
isolated forked workers (**2 passed, 0 skipped**):

```bash
DS_ACCELERATOR=cpu PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONDONTWRITEBYTECODE=1 \
  python -m pytest -q -p no:cacheprovider -p pytest_forked --forked \
  tests/unit/module_inject/test_auto_ep_comm.py::TestSkipRecomputeCombine::test_outer_recompute_respects_the_decoder_training_state \
  tests/unit/module_inject/test_auto_ep_comm.py::TestSkipRecomputeCombine::test_nothing_is_skipped_without_a_recompute
```

The new regression produces exactly two missing-error failures with the
original guard (eval mode, pre/post), while its two training controls
pass. The earlier six pattern regressions passed under isolated forked
workers (**6 passed, 0 skipped**) on the same CPU setup:

```bash
DS_ACCELERATOR=cpu PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONDONTWRITEBYTECODE=1 \
  python -m pytest -q -p no:cacheprovider -p pytest_forked --forked \
  tests/unit/v1/moe/test_autoep_unit.py::TestAutoEPConfig::test_skip_recompute_combine_rejects_pattern_overrides_even_with_supported_presets
```

Existing product validation is bound to the original PR commit
`29303c378`: **275 passed, 1 skipped** on four H100s. All four
eager/fused and uniform/skewed skip-parity cases ran, as did the
recorded fused-weighting backward test. The skipped case is a MiniMax-M3
router-logit test requiring Transformers >=5.15.0; the validation
environment has 5.12.0. This is reused evidence for the original
implementation, not a claim that the entire suite was rerun after
rebase.

Pre-review focused CPU validation: **75 passed, 1 CUDA test skipped**,
under both ordinary pytest and `pytest --forked`, on macOS with Torch
2.10.0 and Transformers 5.12.0. This covers the comm/replay suite, three
skip config/conversion cases and the one-step helper defaults. Ordinary
pytest also reports **52 subtests passed**.

Earlier focused device validation, before the pattern and training-state
guard follow-ups: **9 passed, 0 skipped** with `pytest --forked`, on
**4x NVIDIA H100 80GB HBM3**, driver **580.159.04**, Torch
**2.10.0.2+cu130 / CUDA 13.0**, Triton **3.6.0**, Transformers
**5.12.0**, using the previously validated DeepEP runtime:

- All four eager/fused and uniform/skewed skip-parity cases run two
training steps on each model. They retain the original numerical bounds,
check last-step output/input/router/parameter gradients and accumulated
parameter deltas, and verify one forward combine per layer per step
rather than two.
- The four upstream non-reentrant/nested-reentrant replay cases still
pass, confirming that the shared context preserves normal replay
behavior.
- The recorded fused-weighting backward comparison runs in a fresh
worker. The original ordinary unittest reproduces `Cannot re-initialize
CUDA in forked subprocess` on the same setup; the new worker-based case
passes.

GPU reproduction selector, from `tests/`:

```bash
PYTHONPATH=.. DEEPSPEED_RUN_H100_TESTS=1 pytest --forked \
  unit/module_inject/test_auto_ep_comm.py unit/v1/moe/test_autoep_deepep_parity.py \
  -k 'skipping_the_recomputed_combine or recorded_fused_row_weighting or non_reentrant_checkpointing_replays'
```

Changed-files pre-commit passed for all 11 files in the final PR delta.
Existing device evidence is reused for unchanged kernels/backward and
supported training paths; GPU tests, full E2E and the existing
performance matrix were not restarted for these guard follow-ups. The
new state predicate is exercised through actual Torch
checkpoint/autograd on CPU, not presented as a fresh H100 execution or a
real Transformers-model run. The focused tests do not establish every
ZeRO/offload/TP/PP combination, other hardware, arbitrary checkpoint
composition or long-run convergence.

The static CI selector includes the v1 AutoEP unit and parity files.
Real DeepEP cases remain gated on the opt-in H100 test flag, four GPUs
and a GIN-capable DeepEP build, so test collection alone does not prove
they ran. The standalone recorded-weighting CUDA comparison is outside
Modal's v1 test scope and was explicitly included in the focused
hardware command above; its recorded path is also exercised by the v1
model-parity cases. Full GPU CI follows the repository's merge-queue
workflow.

## Existing performance evidence

Qwen3-30B-A3B, **8 H100s**, EP8, micro-batch **4**, gradient
accumulation **16**, sequence **4096**, DeepEP **28 SMs**, reentrant
activation checkpointing; **30 steps with 10 warmup**. The equivalent
benchmark prototype records the same weighting/combine backward but
returns uninitialized output where the product fills NaN. Both arms
inherit concatenated gate+up and backward weight-gradient overlap; this
is the **incremental skip effect**, not their combined benefit.

One allocation, order normal / skip / skip / normal:

| Recompute | Run medians | Mean |
|---|---|---:|
| Normal | 20,575.1 / 20,574.2 ms | 20,574.7 ms |
| Combine + post-weighting forward skipped | 19,945.7 / 19,928.2 ms |
**19,936.9 ms (-3.10%)** |

Peak allocated memory stayed at **58.69 GB**; peak reserved memory was
**0.25 GB lower**. Loss differences over these 30 steps were within
same-arm repeat noise (maximum **9.4e-4**). The 8-GPU residual-block
gate had numerical equality under `torch.equal` for output/input/router
gradients and expert-gradient differences around **5e-5 relative L2**,
within two normal recomputes' variation. `torch.equal` is not a claim
about signed-zero bit patterns.

The measurements are historical prototype evidence, **not** a retiming
of the rebased product or a universal benefit across models/hardware.
Skipping the forward combine removes that recompute transfer; it does
not add overlap or remove the cached dispatch and weight-gradient
communication required by backward.

---------

Signed-off-by: yh0903 <helloyu0903@gmail.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: pengdurice <pengduhit@gmail.com>
@tohtana
tohtana enabled auto-merge November 14, 2026 23:37
@tohtana
tohtana added this pull request to the merge queue Nov 15, 2026
Merged via the queue into deepspeedai:master with commit 5dc44e8 Nov 15, 2026
19 checks passed
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants