Skip to content

AutoEP: opt-in routing weights inside the expert activation - #8748

Open
yh0903 wants to merge 2 commits into
deepspeedai:masterfrom
yh0903:yh0903/autoep-row-weighting-in-activation
Open

yh0903 wants to merge 2 commits into
deepspeedai:masterfrom
yh0903:yh0903/autoep-row-weighting-in-activation

Conversation

@yh0903

@yh0903 yh0903 commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

The backward weight-gradient overlap prerequisite, #8739, has merged. This follow-up is integrated onto current master as a child-only delta; it does not reintroduce the parent commits or change the disabled defaults. Activation weighting remains an independent opt-in.

The DeepEP route applies each received row's routing weight to the expert output: one more pass over [rows, hidden] in forward, and in backward a pass that also reduces each row's weight gradient. The down projection is linear and bias-free, so scaling its input inside the activation (h = act(gate, up) * weight) is the same mathematical function. Evaluation order and intermediate rounding change, including for FP32; BF16/FP16 activation values are rounded once after the FP32 weighted product, rather than after post-expert weighting. No bitwise-equivalence claim is made. NeMo AutoModel applies its routing probabilities at this mathematical boundary.

This adds expert_parallel.row_weighting_impl="activation".

Change

  • swiglu_triton.swiglu_weighted(gate, up, weights): fused Triton kernels.
    • Forward computes silu(gate) * up * weight in FP32 and rounds once.
    • Backward, one program per row, returns the gate and up gradients and the row's FP32 weight gradient from the same pass.
    • Off the accelerator, or without Triton, it uses the same expression in plain PyTorch.
  • ExpertActivation gains an optional weighted_fused_fn, registered for swiglu.
    • apply_expert_activation(..., row_weights=...) uses it when available.
    • Otherwise it computes the form in FP32, multiplies, and rounds once.
  • Separate and packed gate+up have weighted forward/backward callbacks. They share the same weighted kernel arithmetic with explicit row strides; the packed path reads projection halves in place and writes one packed gradient, avoiding half copies.
  • GroupedExperts.forward and all three expert paths (for-loop, torch._grouped_mm, Triton grouped GEMM) take optional row_weights. The for-loop path splits them per expert and ignores padding rows.
  • The fused native grouped-GEMM and parent's deferred-weight-gradient path also take row_weights. dX and the FP32 router-weight gradient return through the expert backward immediately; only parameter-gradient GEMMs enter the slot, so async combine receives both token and routing-score gradients.
  • With "activation", the DeepEP route hands the received weights to the experts and does not weight their output afterwards.
  • Rejected rather than ignored:
    • score_apply resolving to "pre", checked at layer construction;
    • comm_backend other than "deepep";
    • autoep_size=1.
  • Defaults are unchanged.
  • Shape/dtype/device mismatches are rejected before kernel launch. Weighted Triton kernels select the input device/current stream and restore the caller; they are first-order only and explicitly reject create_graph=True.
  • Docs: autoep.rst and the config reference.

Tests

  • Triton (GPU):
    • Forward and gate/up gradients against the FP32 reference, for FP32/FP16/BF16 and even/uneven shapes.
    • The weight gradient within FP32 summation order.
    • Empty input; validation of the weights.
  • CPU:
    • For every registered activation, the weighted activation equals the form's FP32 product rounded once under value comparison, without claiming signed-zero bit-pattern equivalence.
    • The for-loop experts with row weights equal post-expert weighting (output, input and weight gradients), including an empty expert and padding rows.
  • GPU: the torch._grouped_mm and Triton grouped GEMM paths take row weights like the for-loop path, for every activation.
  • Config and layer: "activation" is rejected without DeepEP, with autoep_size=1, and when score_apply resolves to "pre". The DeepEP route hands the weights to the experts and does not call the row weighting.
  • GPU, test_row_weighting_in_activation_matches_eager, 4 GPUs with DeepEP:
    • grouped GEMM (fused kernel) and for-loop paths; uniform and skewed routing; reentrant checkpointing;
    • identical routes;
    • output, input and every parameter gradient within 2e-2 relative L2 of eager.
  • GPU suites (DeepEP parity, comm, unit, SwiGLU Triton, expert activation): 394 passed, 1 skipped, 2 failed.
    • Both failures are TestMiniMaxM3Block::test_replaced_block_matches_hf_block, and the skip is MiniMax-M3 router-logit capture. Both need Transformers >= 5.15.0; the image has 5.12.0.
  • End to end, Qwen3-30B-A3B on 8 H100s, measured with an equivalent benchmark patch on our benchmark base (routing weight inside the fused SwiGLU).
    • Setup: expert parallel size 8, micro-batch 4, 16 accumulation steps, sequence length 4096, DeepEP with 36 SMs, reentrant checkpointing, 30 steps with 10 warmup.

    • The base also had fused gate+up, the backward weight-gradient overlap, the recomputed-combine skip, and the whole-buffer slice fix.

    • One job, order base, change, change, base:

      Run medians Mean
      Separate row weighting 19,553.4 / 19,547.3 ms 19,550.3 ms
      Weight inside the SwiGLU 18,863.4 / 18,866.8 ms 18,865.1 ms (-3.50%)
    • A real-DeepEP check on 8 GPUs before the timing: output 1.2e-3, input gradient 1.6e-3, router gradient 4.3e-3, expert gradients up to 4.3e-3 relative L2 against the separate weighting.

    • Losses agree within same-arm repeat noise; allocated memory unchanged.

Ordered review follow-up

  • Current-master integration retains the merged skip-combine guard/lifecycle, frozen-weight gradient pruning and clamped-activation callbacks. With activation weighting enabled, the skip-combine path skips only the combine: it must not apply the row weight again after the experts.
  • The new two-step CPU route regression checks output/input/router/expert gradients with uniform and empty-expert routing. Two real-DeepEP cases also compose activation weighting with the merged skip-combine path. The weighted SwiGLU kernel and public weighted-entrypoint ASTs are unchanged from the previously validated child.
  • Local CPU compatibility checks on macOS, torch 2.10.0 and transformers 5.12.0: 42 passed, 21 CUDA cases skipped. Changed-files pre-commit passes.
  • Targeted device acceptance: 18 distinct cases passed, 0 skipped, on 4x NVIDIA H100 80GB HBM3, driver 580.159.04, torch 2.10.0.2/CUDA 13.0, Triton 3.6.0 and transformers 5.12.0, under pytest --forked. Eight weighted backward/deferral cases passed in the first run; the ten distributed cases initially failed at transport initialization before product checks. Only those ten were retried, with the accepted parent's default NCCL transport setup, and all passed on identical source. These cover ZeRO 1/2, separate/fused gate+up, uniform/skewed routes, and two-step activation-weighting plus skip-combine parity. No fresh throughput or convergence sweep was run.
  • The current CI selector includes the v1 AutoEP parity tests; public test collection is checked separately from the actual targeted H100 acceptance.
  • This child inherits the parent/master integration, including actual ZeRO-stage forwarding, checkpoint-layout replay, exact-size slice behavior and failure-safe async event/carveout handling. It does not duplicate those changes.
  • The published mathematical contract is not a bitwise contract. Existing weighted-kernel and model-gradient tolerances remain unchanged; near-zero Adam updates are not used as the only correctness criterion.
  • On CPU, weighted scalar/reference, metadata and deferral checks pass, including all four activations, FP32/BF16, separate/packed projections and router gradients. The combined comm/replay suite passes 68/68 under pytest --forked on Apple M4 Pro/torch 2.14.1.
  • Earlier targeted acceptance of the reviewed child 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: 85 passed, 0 skipped. This includes all old weighted-kernel shapes/dtypes, packed/unpacked and standalone-gradient equivalence, device/higher-order contracts, all four activation forms, and real eager-vs-activation-vs-overlap comparisons at ZeRO 1/2 with separate/fused gate+up and uniform/skewed routing.
  • The model-level comparisons retain the existing 2e-2 relative-L2 bound and inspect every trainable accumulated gradient before clipping. Dropping only the custom backward's row-weight gradient reproduces all eight direct-gradient failures and all six route/checkpoint subcase failures on CPU, confirming that the router path is not silently omitted.
  • The existing 394-passed/1-skipped/2-version-related-failure GPU suite and 3.5% E2E prototype evidence are reused. No fresh throughput or convergence sweep was run; the historical percentage is not a retiming of this integrated child.

Validation limits: real DeepEP supports BF16 rows here; direct weighted kernels cover FP32/FP16/BF16 and FP32 weights. Overlap requires the parent's native grouped-GEMM and ZeRO 1/2 scope. No fresh offload, expert-TP, multi-node or non-CUDA-device matrix is claimed.

AI assistance was used for review, conflict integration and tests. The submitting human authorized this existing PR update; maintainer review is still required. This is not a new duplicate feature.

AI review follow-up

The four direct weighted SwiGLU entrypoints now select Triton from actual CUDA tensor placement, not the configured accelerator's on_accelerator() predicate. Valid CPU tensors retain the eager forward and standalone backward even on a CUDA/Triton host with DS_ACCELERATOR=cpu. The new regression uses the real CPU accelerator and an independent eager oracle for FP32/BF16, separate/packed projections, and both autograd and standalone backward.

Current master is integrated without restoring obsolete parent behavior. The newly merged cross-backward dW staging remains unchanged for its existing paths. Combining row_weighting_impl="activation" with deferred_dw_flush_period > 1 is explicitly rejected at config/layer validation and the direct expert interface rather than silently ignoring an option; that combination is outside this PR's validated scope. Existing ZeRO-1/2 backward overlap remains supported.

CPU validation of the directly affected weighted/staging/checkpoint cases: 70 passed, including 27 subtests, on macOS/Torch 2.10.0. Changed-files pre-commit passed.

Current acceptance on 4x NVIDIA H100 80GB HBM3, driver 580.159.04, Torch 2.10.0.2/CUDA 13.0, Triton 3.6.0 and Transformers 5.12.0:

  • 18 device cases passed, 0 skipped under pytest --forked, retaining the existing ZeRO-1/2 weighted overlap, short/reentrant recompute and standalone weighted-gradient parity checks.
  • With actual DS_ACCELERATOR=cpu on that CUDA host and Triton availability verified, all 8 new CPU-mode cases pass. Replacing only the weighted module with the reviewed runtime reproduces 8 failures, each Expected a cuda device, but got: cpu.

Kernel arithmetic and the historical E2E evidence are unchanged; no timing or convergence sweep was restarted.

Current targeted device selector, from tests/ on the documented four-H100/DeepEP setup:

PYTHONPATH=.. DEEPSPEED_RUN_H100_TESTS=1 pytest --forked \
  unit/v1/moe/test_autoep_deepep_parity.py unit/v1/moe/test_autoep_expert_activation.py \
  -k 'activation_weighting_composes or (skipping_the_recomputed_combine and activation) or weighted_gradients_compose_with_deferral_on_cuda'

banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Oct 27, 2026
…peedai#8652)

# AutoEP: fused Triton kernel for the clamped expert activations

<!-- r3 2026-10-15: branch peng-add-fuse-fn-clamped-form-v2 (worktree
/fsx/peng/workspace/ds-add-fuse-fn-clamped-form-v2)
on master 5f266e2; pushed to the PR's branch
peng-add-fuse-fn-clamped-form-v1 with --force-with-lease (GitHub
shows the PR's commit 90c9660 in conflict with master). DRAFT
2026-10-12, for the PR body of deepspeedai#8652. Replaces the whole current body.
Items marked TODO(user) need the
submitter. Job IDs of every result: SOURCES.md. -->

**Branch:** `peng-add-fuse-fn-clamped-form-v1`, rebased on `master` at
`5f266e26d` (2026-10-15). The expert activation registry it
registers into is merged (deepspeedai#8650), and so is the fused gate+up projection
(deepspeedai#8733), which this PR now also covers.
**Part of:** deepspeedai#8672 (Q4 2026 roadmap), "Mixture-of-Expert (MoE) Training
Scaling and Kernel Development": "AutoEP
Performance Optimization & Parallel Folding (AutoEP + AutoTP)" (PoC
@tohtana @pengdurice). Follows the merged expert
activation registry (deepspeedai#8650) and MiniMax-M3 preset (deepspeedai#8651).

## Summary

The clamped expert activations `swiglu_clamped` (DeepSeek-V4) and
`swiglu_oai` (GPT-OSS, MiniMax-M3) run as plain
PyTorch expressions that keep about four `[rows, ffn]` temporaries for
backward. Plain `swiglu` has fused Triton
kernels that keep only `gate` and `up`. This PR adds the same kernels
for the clamped forms, for both expert layouts:

- `gate_up_impl="separate"` (two grouped GEMMs): `swiglu_clamped(gate,
up, ...)`.
- `gate_up_impl="fused"` (one grouped GEMM, deepspeedai#8733):
`swiglu_clamped_packed(gate_up, ...)`, which reads the two halves
  of the packed GEMM output in place, as master's `swiglu_packed` does.

At the busiest rank of a MiniMax-M3 run that ran out of memory
(1,045,081 rows x 3,072, bf16), one `swiglu_oai`
call goes from 41.86 GiB extra peak memory and 77.8 ms to 17.94 GiB and
11.9 ms, the same as plain `swiglu`.

## Duplicate check

Open PRs and issues searched on 2026-10-12 for "swiglu", "clamp",
"expert activation" and "gpt-oss": no other work on
fused clamped activations. deepspeedai#8748 (another author, open) adds a different
kernel, `swiglu_weighted` (routing weight
inside the activation, plain `swiglu` only), to the same two files
(`swiglu_triton.py` and the registry in
`ep_experts.py`). The two do not overlap in function; whichever merges
second needs a small rebase.

## Problem

Each clamped form is two clamps, a sigmoid, three products and an add in
plain PyTorch, each a full `[rows, ffn]`
temporary, most of them saved for backward. On an expert-parallel rank
this is where the memory goes, because
AutoEP has no capacity limit and real routers send some ranks several
times the mean number of rows.

MiniMax-M3 at 65,536 tokens with expert parallel 32 on 4 nodes of 8 H200
ran out of memory there: the busiest rank
received 1,045,081 rows (3.99 times its own 262,144) and failed inside
`apply_expert_activation` on one 11.96 GiB
temporary, with 129.50 GiB already in use. (Setup: all 60 layers, real
checkpoint, `minimax_m3` preset, ZeRO-3 with
the optimizer state on the host, activation checkpointing; torch
2.8.0+cu126, transformers 5.15.1, DeepSpeed master
`4a5856c25` plus the then-open registry PR.) Over the 57 MoE layers, the
busiest of 32 ranks received a median 4.20
times the mean number of rows (maximum 7.84).

## The change

| File | What |
|---|---|
| `deepspeed/ops/triton_ops/swiglu_triton.py` |
`_swiglu_clamped_fwd_kernel` / `_swiglu_clamped_bwd_kernel`, modelled on
master's swiglu kernels: int64 offsets, float32 math, one rounding on
store, `OAI: tl.constexpr` selects the form, `PACKED: tl.constexpr`
reads `gate` and `up` from one `[rows, 2 * INTER]` tensor with master's
packed indexing. The clamp gradient passes at the limit, as
`torch.clamp`'s does. Public `swiglu_clamped(gate, up, alpha, limit,
oai)` and `swiglu_clamped_packed(gate_up, alpha, limit, oai)`;
plain-PyTorch fallback without Triton or on the CPU. The packed backward
raises for `create_graph=True`, as master's packed swiglu does |
| `deepspeed/moe/ep_experts.py` | registers the kernels as `fused_fn`
and `packed_fused_fn` of `swiglu_clamped` and `swiglu_oai`. Nothing else
changes: the grouped-GEMM expert paths reach them through
`apply_expert_activation(..., fused=True)` and
`apply_packed_expert_activation`; the for-loop reference path keeps
`fused=False` |
| `docs/_pages/config-json.md` | one sentence: which forms run a fused
kernel |
| `tests/unit/v1/ops/triton_ops/test_swiglu_triton.py`,
`tests/unit/v1/moe/test_autoep_expert_activation.py` | see Tests |

Size: 264 added and 2 removed lines under `deepspeed/` (232 added in
`swiglu_triton.py`, 32 in `ep_experts.py`).

## Measured

One H200, torch 2.8.0+cu126, Triton 3.4.0, through
`apply_expert_activation` / `apply_packed_expert_activation`
(`fused=True`). 1,045,081 rows x 3,072 in bf16 (one `[rows, ffn]` tensor
= 5.98 GiB), alpha 1.702, limit
7.0, inputs at 6 x standard normal so most values are past a clamp.
Extra peak = `max_memory_allocated` during
forward + backward minus the memory allocated before (inputs and
upstream gradient). Kept = memory still allocated
after the forward, minus the output. Time = median of 5 forward +
backward passes after 3 warm-ups.

| Form | Layout | master `1c862f7df`: extra peak / kept / time | this
PR: extra peak / kept / time |
|---|---|---|---|
| `swiglu` (existing kernels, for comparison) | separate | 17.94 GiB /
0.00 GiB / 11.9 ms | 17.94 GiB / 0.00 GiB / 11.9 ms |
| `swiglu` | packed | 17.94 / 0.00 / 11.9 ms | 17.94 / 0.00 / 11.9 ms |
| `swiglu_clamped` | separate | 35.88 / 17.94 / 51.6 ms | **17.94 / 0.00
/ 11.9 ms** |
| `swiglu_clamped` | packed | 35.88 / 17.94 / 92.1 ms | **17.94 / 0.00 /
13.1 ms** |
| `swiglu_oai` | separate | 41.86 / 23.92 / 77.8 ms | **17.94 / 0.00 /
11.9 ms** |
| `swiglu_oai` | packed | 41.86 / 23.92 / 118.3 ms | **17.94 / 0.00 /
13.2 ms** |

Per MoE layer on that rank, `swiglu_oai` keeps 23.92 GiB less for
backward and runs 6.5 times faster (separate) or
9.0 times faster (packed). The packed clamped kernels are 1.2-1.3 ms
slower than master's packed `swiglu` kernel,
which does less arithmetic per element. Bench script:
`expert_activation_bench.py` (TODO(user): attach as a gist or
drop this line).

## Tests

Command, from `tests/`, on 1 node of 8 H200 (143,771 MiB each, driver
580.126.09), torch 2.8.0+cu126, Triton 3.4.0,
transformers 5.15.1, pytest 9.1.1:

```bash
DEEPSPEED_RUN_H100_TESTS=1 python -m pytest unit/v1/ops/triton_ops/test_swiglu_triton.py \
    unit/v1/moe/test_autoep_expert_activation.py -v \
    -k "not (skewed_and_empty or accumulated_updates_and_checkpoint)"
```

Result: **204 passed**, 12 deselected, in 31 s. On master `5f266e26d`
(2026-10-15): **204 passed**, 12 deselected, in 34 s on torch 2.8.0; the
two empty-expert tests from deepspeedai#8733 on torch 2.9.1: 12 passed on this
branch and 12 passed on master.

The two deselected tests are master's (deepspeedai#8733). On torch 2.8.0+cu126 on
H200 they do not finish, on master as well
as on this branch: they pass an empty expert group (`counts = [37, 0,
291, 72]` and `[16, 0, 32, 16]`) to
`torch._grouped_mm`, whose backward never returns for some shapes when a
group is empty on that torch version (GPU at
100% with no progress; known from MiniMax-M3 work, one-GPU reproduction
available). AutoEP itself never passes an
empty group, because `generate_permute_indices` gives every local expert
at least 8 rows. On torch 2.8.0 master's
`test_matches_separate_with_skewed_and_empty_experts[swiglu]` did not
finish in 300 s; on torch 2.9.1+cu128 (Triton
3.5.1) both tests pass, **12 passed** on this branch and 12 passed on
master.

New and changed tests:

| Test | What it would catch |
|---|---|
| `test_clamped_forward_matches_reference` (2 forms x 3 dtypes x 6
shapes) | a wrong output: compared with the expression evaluated in
float32 and rounded once; inputs at scale 4 so about 8% are past a
clamp; the kernel must also be no farther from float32 than the eager
low-precision evaluation |
| `test_clamped_backward_matches_reference` (2 x 3 x 5) | wrong input
gradients, the same way, with a random upstream gradient |
| `test_clamped_alpha_and_limit_are_honoured` | alpha or limit ignored;
a nonzero gradient where an input was clamped |
| `test_clamped_gradient_at_the_limit_is_inclusive` | a gradient that
stops at `gate == limit` or `up == -limit`, where `torch.clamp`'s passes
|
| `test_clamped_empty_input`, `test_clamped_non_contiguous_input`,
`test_clamped_shape_and_dtype_mismatch_rejected` | the edge cases
master's swiglu tests cover |
| `test_clamped_packed_matches_the_separate_kernel_exactly` (2 forms x 2
dtypes x 4 shapes, including 3-D and empty) | a packed path that reads
the wrong half or row: output and gradient bit-equal to the separate
kernel |
| `test_fused_kernel_matches_plain_pytorch` (every form with a
`fused_fn`) | `apply_expert_activation(fused=True)` differing from the
plain form evaluated in float32 and rounded once (bf16, 256 x 3,072) |
| `test_packed_kernels_are_registered` (was
`test_only_swiglu_has_a_packed_kernel`) | the fused gate+up path
silently running the clamped forms in plain PyTorch |
| `test_grouped_gemm_paths_match_the_for_loop`,
`test_packed_activation_matches_the_separate_halves` (master's, now
running the new kernels) | the grouped-GEMM paths differing from the
for-loop reference path |

`pre-commit run --files` passes on every changed file.

## Compatibility

The change is an elementwise kernel behind AutoEP's existing activation
registry; it does not depend on the ZeRO
stage, offload or parallel layout.

| | Validated | Not validated |
|---|---|---|
| Precision | float32, float16, bf16 (kernel tests); bf16 through the
expert paths | |
| Expert layouts | `gate_up_impl` `"separate"` and `"fused"`;
`torch._grouped_mm` and Triton grouped-GEMM paths (unit tests) | |
| End to end | | no training job has run with this kernel. The
MiniMax-M3 runs on 4 nodes used the plain PyTorch form (the
out-of-memory case above was avoided with expert parallel 4) |
| Accelerators | CUDA (H200); CPU fallback (plain PyTorch) | ROCm, XPU
and other Triton backends. The packed path sets the device with
`torch.cuda.device` (`#ignore-cuda`), as master's packed swiglu does |

## AI assistance

This PR was written with AI assistance (Claude).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: pengdurice <pengduhit@gmail.com>
@tohtana tohtana added needs-gpu-test GPU testing is recommended to validate the changes in this PR. and removed needs-gpu-test GPU testing is recommended to validate the changes in this PR. labels Nov 10, 2026
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 15, 2026
…bine (deepspeedai#8739)

The fused gate+up prerequisite, deepspeedai#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, deepspeedai#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:

```bash
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.

---------

Signed-off-by: yh0903 <helloyu0903@gmail.com>
Signed-off-by: Masahiro Tanaka <tanaka.masahiro@gmail.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: pengdurice <pengduhit@gmail.com>
Co-authored-by: Masahiro Tanaka <tanaka.masahiro@gmail.com>
Apply the reviewed activation-weighting child delta on top of the merged overlap implementation, retaining current replay, skip-combine, frozen-parameter and clamped-activation contracts. Return routing-score gradients alongside input gradients while deferring only parameter gradients.

Keep the disabled default unchanged and the weighted kernel arithmetic from the accepted implementation. Cover activation weighting together with skip-combine and the existing ZeRO-1/2 overlap matrix; retain the bounded numerical and historical performance claims.

Signed-off-by: yh0903 <helloyu0903@gmail.com>
@yh0903
yh0903 force-pushed the yh0903/autoep-row-weighting-in-activation branch from ac87d34 to e80c269 Compare November 17, 2026 04:27
@yh0903
yh0903 marked this pull request as ready for review November 17, 2026 04:27
@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T04:34:07.700278Z e80c269 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.

🟡 Changes recommended

The four weighted Triton entrypoints can select CUDA kernels for valid CPU tensors when DS_ACCELERATOR=cpu on a CUDA-capable host, causing failures instead of using the eager fallback.

1 open issue
What changed in this PR

Adds opt-in routing-weight application inside AutoEP expert activations, avoiding a separate post-expert weighting pass on the DeepEP route. Defaults remain unchanged; the new mode preserves the mathematical function but changes intermediate rounding.

Changes:

  • Adds weighted SwiGLU forward/backward kernels for separate and packed projections, with eager fallbacks.
  • Threads row weights through expert execution and deferred parameter gradients while preserving immediate router gradients.
  • Adds configuration guards, documentation, and coverage for kernel parity, checkpointing, and backward overlap.
File Description
tests/​unit/​v1/​ops/​triton_ops/​test_swiglu_triton.py Tests weighted kernels, gradients, validation, and device handling.
tests/​unit/​v1/​moe/​test_autoep_unit.py Tests configuration and score-application restrictions.
tests/​unit/​v1/​moe/​test_autoep_expert_activation.py Tests weighted activations, expert paths, and gradient deferral.
tests/​unit/​v1/​moe/​test_autoep_deepep_parity.py Adds distributed parity and overlap-composition coverage.
tests/​unit/​module_inject/​test_auto_ep_comm.py Tests weight handoff, async gradients, and skipped-combine behavior.
docs/​code-docs/​source/​autoep.rst Documents activation weighting, numerical behavior, and limitations.
docs/​_pages/​config-json.md Expands the row-weighting configuration reference.
deepspeed/​ops/​triton_ops/​swiglu_triton.py Implements weighted SwiGLU kernels and public entrypoints.
deepspeed/​moe/​ep_experts.py Propagates row weights through activations and expert execution.
deepspeed/​module_inject/​auto_ep_presets/​base.py Adds the activation-weighting configuration value.
deepspeed/​module_inject/​auto_ep_layer.py Passes weights into experts without weighting outputs again.
deepspeed/​module_inject/​auto_ep_config.py Validates backend and expert-parallel requirements.

Review effort: Balanced

Preserve current master cross-backward staging and frozen-parameter behavior while keeping activation weighting separately opt-in. Reject the unvalidated activation-plus-staging combination rather than silently ignoring either mode.

All four weighted SwiGLU entrypoints now require CUDA tensors before selecting Triton. Cover real CPU-accelerator eager parity on a CUDA-capable host for packed/separate forward and standalone backward. Kernel arithmetic is unchanged; targeted H100 acceptance and old-runtime negatives passed.

Signed-off-by: yh0903 <helloyu0903@gmail.com>

This branch has not been deployed

No deployments
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.

4 participants