Skip to content

AutoEP: reorder expert rows with gathers on the collective path - #8671

Merged
tohtana merged 5 commits into
deepspeedai:masterfrom
yh0903:yh0903/autoep-gather-permute
Oct 2, 2026
Merged

tohtana merged 5 commits into
deepspeedai:masterfrom
yh0903:yh0903/autoep-gather-permute

Conversation

@yh0903

@yh0903 yh0903 commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

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, with permute_by_local_expert and unpermute_by_local_expert. The autoep_size=1 path uses the same two functions. Both moved every routed row more often than needed:

  • permute_by_local_expert:
    • appended a zero row to the received rows with torch.vstack, a full copy, before indexing the padded expert-major buffer;
    • its backward was an accumulating 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 elementwise index_put.

On CUDA with Triton, both directions are now gathers:

Direction Forward Backward
permute a Triton row gather that writes zero rows where generate_permute_indices marked padding (-1) index_select through the inverse permutation
unpermute index_select through the inverse permutation the same padded row gather

Scope.

  • This is a local, on-rank change to the expert reorder.
  • The all-to-alls send and receive the same rows in the same order, so communication volume is unchanged, and no communication/computation overlap is added.
  • generate_permute_indices is unchanged, and the DeepEP backend does not call these functions.
  • There is no switch: the gathers replace the previous code for 2-D CUDA tensors when Triton is available, because their results are equal to it (see Numerics). Other tensors keep the previous code.

Permutation contract

generate_permute_indices sends 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:

  • Permute forward: writes each output row once: the row mapped to its slot, or zeros at a padding slot.
  • Inverse permutation: a scatter of slot positions into scratch of N + N_padded entries. Each padding slot goes to its own entry past N, so no entry is written twice, and every row's entry is written.
  • Unpermute forward: reads each row's slot through the inverse; padding rows are never read.
  • Backward: each direction's backward is the other gather. A row's gradient is that of the one slot it occupied, not a sum, and padding slots get zero gradient. Both backwards are autograd functions themselves, so double backward goes through the same pair.
  • Top-k: each received row is one (token, expert) assignment. Summing a token's top-k expert outputs, in the combine, and accumulating its top-k gradients, in the backward of the routed gather x[token_indices // top_k], stay in the surrounding code, unchanged.

These helpers are therefore not a general gather/scatter. permute_rows, unpermute_rows and inverse_permutation require 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:

  • with expert parallelism, each all-to-all receives exactly the row sums of the exchanged counts;
  • with autoep_size=1, the T × top_k routed 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.0 from -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:

  • Both outputs and the unpermute gradient are bitwise identical to the previous implementation's.
  • The permute gradient differs only where the upstream gradient is -0.0. The previous backward accumulated it into a zero-filled buffer, giving +0.0, whereas the gather passes -0.0 through.

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:

  • Shape: T tokens, top-8 of 128 experts, EP16 (8 local experts), hidden 2048.
  • The all-to-alls are replaced by the identity and the experts by a scalar multiply, so only the local work is timed.
  • Each iteration runs a no-grad forward, a grad forward and a backward, as under reentrant activation checkpointing.
  • The whole local chain is timed; only the reorder differs between the two columns.
T Before After Saving × 48 layers
8192 7.04 ms 5.12 ms −92 ms
16384 13.53 ms 9.58 ms −190 ms

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:

Sequence Before After Change
8192 2649.4 ms 2554.3 ms −95.2 ms (−3.6%)
16384 5434.6 ms 5244.5 ms −190.2 ms (−3.5%)
  • Each arm's two runs agree within 5 ms.
  • The end-to-end saving matches the local estimate scaled to 48 layers (−92 and −190 ms).
  • Peak memory and the step-0 loss are identical in both arms.

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 with torch.equal:

  • forward and backward of both reorders:
    • bf16 and fp32;
    • hidden 2048, 100 and 1;
    • source-major [ep, E_local] counts with and without empty experts, and aggregated [E_local] counts;
  • fp16 and bf16 rows read through a column-strided view, with column-major upstream gradients, in both directions, including the output strides;
  • double backward of both reorders;
  • a round trip with zero padding;
  • zero tokens;
  • the row gather with both padding encodings, through a contiguous and a strided index;
  • host tensors keeping the previous code.

Results:

  • 1× NVIDIA H100 80GB HBM3, Python 3.12, torch 2.10 (CUDA 13.0), Triton 3.6.0: 27 passed, and 217 together with tests/unit/v1/moe/test_autoep_unit.py.
  • The same 27 tests against this PR's first commit, the code the timings used: 26 passed. The strided-index case failed, because that commit read the index as if contiguous.
  • CPU, torch 2.14: 1 passed, 26 skipped.
  • Forked-runner review regression on H100, torch 2.10 (CUDA 13.0), Triton 3.6.0: plain pytest, pytest --forked and pytest -n 4 --forked each 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.
  • CPU review regression, torch 2.14: --forked and -n 4 --forked each give 1 passed, 26 skipped.
  • pre-commit run --files on the changed files: passed.

CI

  • cpu-torch-latest runs the host test and skips the rest.
  • The test file is under 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-latest uses pytest -n 4 --forked. The GPU cases now use DistributedTest with world_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

  • ROCm: PyTorch reports ROCm devices as cuda, so the gathers would be used there, as the existing Triton index generation is. Neither was tested on ROCm here.
  • Inputs that break the permutation contract. It is not checked; both callers meet it by construction.
  • torch.compile of the MoE layer itself. AutoEP's regional compilation keeps that layer eager, and the path already launched Triton kernels there.
  • Models, sequence lengths, hardware and parallel layouts other than the ones above.

…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>
@yh0903
yh0903 force-pushed the yh0903/autoep-gather-permute branch from 640c947 to fcdf521 Compare September 27, 2026 02:45
@yh0903
yh0903 marked this pull request as ready for review September 27, 2026 02:46
@hwchen2017
hwchen2017 requested a balanced review from Copilot September 29, 2026 03:32

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.

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 High severity

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")

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

yermakoffivan pushed a commit to yermakoffivan/deepspeed that referenced this pull request Sep 29, 2026
…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>
pengdurice and others added 2 commits September 29, 2026 11:28
…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>
@yh0903

yh0903 commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

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.

Thanks @tohtana for the careful review and benchmarks!
Fixed the blocking test issue in latest commit , following your suggestion: the GPU cases now use DistributedTest with world_size=1, and the collection-time CUDA availability probe is removed. All existing cases and assertions are preserved; the runtime implementation is unchanged.
On H100, plain pytest,  pytest --forked , and  pytest -n 4 --forked  each pass all 27 cases with no skips or bad-fork errors. The previous tests reproduce the reported failure in the same environment.
I've also noted the small-shape forward regression in the description. I'll leave shape-specific tuning out of this PR to keep the change focused. Please take another look when you have a chance.

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

Thank you for the update, looks good to me!

@tohtana
tohtana enabled auto-merge October 1, 2026 22:07
@tohtana
tohtana added this pull request to the merge queue Oct 1, 2026
Merged via the queue into deepspeedai:master with commit bfd2917 Oct 2, 2026
13 checks passed
@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
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