Skip to content

AutoEP: MiniMax-M3 preset - #8651

Merged
pengdurice merged 1 commit into
deepspeedai:masterfrom
pengdurice:peng-add-minimax-m3-preset-v1
Oct 1, 2026
Merged

pengdurice merged 1 commit into
deepspeedai:masterfrom
pengdurice:peng-add-minimax-m3-preset-v1

Conversation

@pengdurice

@pengdurice pengdurice commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

AutoEP: MiniMax-M3 preset

What

A built-in preset minimax_m3 for MiniMax-M3 (model_type = "minimax_m3_vl_text", transformers >= 5.15.0).
MiniMax-M3 is 425.9 B parameters, 25.7 B active: 60 layers, the first 3 dense, the other 57 with 128
experts, top-4, and one shared expert. With the preset, expert_parallel: {"enabled": true, "autoep_size": N}
is the whole configuration; nothing has to be spelled out.

preset field value where it comes from
MoE block, router, experts, shared expert model.layers.N.mlp, gate, experts, shared_experts MiniMaxM3VLSparseMoeBlock
expert weights fused 3-D gate_up_proj / down_proj MiniMaxM3VLExperts
expert and top-k counts num_local_experts / num_experts_per_tok on the model config MiniMaxM3VLTextConfig (128 / 4)
scoring sigmoid, applied after the experts, selected top-k weights normalised MiniMaxM3VLTopKRouter
selection bias gate.e_score_correction_bias (a buffer, as in DeepSeek-V3) found by the existing bias-path resolution
routed output scale routed_scaling_factor = 2.0 read from the model config by the existing code
expert activation swiglu_oai, alpha 1.702, limit 7.0 preset; the model's swiglu_alpha / swiglu_limit override it at detection
router logits recorded at the model level as OutputRecorder(MiniMaxM3VLTopKRouter, index=0), the raw logits same pattern as Mixtral, so the adapter is a TransformersTopLevelRouterLogitsAdapter
version gate transformers >= 5.15.0, checked when the model type is MiniMax's adapter opts in
composite minimax_m3_vl (vision + text) refused with a note to pass the text backbone unsupported_hf_model_type_notes
load_balance_coeff defaults to None; a non-null value is rejected, as for DeepSeek-V3 autoep_config_defaults, supports_expert_bias=False

Trained at scale: the full MiniMax-M3 on 65,536-token books, 4 nodes of 8 H200

This preset is the configuration under which the real MiniMax-M3 checkpoint fine-tuned on real
65,536-token sequences. The run used the preset before it was committed; the preset fields, the
swiglu_oai form with alpha 1.702 / limit 7.0, and the config keys are the ones in this PR.

Setup: 4 nodes of 8 H200 (32 ranks), all 60 layers, the real checkpoint (795.5 GiB in 59 safetensors
shards, streamed in one tensor at a time in 791 s), 426.2B parameters of which 413.1B are expert weights.
expert_parallel: {"enabled": true, "autoep_size": 4}: 8 expert groups of 4 ranks, each rank holding 32
experts that ZeRO-3 shards 8 ways across the expert-data-parallel group. fused_weighted_sum combine,
ZeRO-3 with the optimizer state offloaded to host memory, activation checkpointing with the checkpoint
inputs on host, tiled loss (64 shards over the 200,064-token vocabulary), micro-batch 1 per rank = one
whole PG-19 book of 65,536 tokens per rank, learning rate 1e-6, 1 warm-up + 2 measured steps. torch
2.8.0+cu126, transformers 5.15.1. Attention ran through a harness-side gather over each query's selected
keys, because the stock transformers path materialises a [1, 64, S, S] block mask and stops at 14,336
tokens on a 141 GB card; that module is outside this PR.

step loss (rank 0's book) grad norm step time rank 0 peak allocated
1 (warm-up) 0.0153 (the King James Bible) 0.98 361.0 s 89.1 GiB
2 0.8592 1.18 296.1 s 90.6 GiB
3 1.0754 1.23 292.3 s 90.6 GiB

Measured average 294.22 s per step = 7,128 tokens/s over the 32 ranks. Memory: rank 0 peak 90.57 GiB
allocated / 109.78 GiB reserved; the highest rank 102.07 GiB allocated / 126.24 GiB reserved of 139.80.
Host memory 1.87 TB per node, most of it the offloaded optimizer state.

The losses are a trained model's losses on real text (0.015 on a text every corpus contains, 0.86 and
1.08 on two other pre-1919 books), against 13.44 with random weights on the same setup. That is the
end-to-end check of everything the preset describes: the conversion of the checkpoint's per-expert
w1/w3/w2 into AutoEP's fused expert layout, the sigmoid router with the fp32 selection bias,
routed_scaling_factor 2.0, the shared expert, and the clamped activation. With standard SwiGLU in
place of swiglu_oai the replaced block differs from the model's own by 0.41 mean absolute (correlation
0.74), so the activation form is what makes this loss a real loss.

Why expert parallel 4 and not 32: real router weights route far more unevenly than random ones. Over all
57 MoE layers of this run, the busiest of the 4 ranks in an expert group received 1.09 to 2.22 times the
mean number of rows (median 1.36; the worst is layer 54, 581,906 rows on one rank against 262,144 own
rows). The same counts grouped as expert parallel 32 give a median of 4.20 and a maximum of 7.84 times
the mean, and at that skew the busiest rank runs out of memory at this length:, same setup with
expert parallel 32, failed in the step-1 forward on one rank with a single 11.96 GiB temporary for
1,045,081 routed rows inside the expert activation, 129.50 GiB already in use. AutoEP has no capacity
limit, so the busiest rank sets the memory ceiling; a smaller expert group spreads each expert set over
more ranks, at the cost of a per-layer all-gather of the local experts (32 experts x 113 MB at expert
parallel 4).

Why a preset

Without it, MiniMax-M3 runs through the custom moe_layer_pattern path with six keys (score_func,
score_apply, route_norm, has_shared_experts, shared_experts_pattern, expert_activation), and a
user who omits expert_activation is stopped by the registry PR's check rather than silently trained on
silu(gate) * up. The preset makes the model type enough, records the facts above in one place, and
switches on the version gate for it. The run above is this configuration.

Files

file change
deepspeed/module_inject/auto_ep_presets/minimax_m3.py new: the preset and MiniMaxM3PresetAdapter
deepspeed/module_inject/auto_ep_presets/registry.py registers the module
docs/_pages/config-json.md, docs/code-docs/source/autoep.rst minimax_m3 in the preset list and the version table
tests/unit/v1/moe/autoep_test_utils.py tiny_minimax_m3_config
tests/unit/v1/moe/test_autoep_unit.py registry contract extended; test_hf_minimax_m3_causal_lm_matches_autoep_with_router_logits; test_minimax_m3_adapter_guards
tests/unit/v1/moe/test_autoep_expert_activation.py the block-parity test now runs through the preset as well as the custom pattern; "every preset is swiglu" becomes "every preset names its form"

Tests

test what it checks, and the wrong behaviour it would catch
test_preset_registry_core_contracts minimax_m3 registered; minimax_m3_vl_text resolves to it; the composite minimax_m3_vl carries a note naming the text backbone
test_minimax_m3_adapter_guards a mock model of type minimax_m3_vl_text is detected as minimax_m3 with swiglu_oai; an installed transformers below 5.15.0 is refused with the version named (the gate is switched on for this preset; an unregistered adapter would silently skip it); the composite type is refused with the note
test_hf_minimax_m3_causal_lm_matches_autoep_with_router_logits a tiny MiniMaxM3VLForCausalLM (1 layer, 4 experts, top-2), state-matched, native against AutoEP: loss, the recorded router logits, and the auxiliary load-balancing loss agree at rtol 1e-5 (the recorder retarget and the raw-logit capture mode are what make the last two agree)
TestMiniMaxM3Block.test_replaced_block_matches_hf_block[preset-*] a real MiniMaxM3VLSparseMoeBlock found from the model type alone, no config keys: family minimax_m3, activation swiglu_oai with 1.702 / 7.0 from the model, and the replaced block matches a deep copy of the original, forward and input gradient, at weight std 0.02 and 0.5
TestMiniMaxM3Block.*[custom_pattern-*], test_custom_pattern_without_the_key_is_refused the custom-pattern route from the registry PR, kept for a model type AutoEP does not know yet

Results, all on this branch:

where environment test_autoep_expert_activation.py test_autoep_unit.py test_autoep_grad_parity.py
CPU, one process torch 2.9.1, transformers 5.15.0 29 passed, 8 skipped (accelerator cases) 186 passed, 6 skipped not run (needs 4 devices)
H200 node, 4 GPUs torch 2.9.1+cu128, transformers 5.15.0, Triton 3.5.1 37 passed 192 passed 23 passed, 8 skipped (the regional-compile parity cases need DEEPSPEED_RUN_H100_TESTS=1), 2 min 44 s

pre-commit run --files on the changed files: yapf, flake8, codespell, check-torchdist, check-torchcuda
pass; check-license reports the new preset file only because the hook uses git grep, which skips
untracked files.

Signed-off-by: pengdurice <pengduhit@gmail.com>
@pengdurice
pengdurice force-pushed the peng-add-minimax-m3-preset-v1 branch from 54963c2 to 8390a16 Compare September 29, 2026 16:09
@pengdurice
pengdurice marked this pull request as ready for review September 29, 2026 16:14
@hwchen2017
hwchen2017 requested a balanced review from Copilot September 29, 2026 16:22

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

🟢 Approval recommended

The preset matches the Transformers model contract and includes comprehensive focused coverage.

Review effort: Balanced
Findings: None

What changed in this PR

Adds a built-in AutoEP preset for MiniMax-M3, covering its routing, expert layout, shared expert, and clamped activation.

Changes:

  • Registers the minimax_m3 preset and Transformers adapter.
  • Adds parity, router-logit, registry, and compatibility tests.
  • Documents preset requirements and Transformers support.
File Description
deepspeed/​module_inject/​auto_ep_presets/​minimax_m3.py Defines the MiniMax-M3 preset and adapter.
deepspeed/​module_inject/​auto_ep_presets/​registry.py Registers the new preset.
docs/​_pages/​config-json.md Documents configuration support.
docs/​code-docs/​source/​autoep.rst Adds API documentation and version requirements.
tests/​unit/​v1/​moe/​autoep_test_utils.py Adds a compact MiniMax-M3 configuration.
tests/​unit/​v1/​moe/​test_autoep_unit.py Tests detection, guards, and model-level parity.
tests/​unit/​v1/​moe/​test_autoep_expert_activation.py Tests preset activation and block parity.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@pengdurice
pengdurice added this pull request to the merge queue Oct 1, 2026
Merged via the queue into deepspeedai:master with commit b9ce5f4 Oct 1, 2026
17 of 19 checks passed
@pengdurice
pengdurice deleted the peng-add-minimax-m3-preset-v1 branch October 1, 2026 22:46
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 <pengduhit@gmail.com>
@auto-pr-labeler-with-jev auto-pr-labeler-with-jev Bot added the skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. label Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants