Skip to content

AutoEP: Add activation registry - #8650

Merged
tohtana merged 1 commit into
deepspeedai:masterfrom
pengdurice:peng-add-activation-registry-moe-v1
Sep 27, 2026
Merged

tohtana merged 1 commit into
deepspeedai:masterfrom
pengdurice:peng-add-activation-registry-moe-v1

Conversation

@pengdurice

Copy link
Copy Markdown
Contributor

AutoEP: a registry of expert activations, checked against the model at detection time

Problem

GroupedExperts computes silu(gate) * up in all three of its paths, and nothing in AutoEP checks
which 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):

expert MLP form families examples
silu(gate) * up 42 Mixtral, Qwen2/3/3.5-MoE, DeepSeek-V2/V3/V3.2, GLM-4 MoE, GLM-DSA, Kimi-style inkling, Granite, OLMoE, Jamba, Mistral-4, ...
gelu_tanh(gate) * up 2 Gemma-4, Diffusion-Gemma
silu(clamp(gate)) * clamp(up), limit 10 1 DeepSeek-V4
(clamp(up) + 1) * clamp(gate) * sigmoid(1.702 * clamp(gate)), limit 7 3 GPT-OSS, MiniMax-M3, OpenAI privacy filter
relu(up)^2, no gate projection 1 Nemotron-H (different weight layout; out of scope here)
not resolved from the config defaults 1 LFM2-MoE

hidden_act cannot be used to tell them apart: the configs of DeepSeek-V4, GPT-OSS and MiniMax-M3
all say silu. Each of the non-default families is replaced by AutoEP today with no error and no
warning, through the custom moe_layer_pattern path, and the replaced layer then computes a different
function. Measured on CPU with one real block against a deep copy of itself (master 4e394422a,
hidden 64, 8 experts, top-2):

block how it was given to AutoEP weight std relative error of the AutoEP layer
MiniMaxM3VLSparseMoeBlock custom moe_layer_pattern (its names are the custom defaults) 0.02 0.8057
same same 0.5 0.2929
GptOssMLP custom pattern + router_pattern="router" 0.02 1.0084 (activation, plus dropped biases and the interleaved layout)

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 registry

  • ExpertActivation: fn(gate, up, alpha, limit) in plain PyTorch, an optional fused_fn with the
    same signature, uses_alpha / uses_limit, and gate_fn, the elementwise function the form
    applies to gate when it is gate_fn(gate) * up (used by the check below; None for swiglu_oai,
    which is not such a product).
  • EXPERT_ACTIVATIONS: swiglu (with the existing fused Triton kernel as fused_fn), geglu_tanh,
    swiglu_clamped, swiglu_oai. register_expert_activation(name, fn, ...) adds a form; a
    duplicate name is an error.
  • apply_expert_activation(gate, up, activation, alpha, limit, fused). The three expert paths take
    activation, alpha, limit and call it; the for-loop path passes fused=False, so it stays in plain
    PyTorch and on CPU exactly as before. GroupedExperts.__init__ takes the three values and rejects an
    unknown name at construction.
  • Default "swiglu": no behaviour change for any existing preset.

auto_ep_presets/base.py, auto_ep_config.py, auto_ep_presets/registry.py: the name travels
with the preset

  • MoEModelPreset and MoELayerSpec gain expert_activation, expert_activation_alpha,
    expert_activation_limit. AutoEPConfig gains expert_activation: str | None (None = the
    preset's). The expert_parallel.expert_activation key 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_activation runs once per detected layer:

  1. _detect_clamped_swiglu looks for a clamp limit: swiglu_limit / swiglu_alpha on the experts
    module, the model config or its text config (MiniMax-M3, GPT-OSS), or a numeric limit / alpha
    on 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.
  2. _gate_activation_matches evaluates the experts' act_fn, when there is one, on a probe vector and
    compares it numerically with the gate_fn of every registered form. An act_fn that does not
    match the named form is an error (Gemma-4's gelu_pytorch_tanh under a swiglu preset; an
    activation nobody registered).
  3. Setting expert_activation in 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 to GroupedExperts.

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 as test_autoep_unit.py.
35 cases; 27 run on CPU in one process, 8 need an accelerator.

group what it checks, and the wrong behaviour it would catch
TestApplyExpertActivation hand-computed values for the three non-default forms (clamp hits gate from above only and up on both sides; alpha and limit honoured); every pair of forms differs; equality with MiniMaxM3VLExperts._apply_gate, DeepseekV4Experts._apply_gate and transformers' _default_apply_gate with silu and gelu_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 refused
TestGroupedExpertsActivation for-loop path against a dense per-expert reference, forward and input gradient, every registered form, with an expert that has zero tokens; accelerator: the torch._grouped_mm and 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 kernel
TestPresetAndConfig every built-in preset is swiglu; the config key reaches a custom preset and overrides a built-in one without changing the registered preset
TestExpertActivationDetection a plain model is unchanged; a clamp limit on the experts (swiglu_limit, or limit + alpha) or on the config is refused under a plain preset; explicit swiglu is kept; alpha and limit come from the model; the DeepSeek-V4 shape (limit, no alpha) is refused with swiglu_clamped named, and accepted with it set; gelu_tanh experts are refused under a plain preset and accepted with geglu_tanh; silu experts pass; an act_fn matching no registered form is refused unless the user chooses
TestMiniMaxM3ThroughCustomPattern a real MiniMaxM3VLSparseMoeBlock given through the custom pattern, as a user does before a preset exists: without the key it is refused; with expert_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_contracts in test_autoep_unit.py is unchanged: this PR adds no preset.

Results, all measured on this branch:

where environment test_autoep_expert_activation.py test_autoep_unit.py test_autoep_grad_parity.py ops/triton_ops/test_swiglu_triton.py
login node, CPU, one process torch 2.9.1, transformers 5.15.0 27 passed, 8 skipped (accelerator cases) 184 passed, 6 skipped not run (needs 4 devices) not run
H200 node, Slurm jobs 34594 (4 GPUs) and 34598 (1 GPU) torch 2.9.1+cu128, transformers 5.15.0, Triton 3.5.1 35 passed (job 34598) 190 passed (job 34594) 23 passed, 8 skipped (the regional-compile parity cases need DEEPSPEED_RUN_H100_TESTS=1), 2 min 41 s (job 34594) 37 passed (job 34594; kernel unchanged, it is the swiglu fused path)

The accelerator test went through two tolerance fixes on the way: out.sum().backward() hands
torch._grouped_mm an expanded all-ones gradient with zero strides, which it refuses (real training
never 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) * up on 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 --files on the changed files: yapf, flake8, codespell, check-torchdist, check-torchcuda
pass. check-license reports the new test file only because the hook uses git grep, which skips
untracked files; the header is the same as test_autoep_unit.py's.

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

This is a very critical fix, thank you @pengdurice!

@tohtana
tohtana added this pull request to the merge queue Sep 27, 2026
Merged via the queue into deepspeedai:master with commit c193f22 Sep 27, 2026
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]>
@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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants