Repository navigation
AutoEP: fused Triton kernel for the clamped expert activations - #8652
Conversation
f0db347 to
90c9660
Compare
Signed-off-by: pengdurice <pengduhit@gmail.com>
90c9660 to
b5febe5
Compare
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b5febe562a
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| g = tl.minimum(gate, limit) | ||
| u = tl.minimum(tl.maximum(up, -limit), limit) |
There was a problem hiding this comment.
Preserve NaNs through the clamp
When a preceding grouped GEMM yields a NaN in gate or up, Triton's elementwise minimum/maximum use their default non-NaN-propagating mode, unlike the eager torch.clamp reference, so these lines replace the NaN with a finite clamp bound. The backward kernel repeats that clamp and its comparisons then zero the corresponding gradient, allowing a diverged AutoEP step to produce finite outputs and gradients; request NaN propagation (or use comparisons that preserve NaNs) in both kernels.
Useful? React with 👍 / 👎.
| n_elements = gate.numel() | ||
| if n_elements > 0: | ||
| grid = (triton.cdiv(n_elements, _BLOCK_SIZE), ) | ||
| _swiglu_clamped_fwd_kernel[grid](gate, |
There was a problem hiding this comment.
Guard separate launches with the input device
When gate and up reside on a CUDA device that is not the process's current device (for example, tensors on cuda:1 while the caller remains on cuda:0), this launch and the analogous backward launch run on Triton's current device/stream rather than the tensor device, so the kernel sees inaccessible pointers or launches on the wrong stream. The packed implementation already enters an input-device context around both launches; the separate implementation needs the same protection.
AGENTS.md reference: AGENTS.md:L40-L40
Useful? React with 👍 / 👎.
| return out | ||
|
|
||
| @staticmethod | ||
| def backward(ctx, grad_out: torch.Tensor): |
There was a problem hiding this comment.
Reject higher-order gradients in the separate path
When a caller requests create_graph=True from the separate swiglu_clamped path, this backward writes gradients into fresh empty_like buffers via Triton, so the returned first derivatives are detached and a subsequent derivative fails. The packed class explicitly detects and rejects this unsupported mode, but this new separate class neither rejects it nor provides a differentiable fallback; add the same guard or a differentiable backward here.
Useful? React with 👍 / 👎.
…ed buffer (deepspeedai#8840) # ZeRO-3: pin the offloaded master weights and cast them on the device when copying them back **Part of:** deepspeedai#8672 (Q4 2026 roadmap), "Enable training of large scale models". ## Summary With `offload_optimizer.device: cpu`, ZeRO-3 copies each sub-group's updated float32 master partition back to the device as bf16 after every step. - `pin_memory: true` (the default since deepspeedai#8207) pins the float32 gradient partitions. It does not pin the master partitions, so this copy reads pageable host memory. - The copy is also a cast. A blocking `copy_` from float32 into bf16 casts on the CPU into a new pageable tensor and copies from that at a few GB/s. This PR follows ZeRO-1/2 and deepspeedai#5301: - with `pin_memory: true`, each CPU master partition is pinned when it is created, as ZeRO-1/2 does; - the copy-back moves the pinned float32 master to the device and casts it there, in pieces of 2**26 elements, so the device temporary is one piece (0.25 GiB) instead of a whole sub-group. Results: - Qwen2.5-32B, 8 H200, whole optimizer on the CPU: 12.08 s to 9.42 s per step (-22.0%), same peak device memory, same losses (the new unit test compares the parameters bitwise). - Host memory: the master partitions are already in host memory and become pinned. PyTorch's pinned allocator rounds each allocation up to a power of two: a 1e9-element sub-group (3.73 GiB in float32) reserves 4.00 GiB. ## Duplicate check Searched issues and PRs on 2026-10-13 ("offload pinned fp32 partition", "zero3 offload pin_memory copy", "fp32_partitioned_groups_flat", "offload ratio pinned", "pageable offload"). Related, not duplicates: deepspeedai#8207 (merged: pinned the ZeRO-3 gradient offload buffers, default `pin_memory: true`; master partitions unchanged), deepspeedai#8256 (merged: routes pin sites through `get_accelerator().pin_memory()`; this PR uses the same accelerator calls), deepspeedai#8618 (closed: a CPU-offload benchmark). Sibling path: ZeRO-1/2 pins its master partitions ([stage_1_and_2.py#L563-L575](https://github.com/deepspeedai/DeepSpeed/blob/0f8c9d7f13fc5d16479376392c67e7ca82ae9eed/deepspeed/runtime/zero/stage_1_and_2.py#L563-L575)). deepspeedai#5301 added the pinning and copied the pinned master to the device before the cast; ZeRO-1/2 now casts into a pinned bf16 buffer of each partition's size instead ([#L3093-L3096](https://github.com/deepspeedai/DeepSpeed/blob/0f8c9d7f13fc5d16479376392c67e7ca82ae9eed/deepspeed/runtime/zero/stage_1_and_2.py#L3093-L3096)). This PR uses deepspeedai#5301's form, which needs no second pinned buffer. ## Root cause What `offload_optimizer.pin_memory: true` pins in ZeRO-3 on master, checked at runtime on the earlier version of this PR, which pins the same buffers as master (one GPU, bf16, DeepSpeedCPUAdam, after `deepspeed.initialize` and after one step): | Buffer | Where | Pinned | |---|---|---| | `fp16_partitioned_groups_flat` (bf16 parameter partitions) | device | (device memory) | | `fp32_partitioned_groups_flat[i].grad` (float32 gradient partitions) | host | yes ([stage3.py#L1339-L1340](https://github.com/deepspeedai/DeepSpeed/blob/0f8c9d7f13fc5d16479376392c67e7ca82ae9eed/deepspeed/runtime/zero/stage3.py#L1339-L1340)) | | `fp32_partitioned_groups_flat` (float32 master partitions) | host | no | | Adam `exp_avg`, `exp_avg_sq` | host | no | With `offload_param`, `fp16_partitioned_groups_flat` is on the host and already pinned: it is a view of `param_groups_fp16_flat_cpu_memory` ([stage3.py#L906](https://github.com/deepspeedai/DeepSpeed/blob/0f8c9d7f13fc5d16479376392c67e7ca82ae9eed/deepspeed/runtime/zero/stage3.py#L906)). `_create_fp32_partitions` builds each CPU master partition with `.to('cpu', dtype=...)` and `.clone().detach()` ([stage3.py#L1157-L1160](https://github.com/deepspeedai/DeepSpeed/blob/0f8c9d7f13fc5d16479376392c67e7ca82ae9eed/deepspeed/runtime/zero/stage3.py#L1157-L1160)), which gives pageable memory. After the CPU optimizer step, `_reassign_or_swap_out_partitioned_parameters` runs `fp16_flat.data.copy_(fp32_flat.data)`: a blocking copy from CPU float32 to device bf16, which PyTorch does by casting on the CPU into a new pageable bf16 tensor of the whole partition, copying it from pageable memory and synchronizing. Found in a profile (MiniMax-M3, first 8 layers, 8 H200, 75% of the optimizer on the CPU, rank 0): 13 bare `aten::copy_` host-to-device copies of 576 MiB per step from pageable memory, at 3-7 GB/s, 1,648 ms per step. ## The change (`deepspeed/runtime/zero/stage3.py`, 43 added, 4 removed lines) | Where | What | |---|---| | `_create_fp32_partitions` | with `offload_optimizer.pin_memory`, pins each CPU master partition after `clone().detach()` (`get_accelerator().pin_memory`) | | `_reassign_or_swap_out_partitioned_parameters` | uses the new copy for a master pinned there whose destination is on the device; every other case keeps `dst.copy_(src)`: `pin_memory` false, sub-groups kept on the device (`ratio` < 1), NVMe-swapped sub-groups | | new `_copy_pinned_master_to_device(dst, src)` | per piece of 2**26 elements: `src[piece].to(device, non_blocking=True)`, then `dst[piece].copy_(...)`, which casts on the device; at the end, records an event and waits for it | | new `_master_pinned_at_construction(sub_group_id)` | the condition above (pinned, on the CPU, not NVMe-swapped); also used by `_unpin_offload_buffers` | | `__init__`, `_unpin_offload_buffers` | the piece size; release of the pinned masters (matters under `DS_PIN_MEMORY_BACKEND=native`) | Design notes: - **Why the cast moves to the device:** pinning alone does not make the copy faster. A blocking `copy_` from pinned float32 into bf16 still casts on the CPU into a new pageable tensor (136.2 ms against 136.5 ms from pageable memory, 300M elements, in an earlier measurement on the same setup). - **Why pieces:** `.to(device)` of a whole sub-group makes a float32 device temporary of the sub-group's size, 3.73 GiB at the default `sub_group_size` of 1e9. Pieces of 2**26 elements keep it at 0.25 GiB at the same speed. Measured on one H200, torch 2.8.0, 12 CPU threads, copying one partition back into its bf16 device partition: | Copy back | 300M elements | 1e9 elements | Extra device memory at 1e9 | |---|---|---|---| | `copy_` from pageable float32 (master) | 132.6 ms | 483.3 ms | 0 | | pinned float32, `.to(device)`, then `copy_` (deepspeedai#5301) | 22.1 ms | 73.6 ms | 3.73 GiB | | the same in pieces of 2**26 elements (this PR) | 22.1 ms | 73.7 ms | 0.25 GiB | | earlier version of this PR: two pinned 2**26-element bf16 staging buffers | 19.4 ms | 73.6 ms | 0 | - **Same values:** the device cast rounds to nearest even, as the CPU cast does. The new test compares the trained parameters bitwise against `pin_memory: false`. - **Stream order:** the pieces go on the current stream. The final wait keeps what callers had before: the partition is on the device when the function returns. The next forward's parameter all-gathers run on their own stream, and that stream does not wait for the main stream. - **Host synchronization:** one wait per sub-group, at the end of its copy. The old path also blocked for the whole copy. ## Measured Qwen2.5-32B (all 64 layers, real weights), 1 node of 8 H200 (143,771 MiB, driver 580.126.09), torch 2.8.0+cu126. Settings: - ZeRO-3 with `offload_optimizer: {device: cpu, pin_memory: true}`; - float32 master weights and Adam states, DeepSpeedCPUAdam with 12 threads per rank; - bf16, one 8,192-token PG-19 sequence per GPU, activation checkpointing, lr 1e-6; - mean of steps 3-8; one run per column; all runs in one job on the same node. | | master `0f8c9d7f1` | earlier version of this PR (staging buffers) | this PR | |---|---|---|---| | step time | 12.08 s | 10.20 s | **9.42 s** | | step time with `wall_clock_breakdown` | 11.96 s | - | 9.42 s | | rank 0: forward / backward | 1.19 / 3.71 s | - | 1.19 / 3.67 s | | rank 0: `step` / of which the sub-group loop (`optimizer_step`) | 7.06 / 6.05 s | - | 4.56 / 3.52 s | | peak device memory (rank 0) | 34.66 GB | 34.66 GB | 34.66 GB | | loss at steps 1 / 2 / 8 | 0.022649 / 0.976290 / 1.746374 | 0.022649 / 0.976256 / 1.746135 | 0.022649 / 0.976285 / 1.746306 | The losses differ from step 2 by run-to-run variation: two master runs differ by as much (step 2 is 0.976235 with `wall_clock_breakdown` and 0.976290 without it). The flash-attention backward adds with atomics. The bitwise check is the unit test below. This version is faster than the earlier one in training (9.42 against 10.20 s), although the two copies take the same time alone at 1e9 elements. A likely reason, not measured: the earlier version cast on the CPU, which the CPU optimizer of all 8 ranks on the node also uses; this version casts on the device. <details><summary>Earlier version of this PR (staging buffers) on MiniMax-M3 (DeepSpeed master + unmerged MiniMax-M3 model code: deepspeedai#8658, deepspeedai#8652)</summary> Settings for both: ZeRO-3 + AutoEP (expert parallel 8), real weights, each 65,536-token sequence split over 4 GPUs, 65% of the optimizer on the CPU (`offload_optimizer.ratio` 0.65), float32 master + Adam. - 4 nodes x 8 H200, all 60 layers, same nodes, back to back: 126.9 s without, 123.9 s with (mean of steps 3-10); peak device memory 132.4 GB in both. - 1 node, first 8 layers: 14.09 s without, 12.46 s with; losses equal at every printed step. These were not repeated with this version. </details> ## Tests Updated: `TestZero3OffloadPinnedCopyBack` in `tests/unit/v1/zero/test_zero.py` (2 ranks, `ratio` 1.0 and 0.5, `sub_group_size` 20,000 so partial offload has sub-groups on both sides). - It trains 3 steps with `pin_memory: false` (direct copy) and with `pin_memory: true`, and requires the gathered parameters to be bitwise equal. - It requires every CPU master partition to be pinned with `pin_memory: true`, and none with `pin_memory: false`. - It requires that the pinned run used the new copy. Otherwise the test would compare the direct copy with itself. - The piece size is set to 1,000 elements, so each sub-group is copied in many pieces. Commands, from `tests/`, on 1 node of 8 H200 (143,771 MiB, driver 580.126.09), torch 2.8.0+cu126, pytest 9.1.1: ``` # master 0f8c9d7 + only the new test: 2 failed, AttributeError: no attribute '_copy_pinned_master_to_device' # master + this PR: pytest unit/v1/zero/test_zero.py -k TestZero3OffloadPinnedCopyBack # 2 passed pytest unit/v1/zero/test_zero.py unit/v1/zero/test_zero_user_backward.py unit/v1/pin_memory/ \ -k "offload or Offload or pin or Pin" # 61 passed, 1 skipped (torch_npu) pytest unit/v1/zero/test_offload_states.py # 128 passed pytest unit/runtime/zero/test_zero_offloadpp.py unit/v1/pin_memory/ # 47 passed, 1 skipped (torch_npu) ``` The test is in `tests/unit/v1`, so PR CI selects it: the `modal-torch-latest` selector (`ci/tests_fetcher.py`) picked `tests/unit/v1/zero/test_zero.py` for the earlier version, which changes the same two files. ## Compatibility | Cell | Validated | |---|---| | ZeRO-3, CPU optimizer offload, `pin_memory` true, whole optimizer on the CPU | yes: new test (ratio 1.0); Qwen2.5-32B | | ZeRO-3, partial offload (`ratio` < 1) | yes: new test (ratio 0.5). MiniMax-M3 on 1 and 4 nodes with the earlier version only | | ZeRO-3, `pin_memory` false | unchanged path (not pinned, direct copy); the new test's reference | | bf16 | yes. fp16: not run (same path; the device cast also rounds to nearest even) | | ZeRO-3, NVMe optimizer offload | not run. Unchanged: NVMe-swapped sub-groups are not pinned here and keep the direct copy | | ZeRO-3 + ZenFlow, `DS_PIN_MEMORY_BACKEND=native` | not run | | ZeRO-1/2 | not affected | | Accelerators other than CUDA | not run; only `get_accelerator()` calls are used (`pin_memory`, `is_pinned`, `Event`, `unpin_memory`) | No config, checkpoint format or public API change. ## AI assistance This change, its tests and this description were prepared with AI assistance (Claude). --------- Signed-off-by: pengdurice <pengduhit@gmail.com> Co-authored-by: Olatunji Ruwase <tunji.ruwase@snowflake.com>
AutoEP: fused Triton kernel for the clamped expert activations
Branch:
peng-add-fuse-fn-clamped-form-v1, rebased onmasterat5f266e26d(2026-10-15). The expert activation registry itregisters into is merged (#8650), and so is the fused gate+up projection (#8733), which this PR now also covers.
Part of: #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 (#8650) and MiniMax-M3 preset (#8651).
Summary
The clamped expert activations
swiglu_clamped(DeepSeek-V4) andswiglu_oai(GPT-OSS, MiniMax-M3) run as plainPyTorch expressions that keep about four
[rows, ffn]temporaries for backward. Plainswigluhas fused Tritonkernels that keep only
gateandup. 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, Add an opt-in fused gate+up grouped GEMM for AutoEP experts #8733):swiglu_clamped_packed(gate_up, ...), which reads the two halvesof the packed GEMM output in place, as master's
swiglu_packeddoes.At the busiest rank of a MiniMax-M3 run that ran out of memory (1,045,081 rows x 3,072, bf16), one
swiglu_oaicall 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. #8748 (another author, open) adds a different kernel,
swiglu_weighted(routing weightinside the activation, plain
swigluonly), to the same two files (swiglu_triton.pyand the registry inep_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_activationon one 11.96 GiBtemporary, with 129.50 GiB already in use. (Setup: all 60 layers, real checkpoint,
minimax_m3preset, ZeRO-3 withthe optimizer state on the host, activation checkpointing; torch 2.8.0+cu126, transformers 5.15.1, DeepSpeed master
4a5856c25plus the then-open registry PR.) Over the 57 MoE layers, the busiest of 32 ranks received a median 4.20times the mean number of rows (maximum 7.84).
The change
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.constexprselects the form,PACKED: tl.constexprreadsgateandupfrom one[rows, 2 * INTER]tensor with master's packed indexing. The clamp gradient passes at the limit, astorch.clamp's does. Publicswiglu_clamped(gate, up, alpha, limit, oai)andswiglu_clamped_packed(gate_up, alpha, limit, oai); plain-PyTorch fallback without Triton or on the CPU. The packed backward raises forcreate_graph=True, as master's packed swiglu doesdeepspeed/moe/ep_experts.pyfused_fnandpacked_fused_fnofswiglu_clampedandswiglu_oai. Nothing else changes: the grouped-GEMM expert paths reach them throughapply_expert_activation(..., fused=True)andapply_packed_expert_activation; the for-loop reference path keepsfused=Falsedocs/_pages/config-json.mdtests/unit/v1/ops/triton_ops/test_swiglu_triton.py,tests/unit/v1/moe/test_autoep_expert_activation.pySize: 264 added and 2 removed lines under
deepspeed/(232 added inswiglu_triton.py, 32 inep_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, limit7.0, inputs at 6 x standard normal so most values are past a clamp. Extra peak =
max_memory_allocatedduringforward + 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.
1c862f7df: extra peak / kept / timeswiglu(existing kernels, for comparison)swigluswiglu_clampedswiglu_clampedswiglu_oaiswiglu_oaiPer MoE layer on that rank,
swiglu_oaikeeps 23.92 GiB less for backward and runs 6.5 times faster (separate) or9.0 times faster (packed). The packed clamped kernels are 1.2-1.3 ms slower than master's packed
swiglukernel,which does less arithmetic per element. Bench script:
expert_activation_bench.py(TODO(user): attach as a gist ordrop 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:
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 #8733 on torch 2.9.1: 12 passed on this branch and 12 passed on master.The two deselected tests are master's (#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]) totorch._grouped_mm, whose backward never returns for some shapes when a group is empty on that torch version (GPU at100% with no progress; known from MiniMax-M3 work, one-GPU reproduction available). AutoEP itself never passes an
empty group, because
generate_permute_indicesgives every local expert at least 8 rows. On torch 2.8.0 master'stest_matches_separate_with_skewed_and_empty_experts[swiglu]did not finish in 300 s; on torch 2.9.1+cu128 (Triton3.5.1) both tests pass, 12 passed on this branch and 12 passed on master.
New and changed tests:
test_clamped_forward_matches_reference(2 forms x 3 dtypes x 6 shapes)test_clamped_backward_matches_reference(2 x 3 x 5)test_clamped_alpha_and_limit_are_honouredtest_clamped_gradient_at_the_limit_is_inclusivegate == limitorup == -limit, wheretorch.clamp's passestest_clamped_empty_input,test_clamped_non_contiguous_input,test_clamped_shape_and_dtype_mismatch_rejectedtest_clamped_packed_matches_the_separate_kernel_exactly(2 forms x 2 dtypes x 4 shapes, including 3-D and empty)test_fused_kernel_matches_plain_pytorch(every form with afused_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(wastest_only_swiglu_has_a_packed_kernel)test_grouped_gemm_paths_match_the_for_loop,test_packed_activation_matches_the_separate_halves(master's, now running the new kernels)pre-commit run --filespasses 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.
gate_up_impl"separate"and"fused";torch._grouped_mmand Triton grouped-GEMM paths (unit tests)torch.cuda.device(#ignore-cuda), as master's packed swiglu doesAI assistance
This PR was written with AI assistance (Claude).
🤖 Generated with Claude Code