Skip to content

AutoEP: support combine_impl="fused_weighted_sum" with AutoEP+AutoTP folding - #8847

Open
pengdurice wants to merge 4 commits into
deepspeedai:masterfrom
pengdurice:peng-autoep-fused-combine-folded-tp-v2
Open

pengdurice wants to merge 4 commits into
deepspeedai:masterfrom
pengdurice:peng-autoep-fused-combine-folded-tp-v2

Conversation

@pengdurice

@pengdurice pengdurice commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

AutoEP: support combine_impl="fused_weighted_sum" with AutoEP+AutoTP folding

Part of: #8672 (Q4 2026 roadmap), "Mixture-of-Expert (MoE) Training Scaling and Kernel Development": "AutoEP Performance Optimization & Parallel Folding (AutoEP + AutoTP)" (PoC @tohtana @pengdurice). Follows #8670.

Problem

combine_impl="fused_weighted_sum" was refused whenever tensor_parallel.autotp_size > 1:

  • deepspeed/module_inject/auto_ep_config.py (validate_autoep_config) raised ValueError.
  • deepspeed/module_inject/auto_ep_layer.py (set_deepspeed_parallelism) raised the same error.

The reason was that the folded path restores tokens with its own function, restore_combined in
deepspeed/moe/ep_tp_dispatch.py, and the fused kernel was only wired into the unfolded path.

restore_combined works like this:

  1. Each TP peer sends only part of the routed assignments to the experts (partition_assignments).
  2. After the experts, it all-gathers the rows, their token index, their top-k slot and their routing weight over the
    TP group.
  3. It casts the routing weights to the activation dtype, multiplies, and adds the products with one index_add_ per
    top-k slot, all in the activation dtype.

So under folding, users could not get the memory saving and the FP32 accumulation of the fused kernel, and the
folded restore did its arithmetic in bf16.

Change

  • New restore_combined_fused in deepspeed/moe/ep_tp_dispatch.py:
    • It does the same differentiable all-gathers as restore_combined for the rows and the routing weights, so the
      tp_size gradient factor that the folded AVERAGE and EXPERT_TP_CANCEL strategies cancel is unchanged.
    • It all-gathers one flat index (token * top_k + slot) instead of the token index and the slot separately.
    • It keeps the routing weights in the router dtype, scatters them into [tokens, top_k], and calls the existing
      fused_weighted_restore. The kernel is unchanged.
    • It raises a clear RuntimeError if the gathered rows do not cover every (token, slot). The folded payload never
      drops or pads assignments today, so this cannot trigger now; it protects the kernel from reading an unset source
      row if capacity dropping is added later.
    • validate_coverage=True runs the same coverage check as restore_combined.
  • AutoEPMoELayer._forward calls restore_combined_fused in the folded branch when
    combine_impl == "fused_weighted_sum". The default ("auto" → "weighted_sum") still calls restore_combined.
  • The two autotp_size > 1 refusals are removed. The other fused refusals stay: expert_tensor_parallel_size > 1,
    DeepEP, score_apply other than "post", and unsupported device or dtype.
  • Docs: docs/code-docs/source/autoep.rst describes the folded fused restore and drops the refusal from the list;
    docs/_pages/config-json.md drops the autotp_size=1 requirement and lists float32 among the accepted activation
    dtypes, as the kernel's check does.

Tests

On master e35282b with this change, pytest 8.3.5:

Test What it checks GPUs torch 2.8.0+cu126 torch 2.9.1+cu128
test_autoep_unit.py (includes TestAutoEPConfig::test_fused_combine_accepts_folded_tensor_parallelism, was ..._rejects_...) the config is accepted with tp_size=2; no other config change up to 8 214 passed not run
test_autoep_autotp_dispatch.py (includes test_restore_combined_fused_rejects_a_missing_assignment and TestRestoreCombinedFusedTensorParallel, fp32 and bf16 rows) a missing (token, slot) raises instead of reading an unset row; 2 TP peers with different row counts, each back-propagating a different gradient: the output is bitwise equal to the unpartitioned fused_weighted_restore, and the row and score gradients, summed over the peers, match the unpartitioned gradients 0 and 2 12 passed 12 passed
test_autoep_fused_parity.py::TestAutoEPFusedParityFoldedTensorParallel (ZeRO 0, 2 and 3, with and without activation checkpointing) one training step with TP 2 × EP 2: the loss, output, input gradient, every parameter gradient and every parameter update of the fused run match the default folded run 4 6 passed 6 passed
rest of test_autoep_fused_parity.py (master's cases) unchanged 1-2 not run (they fail on torch 2.8 on master too, see below) 17 passed
test_autoep_fused_token_ops.py the kernel is unchanged 1 63 passed not run
test_autoep_autotp_grad_parity.py with DEEPSPEED_RUN_H100_TESTS=1 no change to the default folded path up to 8 20 passed not run
test_auto_ep_comm.py, test_autoep_autotp_folding_config.py other uses of the combine and folding settings up to 8 65 passed, 3 skipped, 6 failed (see below); 33 passed not run
test_autoep_expert_activation.py other uses of combine_impl 1-2 not run (stalls on torch 2.8 on master too, see below) 96 passed, 12 skipped (a grouped path that needs CUDA tensors when Triton is installed)

Hardware: 1 node of 8 NVIDIA H100 80GB (driver 595.112.07); torch 2.8.0+cu126 with Triton 3.4.0, and torch
2.9.1+cu128. JIT-built ops used the CUDA 12.8 toolkit (CUDA_HOME).

Every failure and stall above also happens on master without this change, and passes or does not occur on torch 2.9.1:

  • test_auto_ep_comm.py::TestSkipRecomputeCombine (6 cases, added by AutoEP: opt-in skip of the recomputed DeepEP combine #8745) runs torch._grouped_mm on the CPU,
    which torch 2.8 does not implement (Could not run 'aten::_grouped_mm' with arguments from the 'CPU' backend); the
    same 6 fail on master e35282b.
  • Master's 17 fp16 cases of test_autoep_fused_parity.py (TestAutoEPFusedParityExpertParallel x 16,
    TestAutoEPFusedParityLocalExperts) fail on torch 2.8 with RuntimeError: Expected mat_a to be BFloat16 matrix got Half, also on master 3fe2d95 without this change: torch 2.8's torch._grouped_mm accepts only bf16, and these
    cases run in fp16 with grouped GEMM.
  • On torch 2.8 the backward of torch._grouped_mm does not return for some shapes when one expert receives no rows:
    test_autoep_expert_activation.py::TestFusedGateUp::test_matches_separate_with_skewed_and_empty_experts stalls
    there the same way on master 3fe2d95 without this change.

The folded test reads each parameter before and after the step. Under ZeRO-3 a parameter holds only its partition, so
the test's _parameters helper now reads the full fp32 value of ZeRO-3 parameters (safe_get_full_fp32_param); in
these fp32 runs that is the parameter itself. Master's cases have no ZeRO-3 parameters and are unaffected.

The end-to-end folded test runs in FP32, on MockMoEOnlyTransformer, without grouped GEMM:

  • FP32: the default folded restore rounds each product and each top-k addition to the activation dtype. In fp16 the
    two restores differ by 1 to 1.5 units in the last place of the MoE output (about 1,600 in this model), which is more
    than PARITY_TOLERANCE allows after the LM head. In FP32 the two forward passes are bitwise equal. Since both paths
    run in FP32, the folded test compares them directly; master's fp16 cases are judged against an FP32 reference
    instead (Fix torch-latest workflow unit failures #8950), which here would equal the default path.
  • No attention: the key bias of nn.MultiheadAttention has a true gradient of zero, so its computed gradient is
    rounding noise, and Adam's first step turns that noise into ±lr. The parameter-update check then fails by 2 × lr no
    matter which restore is used.
  • No grouped GEMM: on torch 2.8, torch._grouped_mm accepts only bf16, so the fp32 run would fail before reaching the
    restore.

pre-commit run --files passes on the changed files.

Benchmark

One TP group of 2 H200 GPUs on one node. bf16 rows, FP32 routing weights, random routing with distinct experts per
token. The hidden size, top-k and expert count are the MiniMax-M3 and GLM-5.2 values. Memory is the peak above the
inputs. Time is one forward and backward, averaged over 10 runs after 3 warm-up runs, and includes the identical
partition step. Errors are against an FP64 reference. (Measured on master 5f266e2; neither ep_tp_dispatch.py nor the kernel's
fused_weighted_restore has changed on master since.)

Shape (tokens per TP group, top-k, experts, hidden) Forward peak, GiB (default → fused) Backward peak, GiB Time, ms Output error, relative L2 Score gradient error, relative L2
8,192, 4, 128, 6144 (MiniMax-M3) 1.22 → 0.75 1.59 → 0.84 13.3 → 7.4 3.58e-3 → 1.66e-3 2.35e-3 → 8.4e-8
32,768, 4, 128, 6144 (MiniMax-M3) 4.88 → 3.00 6.38 → 3.38 41.1 → 21.0 3.57e-3 → 1.66e-3 2.34e-3 → 8.3e-8
8,192, 8, 256, 6144 (GLM-5.2) 2.35 → 1.50 3.09 → 1.60 26.7 → 12.0 4.36e-3 → 1.66e-3 2.34e-3 → 8.6e-8
32,768, 8, 256, 6144 (GLM-5.2) 9.39 → 6.01 12.38 → 6.38 91.9 → 38.8 4.36e-3 → 1.66e-3 2.35e-3 → 8.7e-8

The fused output error of 1.66e-3 is the rounding of the bf16 output itself. The score gradient is the router
gradient; the default folded path computes it through bf16 weights, the fused path in FP32.

Script: bench_folded_restore.py (run with torchrun --nproc_per_node=2).

Notes

  • The default folded path and the fused path give close but not bitwise-equal results, because the default path
    multiplies and adds in the activation dtype.
  • AutoEP+AutoTP folding runs at ZeRO stages 0 to 3 on master (CPU optimizer offload at ZeRO-3 since AutoEP + AutoTP folding: allow CPU optimizer offload under ZeRO-3 #8829); the
    end-to-end test covers ZeRO 0, 2 and 3.

Duplicate check

Searched open pull requests on 2026-11-13 and again on 2026-11-17 ("fused_weighted_sum", "AutoEP AutoTP folding", "folding universal"): none
enables the fused combine under folding. #8829 (optimizer offload under folding) and #8823 (clipping under folding)
are merged and change other parts of folding; #8745 and #8739 change the DeepEP combine.

AI assistance

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

…folding

Signed-off-by: pengdurice <pengduhit@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.

Read at 2f187305.

The folded path looks right to me. all_flat_indices carries token * top_k + slot for each gathered row, which is what the unfolded call passes as token_indices_sorted, so the kernel sees the same row-to-assignment map. The rows and the routing weights still go through the differentiable gathers, so the folding gradient factor is unchanged.

The kernel needs CUDA and Triton, so on CPU I swapped fused_weighted_restore for an FP32 reference that weights and sums the top-k slots in slot order. I then ran the shapes of your TestRestoreCombinedFusedTensorParallel, with fp32 rows, on 2 gloo ranks: 48 tokens, top-k 4, 8 experts, hidden 130, uneven per-peer row counts (98 and 94), a different upstream gradient per peer.

  • On both ranks, restore_combined_fused matches the unpartitioned reference bitwise.
  • The summed row gradients differ by at most 1.2e-7, and the score gradients by at most 4.8e-6.
  • In fp32 it is also bitwise equal to the default restore_combined: output, row gradients and score gradients.

So the new indexing, gather and score scatter check out. The kernel itself is unchanged and wasn't exercised here. The CPU-runnable tests in test_autoep_autotp_dispatch.py, test_autoep_unit.py and test_autoep_fused_parity.py pass (202); the rest need CUDA, most also Triton.

Merge note: this branch merges cleanly with master. It conflicts with #8745 only in tests/unit/v1/moe/test_autoep_unit.py.

@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 10, 2026
pengdurice and others added 2 commits November 13, 2026 19:09
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: pengdurice <pengduhit@gmail.com>
…s in the config docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: pengdurice <pengduhit@gmail.com>
@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 2026
Resolve the conflict with deepspeedai#8745 in tests/unit/v1/moe/test_autoep_unit.py: keep its two skip_recompute_combine tests and this PR's test_fused_combine_accepts_folded_tensor_parallelism.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: pengdurice <pengduhit@gmail.com>
@pengdurice
pengdurice marked this pull request as ready for review November 17, 2026 04:16
@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:21:56.171720Z 4615408 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.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants