Repository navigation
AutoEP: Add activation registry - #8650
Merged
tohtana merged 1 commit intoSep 27, 2026
Merged
Conversation
Signed-off-by: pengdurice <[email protected]>
pengdurice
requested review from
hwchen2017,
loadams,
tjruwase and
tohtana
as code owners
September 24, 2026 03:02
tohtana
approved these changes
Sep 27, 2026
tohtana
left a comment
Collaborator
There was a problem hiding this comment.
This is a very critical fix, thank you @pengdurice!
Merged
via the queue into
deepspeedai:master
with commit Sep 27, 2026
c193f22
13 of 15 checks passed
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 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
AutoEP: a registry of expert activations, checked against the model at detection time
Problem
GroupedExpertscomputessilu(gate) * upin all three of its paths, and nothing in AutoEP checkswhich form the source model uses. That was true for every model family with a built-in preset, and
it is not true in general. A scan of the 51 experts classes in transformers 5.15.1 (50 model families;
regex over the modeling files, then each non-default row verified by hand in the source):
silu(gate) * upinkling, Granite, OLMoE, Jamba, Mistral-4, ...gelu_tanh(gate) * upsilu(clamp(gate)) * clamp(up), limit 10(clamp(up) + 1) * clamp(gate) * sigmoid(1.702 * clamp(gate)), limit 7relu(up)^2, no gate projectionhidden_actcannot be used to tell them apart: the configs of DeepSeek-V4, GPT-OSS and MiniMax-M3all say
silu. Each of the non-default families is replaced by AutoEP today with no error and nowarning, through the custom
moe_layer_patternpath, and the replaced layer then computes a differentfunction. Measured on CPU with one real block against a deep copy of itself (
master4e394422a,hidden 64, 8 experts, top-2):
MiniMaxM3VLSparseMoeBlockmoe_layer_pattern(its names are the custom defaults)GptOssMLProuter_pattern="router"MiniMax-M3 is one model. DeepSeek-V4 is the reason to make the form a first-class, extensible part of
AutoEP rather than a special case, and the next family will bring its own form.
The change
deepspeed/moe/ep_experts.py: the registryExpertActivation:fn(gate, up, alpha, limit)in plain PyTorch, an optionalfused_fnwith thesame signature,
uses_alpha/uses_limit, andgate_fn, the elementwise function the formapplies to
gatewhen it isgate_fn(gate) * up(used by the check below;Noneforswiglu_oai,which is not such a product).
EXPERT_ACTIVATIONS:swiglu(with the existing fused Triton kernel asfused_fn),geglu_tanh,swiglu_clamped,swiglu_oai.register_expert_activation(name, fn, ...)adds a form; aduplicate name is an error.
apply_expert_activation(gate, up, activation, alpha, limit, fused). The three expert paths takeactivation, alpha, limitand call it; the for-loop path passesfused=False, so it stays in plainPyTorch and on CPU exactly as before.
GroupedExperts.__init__takes the three values and rejects anunknown name at construction.
"swiglu": no behaviour change for any existing preset.auto_ep_presets/base.py,auto_ep_config.py,auto_ep_presets/registry.py: the name travelswith the preset
MoEModelPresetandMoELayerSpecgainexpert_activation,expert_activation_alpha,expert_activation_limit.AutoEPConfiggainsexpert_activation: str | None(None = thepreset's). The
expert_parallel.expert_activationkey is parsed, validated against the registry,counted as a custom field, applied by
apply_config_overrides, and used by_build_custom_preset.auto_ep.py: the preset names the form, the model is checked against it_resolve_expert_activationruns once per detected layer:_detect_clamped_swiglulooks for a clamp limit:swiglu_limit/swiglu_alphaon the expertsmodule, the model config or its text config (MiniMax-M3, GPT-OSS), or a numeric
limit/alphaon the experts module (DeepSeek-V4, GPT-OSS). A limit with a form that does not clamp is an error.
For a clamping form, the model's limit and alpha replace the preset's.
_gate_activation_matchesevaluates the experts'act_fn, when there is one, on a probe vector andcompares it numerically with the
gate_fnof every registered form. Anact_fnthat does notmatch the named form is an error (Gemma-4's
gelu_pytorch_tanhunder aswiglupreset; anactivation nobody registered).
expert_activationin the config is taken as a decision and switches both checks off.The errors name the registered forms and the model families that use them. Nothing is guessed from
the model: the name comes from the preset or the user, the model can only contradict it.
auto_ep_layer.py: passes the three spec fields toGroupedExperts.docs/_pages/config-json.md: the new key, next to the other custom-preset keys.Tests
New file
tests/unit/v1/moe/test_autoep_expert_activation.py, same style astest_autoep_unit.py.35 cases; 27 run on CPU in one process, 8 need an accelerator.
TestApplyExpertActivationgatefrom above only andupon both sides;alphaandlimithonoured); every pair of forms differs; equality withMiniMaxM3VLExperts._apply_gate,DeepseekV4Experts._apply_gateand transformers'_default_apply_gatewithsiluandgelu_pytorch_tanh; unknown names rejected in the call, the layer and the config; a form registered at runtime is usable in the call, the layer, config validation and a custom preset, and a duplicate name is refusedTestGroupedExpertsActivationtorch._grouped_mmand Triton grouped-GEMM paths (packed rows, fused kernel) match the for-loop path in output, input gradient and the three weight gradients, every form; the for-loop path never reaches the Triton kernelTestPresetAndConfigswiglu; the config key reaches a custom preset and overrides a built-in one without changing the registered presetTestExpertActivationDetectionswiglu_limit, orlimit+alpha) or on the config is refused under a plain preset; explicitswigluis kept;alphaandlimitcome from the model; the DeepSeek-V4 shape (limit, no alpha) is refused withswiglu_clampednamed, and accepted with it set;gelu_tanhexperts are refused under a plain preset and accepted withgeglu_tanh;siluexperts pass; anact_fnmatching no registered form is refused unless the user choosesTestMiniMaxM3ThroughCustomPatternMiniMaxM3VLSparseMoeBlockgiven through the custom pattern, as a user does before a preset exists: without the key it is refused; withexpert_activation="swiglu_oai"the replaced block matches a deep copy of the original, forward and input gradient, at weight std 0.02 and 0.5 (0.5 drives pre-activations past the clamp)test_preset_registry_core_contractsintest_autoep_unit.pyis unchanged: this PR adds no preset.Results, all measured on this branch:
test_autoep_expert_activation.pytest_autoep_unit.pytest_autoep_grad_parity.pyops/triton_ops/test_swiglu_triton.pyDEEPSPEED_RUN_H100_TESTS=1), 2 min 41 s (job 34594)swiglufused path)The accelerator test went through two tolerance fixes on the way:
out.sum().backward()handstorch._grouped_mman expanded all-ones gradient with zero strides, which it refuses (real trainingnever does that; the test now uses a random dense upstream gradient), and an elementwise absolute
tolerance is wrong for bf16 sums, because the fused kernel rounds once after fp32 math and the eager
ops round per op, and a matmul then sums those rounded values. A direct probe of the fused kernel
against eager
silu(gate) * upon the H200 (8 shapes from (5, 7) to (1024, 4096), bf16 and fp32,forward and both gradients) stays within one bf16 ulp and is exact in fp32; the test's absolute
tolerance is now set from the compared tensor's largest magnitude.
pre-commit run --fileson the changed files: yapf, flake8, codespell, check-torchdist, check-torchcudapass.
check-licensereports the new test file only because the hook usesgit grep, which skipsuntracked files; the header is the same as
test_autoep_unit.py's.