Repository navigation
AutoEP: reorder expert rows with gathers on the collective path - #8671
Conversation
…and accumulating index_put permute_by_local_expert appended a zero row to every received token (a full copy) before gathering the padded expert-major buffer, and its backward was an accumulating index_put. unpermute_by_local_expert zero-filled a buffer and scattered into it. On CUDA both are now one gather each way: a Triton row gather that writes zeros at padding slots, and index_select through the inverse permutation. The values are the same permutation, so outputs and gradients are unchanged as compared by torch.equal; other tensors keep the previous code. Signed-off-by: yh0903 <helloyu0903@gmail.com>
…on the reorder needs The row-gather kernel addresses its index by linear offset but only made the source contiguous, so a strided index would have been read wrongly. The callers pass contiguous indices, and index.contiguous() is a no-op for them. The docstrings now say what the gathers rely on: the valid entries of the permuted indices are each row exactly once, which holds when the counts sum to the number of rows, and is not checked. They also describe the equality with the previous implementation as tested, with torch.equal, which does not distinguish +0.0 from -0.0, rather than bit for bit. Signed-off-by: yh0903 <helloyu0903@gmail.com>
…and in unpermute double backward The reorder tests covered BF16 and FP32 with contiguous tensors, and double backward only through the permute. They now also compare, in FP16 and BF16, rows seen through a column-strided view with column-major upstream gradients in both directions, and the unpermute's double backward. Signed-off-by: yh0903 <helloyu0903@gmail.com>
640c947 to
fcdf521
Compare
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
The test module probes CUDA during collection, causing its GPU tests to fail under the repository’s forked CI runner.
Review effort: Balanced
Findings: 1
Open (1)
What changed in this PR
Optimizes AutoEP expert-row reordering with Triton gathers while retaining the existing fallback path.
Changes:
- Adds gather-based permutation helpers with differentiable inverses.
- Integrates them into AutoEP’s CUDA path.
- Adds forward, gradient, layout, padding, and fallback tests.
| File | Description |
|---|---|
deepspeed/moe/ep_kernels.py |
Implements gather-based row permutation. |
deepspeed/module_inject/auto_ep_layer.py |
Uses gathers when supported. |
tests/unit/v1/moe/test_autoep_permute_rows.py |
Adds reorder correctness tests. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| ) and ep_kernels._TRITON_AVAILABLE | ||
|
|
||
|
|
||
| gpu = pytest.mark.skipif(not _cuda_triton(), reason="the gather-based reorder needs CUDA and Triton") |
There was a problem hiding this comment.
Hi @yh0903,
Thank you for your great work on AutoEP! The correctness looks good to me.
For performance, my microbenchmark of permute_by_local_expert and
unpermute_by_local_expert shows that forward slows down a bit for small tensors. Here is the result using RTX PRO 4500, PyTorch 2.14, CUDA 13.4.
It would be great if you have any idea to address this easily. But I don't think this is a blocker. The overall improvement is clear.
| Tokens / top-k / experts / EP / local experts | Rows x hidden | Counts / special case | Metric | Base median (IQR), ms | PR median (IQR), ms | Change |
|---|---|---|---|---|---|---|
| 8192 / 8 / 128 / 16 / 8 | 65,536 x 2,048 | [16, 8]; no empty expert |
permute forward | 1.638320 (0.015640) | 1.005200 (0.015072) | -38.6% |
| 8192 / 8 / 128 / 16 / 8 | 65,536 x 2,048 | [16, 8]; no empty expert |
permute backward | 1.574864 (0.004720) | 0.792128 (0.003992) | -49.7% |
| 8192 / 8 / 128 / 16 / 8 | 65,536 x 2,048 | [16, 8]; no empty expert |
unpermute forward | 1.417664 (0.003016) | 0.807456 (0.003552) | -43.0% |
| 8192 / 8 / 128 / 16 / 8 | 65,536 x 2,048 | [16, 8]; no empty expert |
unpermute backward | 1.825392 (0.002080) | 0.803680 (0.003472) | -56.0% |
| 16384 / 8 / 128 / 16 / 8 | 131,072 x 2,048 | [16, 8]; no empty expert |
permute forward | 3.095296 (0.009768) | 1.729488 (0.019696) | -44.1% |
| 16384 / 8 / 128 / 16 / 8 | 131,072 x 2,048 | [16, 8]; no empty expert |
permute backward | 3.061376 (0.005256) | 1.524096 (0.004328) | -50.2% |
| 16384 / 8 / 128 / 16 / 8 | 131,072 x 2,048 | [16, 8]; no empty expert |
unpermute forward | 2.828592 (0.002920) | 1.530192 (0.003712) | -45.9% |
| 16384 / 8 / 128 / 16 / 8 | 131,072 x 2,048 | [16, 8]; no empty expert |
unpermute backward | 3.636080 (0.004608) | 1.529424 (0.003624) | -57.9% |
| 2048 / 4 / 32 / 4 / 8 | 8,192 x 1,025 | [4, 8]; local expert 3 empty |
permute forward | 0.231648 (0.014128) | 0.275616 (0.035088) | +19.0% |
| 2048 / 4 / 32 / 4 / 8 | 8,192 x 1,025 | [4, 8]; local expert 3 empty |
permute backward | 0.164880 (0.006184) | 0.104672 (0.008760) | -36.5% |
| 2048 / 4 / 32 / 4 / 8 | 8,192 x 1,025 | [4, 8]; local expert 3 empty |
unpermute forward | 0.066864 (0.001824) | 0.108336 (0.004136) | +62.0% |
| 2048 / 4 / 32 / 4 / 8 | 8,192 x 1,025 | [4, 8]; local expert 3 empty |
unpermute backward | 0.128800 (0.005680) | 0.103584 (0.011824) | -19.6% |
A more trivial but blocking issue is the test.
As pointed out in the copilot's review, the test run pytest --forked tests/unit/v1/moe/test_autoep_permute_rows.py fails because DeepSpeed/CUDA is touched during collection before pytest-forked creates each child.
Converting the tests to DistributedTest with world_size = 1 will fix it.
Once the second issue is resolved, I think it would be okay to merge this PR.
…eepspeedai#8678) ## Summary - Keep `combine_impl="fused_weighted_sum"` opt-in and change only its forward scheduling: one Triton program handles a whole token, walking the hidden dimension in up to 1024-column chunks instead of launching a program per token and 256-column tile. The backward kernel and its row/score gradients are unchanged. - Preserve the existing routing, expert reorder, collectives, grouped GEMM and top-k semantics. The default combine path is unaffected. ## Numerical contract - Each row value and routing score are multiplied in FP32, the top-k products accumulate in FP32 in a fixed slot order, and the output is cast to the row dtype once. FP contraction is disabled so the product rounds before addition. Hidden-tail loads/stores are masked; non-power-of-two top-k requires no padded loads; token and source-row address arithmetic uses int64. - **Not bitwise unchanged versus eager:** eager's top-k reduction may sum FP32 products in a different order. The existing operator and model parity tolerances are unchanged; repeated fused calls are deterministic on fixed inputs. The backward implementation is unchanged. - Measured step-0 loss was 13.237928 → 13.237917 at 8k and 13.276934 → 13.276920 at 16k. These are **step-0 observations, not upper bounds on differences at later training steps**. No long-run convergence claim is made. ## Testing Done - Previously validated on NVIDIA H100: **241 passed**, including fused restore and AutoEP unit coverage. The operator tests compare forward, row gradients and routing-score gradients against the eager weighted sum. Existing separate model parity tests cover gradients through the router and experts; they were not rerun here. The wide-hidden test covers 2048 columns and a 1030-column tail with top-k 6, plus repeated-run determinism. - New focused FP32 cancellation case: **1 passed, 0 skipped** on one NVIDIA H100 80GB HBM3 (torch 2.10, CUDA 13.0, Triton 3.6). It checks that the product is rounded before it is added, including a non-power-of-two top-k and a 1030-column hidden tail. As a negative control, allowing FP contraction makes this same case fail. The negative-control change is not in this PR; existing tolerances were not relaxed. - Changed-files pre-commit checks passed. ## Performance and attribution Within the same NVIDIA H100 allocation, at top-k 8 and hidden 2048, the restore forward fell from about **0.60 → 0.105 ms** per call at 8k tokens, and **1.20 → 0.20 ms** at 16k. The complete AutoEP native-path old/new comparison (two repeats per arm, identical setup apart from this forward change) is the primary E2E evidence: | Sequence | AutoEP before | AutoEP after | Difference | | --- | ---: | ---: | ---: | | 8192 | 2547.53 ms | 2500.44 ms | −47.1 ms (−1.85%) | | 16384 | 5244.91 ms | 5145.86 ms | −99.1 ms (−1.89%) | Peak allocated and reserved memory did not increase. On this allocation, the remaining AutoEP/Megatron step-time gaps were about 0.43%/0.61% at 8k/16k; those numbers are context, **not** evidence that Transformer Engine's unpermute has identical semantics. Its unpermute does not apply the routing weights, so no direct kernel-to-kernel speedup is claimed. This PR's code is independent of deepspeedai#8671 and changes different files. The **reported E2E baseline already includes deepspeedai#8671's gather-based reorder**, so those timings should not be compared with runs that omit it. No new full E2E or convergence run was required for this focused forward review. 🤖 Generated with [GitHub Copilot CLI](https://docs.github.com/copilot/github-copilot-cli) --------- Signed-off-by: yh0903 <helloyu0903@gmail.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…t --forked The collection-time CUDA availability probe, and CUDA state created by DeepSpeed imports, made the plain GPU tests fail in pytest-forked workers. Use the repository's DistributedTest runner with world_size=1 instead, without initializing a process group for these local operator tests. Keep the host test outside the runner, remove the collection-time device availability probe, and preserve all cases and numerical assertions. Signed-off-by: yh0903 <helloyu0903@gmail.com>
Thanks @tohtana for the careful review and benchmarks! |
tohtana
left a comment
There was a problem hiding this comment.
Thank you for the update, looks good to me!

Summary
AutoEP's native collective path (
comm_backend="comm", NCCL all-to-all) puts each rank's received rows into expert-major order before the grouped GEMM, and back afterwards, withpermute_by_local_expertandunpermute_by_local_expert. Theautoep_size=1path uses the same two functions. Both moved every routed row more often than needed:permute_by_local_expert:torch.vstack, a full copy, before indexing the padded expert-major buffer;index_put, i.e. a sort plus atomic adds.unpermute_by_local_expert: zero-filled an[N + 1, H]buffer, then scattered into it with an elementwiseindex_put.On CUDA with Triton, both directions are now gathers:
generate_permute_indicesmarked padding (-1)index_selectthrough the inverse permutationindex_selectthrough the inverse permutationScope.
generate_permute_indicesis unchanged, and the DeepEP backend does not call these functions.Permutation contract
generate_permute_indicessends each received row to exactly one slot of the padded expert-major buffer and marks every other slot-1. The gathers rely on that one-to-one mapping:N + N_paddedentries. Each padding slot goes to its own entry pastN, so no entry is written twice, and every row's entry is written.x[token_indices // top_k], stay in the surrounding code, unchanged.These helpers are therefore not a general gather/scatter.
permute_rows,unpermute_rowsandinverse_permutationrequire the valid entries to be a complete one-to-one permutation of the rows, and do not check it; the docstrings say so.Both callers meet the requirement, because the counts sum to the number of rows:
autoep_size=1, theT × top_krouted rows are sorted by expert, and the counts are per expert.The previous code tolerated counts that sum to fewer rows (the rows left out came back as zeros); the gathers do not. The row gather reads its index by linear offset, so it now makes the index contiguous first, as it already did the source rows.
Numerics
The gathers only move data. Outputs, gradients and double-backward gradients equal the previous implementation's under
torch.equal, which does not distinguish+0.0from-0.0.We also compared bit patterns on H100, in bf16, fp16 and fp32, with inputs and upstream gradients of which a quarter were
-0.0:-0.0. The previous backward accumulated it into a zero-filled buffer, giving+0.0, whereas the gather passes-0.0through.Validation
Unit tests (below): the earlier H100 validation passed these 27 tests and the existing
tests/unit/v1/moe/test_autoep_unit.py(217 tests). The review follow-up additionally validates all 27 reorder cases with plain, forked and xdist-forked execution.Local token movement, one rank's work for one MoE layer, on one H100:
At T=8192, per grad forward, the permute goes from 0.44 to 0.27 ms and the unpermute from 0.71 to 0.21 ms.
End to end, Qwen3-30B-A3B training with AutoEP:
comm_backend="comm"withcombine_impl="fused_weighted_sum"andasync_split_plan=true.These numbers come from one model, two sequence lengths, one GPU type and one parallel layout. The saving scales with the rows each rank reorders, so its share of the step depends on the configuration.
Small shapes are not guaranteed to improve in every direction: a review microbenchmark on RTX PRO 4500 found slower forwards at 8,192 rows × hidden 1,025, while both backwards improved. This PR does not add a shape-dependent dispatch heuristic.
The local and end-to-end numbers were measured with this PR's first commit. The later commits add
index.contiguous(), a no-op for the contiguous indices both callers pass, and change docstrings and tests. The forked-runner review follow-up changes only test execution, not the runtime implementation.Tests
tests/unit/v1/moe/test_autoep_permute_rows.py, 27 tests: 26 need CUDA and Triton, and 1 runs on the host. All compare against the previous zero-row-and-index implementation withtorch.equal:[ep, E_local]counts with and without empty experts, and aggregated[E_local]counts;Results:
tests/unit/v1/moe/test_autoep_unit.py.pytest --forkedandpytest -n 4 --forkedeach pass all 27 cases, with no skips and no bad-fork errors. In the same environment, the previous tests fail under--forked(26 failed, 1 host case passed), reproducing the reported issue.--forkedand-n 4 --forkedeach give 1 passed, 26 skipped.pre-commit run --fileson the changed files: passed.CI
cpu-torch-latestruns the host test and skips the rest.tests/unit/v1, in the scope of both AWS and Modal GPU CI; Modal executes the selected GPU tests when the PR enters the merge queue.aws-torch-latestusespytest -n 4 --forked. The GPU cases now useDistributedTestwithworld_size=1, launching clean workers even when CUDA was touched while importing DeepSpeed during collection. These local operator tests do not need a process group (init_distributed=False). CUDA availability is checked by the runner during test execution, not by this file's collection-time skip condition. The host case remains an ordinary test, and all 27 cases and their numerical assertions are unchanged.Not covered
cuda, so the gathers would be used there, as the existing Triton index generation is. Neither was tested on ROCm here.torch.compileof the MoE layer itself. AutoEP's regional compilation keeps that layer eager, and the path already launched Triton kernels there.