Repository navigation
Add deepspeed.models.minimax_m3_vl: block-sparse attention for MiniMax M3 - #8658
Draft
pengdurice wants to merge 1 commit into
Draft
pengdurice wants to merge 1 commit into
pengdurice wants to merge 1 commit into
Conversation
pengdurice
force-pushed
the
peng-add-minimax-m3-sparse-attention-v1
branch
from
September 29, 2026 16:18
7fd08fd to
619721c
Compare
…ng MiniMax-M3 at long sequence lengths Signed-off-by: pengdurice <pengduhit@gmail.com>
pengdurice
force-pushed
the
peng-add-minimax-m3-sparse-attention-v1
branch
from
October 15, 2026 19:30
619721c to
70d602d
Compare
This was referenced Oct 16, 2026
Merged
banxingmjj
pushed a commit
to openanolis/DeepSpeed
that referenced
this pull request
Oct 30, 2026
…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>
banxingmjj
pushed a commit
to openanolis/DeepSpeed
that referenced
this pull request
Nov 12, 2026
….2 (deepspeedai#8659) # Add `deepspeed.models.glm_moe_dsa`: TileLang sparse attention for training GLM-5.2 **Part of:** deepspeedai#8672 (Q4 2026 roadmap), "Enable training of large scale models": "Test and verify support of SOTA models" (PoC @pengdurice). Sibling: deepspeedai#8658 (MiniMax-M3). ## Summary * GLM-5.2 cannot train past 16,384 tokens per GPU with the stock transformers attention. Its indexer scores and its attention mask are both dense `seq x seq` tensors. * This PR adds TileLang kernels that attend only to the 2,048 keys the indexer selects for each query, with a backward pass, and a replacement attention module that uses them. One call, `deepspeed.models.glm_moe_dsa.replace_attention(model)`, swaps it in. * With it, the full 78-layer GLM-5.2 (743.4B parameters) trains at 65,536 tokens per GPU on 8 nodes of 8 H200. On an 8-layer cut of the model at 16,384 tokens, 10 training steps give the same loss as the stock path and run 2.7 times faster. * It adds a new folder, `deepspeed/models/<family>/`, for training code that belongs to one model family. ## Why a `deepspeed/models/` folder Some models need changes that only make sense for that model: a kernel for its attention, a replacement module, a fix for its layout. Other training stacks keep this code in one folder per model family, for example `torchtitan/models/<model>/`, Megatron-Bridge's `src/megatron/bridge/models/<family>/`, and THUDM/slime's `slime_plugins/models/glm5/`. DeepSpeed has no such place on the training side. The inference side has `deepspeed/inference/v2/model_implementations/<family>/`, and AutoEP keeps one preset file per model in `deepspeed/module_inject/auto_ep_presets/`. The convention this PR starts: * One package per family in `deepspeed/models/`, named after the model's folder in `transformers.models`. Here that is `glm_moe_dsa`. A reader goes from a Hugging Face model to its DeepSpeed code without a lookup table. * A family package holds whatever that family needs: kernels, modules, or plain PyTorch. Here it holds the TileLang kernels in `kernels/` and the replacement module in `attention.py`. * A family package exposes the function to call on a built model before `deepspeed.initialize`. Here that is `replace_attention`. * `import deepspeed` does not import `deepspeed.models`. A family's optional dependency (here TileLang) is needed only by users of that family. The MiniMax-M3 sparse-attention PR adds a second family, `deepspeed/models/minimax_m3_vl/`. Both PRs add the same `deepspeed/models/__init__.py` and the same docs index entry, byte for byte, so they merge in either order without conflicts. ## Problem GLM-5.2 (transformers `glm_moe_dsa`, DeepSeek Sparse Attention) cannot train at long sequence lengths on the stock transformers path, whatever DeepSpeed does about parameters and optimizer state: * `GlmMoeDsaIndexer.forward` scores every query against every key as a dense float32 `[batch, 32 index heads, S, S]` tensor before the top-k. That is 34 GB at S = 16,384 and 137 GB at S = 32,768, for each layer, before the relu copy and the head-weighted sum. * `GlmMoeDsaAttention.forward` then turns the top-k indices into a dense `[batch, 1, S, S]` additive mask. It calls the attention interface with per-head K and V expanded from the 512-wide latent (`expand_kv`). So the attention is dense too, quadratic in S, and cannot use the absorbed form. * Registering another attention function through `AttentionInterface` does not help. By the time the interface is called, the module has already expanded K and V and built the mask. THUDM/slime trains GLM-5 in Megatron with TileLang kernels that do two things: 1. compute the indexer logits in blocks of query rows and take a hard top-k; 2. run attention in the absorbed multi-head latent attention form over the selected latent keys only, with a fused backward. Depending on slime or Megatron for these kernels is not an option, so this PR adapts them into DeepSpeed. ## The change **`deepspeed/models/__init__.py`** (new): the package docstring that states the convention above. It imports nothing. **`deepspeed/models/glm_moe_dsa/kernels/`** (new): the kernels. They are adapted from the `deepseek_v32` examples in tile-ai/tilelang (MIT), by way of the GLM-5 plugin in THUDM/slime (Apache-2.0). The kernel bodies are the same. The Megatron, context-parallel and sequence-parallel code is removed, and the latent width is a parameter instead of a constant. Importing this package imports TileLang. | file | what it holds | |---|---| | `sparse_mla_fwd.py` | forward kernel: online softmax over the gathered top-k latent keys, `-1` indices masked; returns the output and the log-sum-exp | | `sparse_mla_bwd.py` | backward: preprocess (delta), the `dq` kernel and the atomically accumulated `dkv` kernel, postprocess | | `sparse_mla.py` | `sparse_mla(q, kv, indices, scale, d_v)`: the `torch.autograd.Function` around the two | | `indexer_fwd.py` | lightning indexer logits for a block of query rows, `[rows, keys]` float32, `-inf` outside each row's window | | `indexer.py` | `select_topk(...)`: runs the indexer in blocks of 8,192 query rows (2 GiB of logits per block at 65,536 keys), takes the top-k per block, pads rows with fewer keys with `-1`; `@torch.no_grad()` | Shapes are token-major: `q [tokens, heads, 512 + 64]`, `kv [tokens, 1, 512 + 64]`, and `indices [tokens, 1, topk]` int32 with `-1` for unused slots. `topk` must be a multiple of 64. **`deepspeed/models/glm_moe_dsa/attention.py`** (new): `DeepSpeedGlmMoeDsaAttention(source)` and `replace_attention(model, index_block_rows=8192, warm_up=True)`. * The replacement keeps the source module's parameters and attribute names (`q_a_proj`, `q_a_layernorm`, `q_b_proj`, `kv_a_proj_with_mqa`, `kv_a_layernorm`, `kv_b_proj`, `o_proj`, `indexer`). State-dict keys, parameter-freezing patterns and AutoTP name patterns do not change. Only `forward` is different. * Forward, step by step: 1. The no-rope part of the query is absorbed into the latent with this head's slice of `kv_b_proj.weight`: `q_nope . (W_kc kv) == (W_kc^T q_nope) . kv`. 2. Rotary embedding is applied interleaved, as in the model. 3. The indexer selects the top-k positions. The scores are the same as in transformers: `sum_h w_h relu(scale q_h . k)`. The scale is folded into the weights, which is exact because relu is positively homogeneous. 4. `sparse_mla` attends over the selected latent keys. 5. The other slice of `kv_b_proj.weight` maps the output back to value space before `o_proj`. Layers of type `"shared"` reuse `prev_topk_indices` from the previous full layer, as the stock module does. * The module reads `kv_b_proj.weight` as a tensor and never calls `kv_b_proj`, so ZeRO-3 gets no forward hook for that weight. The module registers the weight with `deepspeed.zero.register_external_parameter`. ZeRO-3 then gathers it for this module's forward and backward and releases it afterwards. * The indexer is not trained. A hard top-k has no gradient, and transformers does the same (its indexer forward is `@torch.no_grad()`). Under ZeRO-3, users freeze the indexer parameters, as they already must on the stock path. * Training only: * no key-value cache; * no padding mask: every sequence in the batch is one full causal sequence; * attention dropout must be 0. * Replace every DSA attention layer of a model, or none. The stock module encodes the earliest rows' missing keys through its causal mask, and this one through `-1`, so a shared layer must receive indices from a layer of its own kind. * Constructor checks: * `kv_lora_rank` and `qk_rope_head_dim` are powers of two; * `index_topk % 64 == 0`; * the head count is at most 64 or a multiple of 64; * the index head count divides 128. * `replace_attention` checks for TileLang first and raises `ImportError` with the install command. * Kernel warm-up. With `warm_up=True` (the default), when the backward kernel uses 128 threads (head blocks under 64 heads, for example with the heads split over tensor-parallel ranks), each attention module launches every kernel once, forward and backward, on a 128-token input with the model's head counts, head dims and top-k, at its first forward and on that forward's device. It runs without autograd, so activation checkpointing's recomputation saves the same tensors as the first forward. * Why: the 128-thread backward kernel spills registers, so its first launch makes the CUDA driver reserve local memory outside PyTorch's allocator, and the driver keeps it. Without the warm-up that launch happens in the first backward of training, when the allocator's cache can hold the rest of the device. On the full 78-layer GLM-5.2 at 65,536 tokens per GPU on 64 H200s it failed there with `CUDA_ERROR_OUT_OF_MEMORY` on 3 of the 64 GPUs. * The 256-thread kernel (64-head blocks: GLM-5.2's 64 heads on one GPU) does not spill, so it gets no warm-up. Measured on one H200, 64 heads, 32,768 tokens, memory used outside PyTorch's allocator around the first backward launch: | Backward kernel | First training-length launch, no warm-up | 128-token warm-up launch | Training-length launch after the warm-up | |---|---|---|---| | 128 threads | +0.469 GiB | +0.467 GiB | +0.000 GiB | | 256 threads (64-head blocks) | +0.002 GiB | not run | | * `kernels/sparse_mla_bwd.py` `backward_threads(heads_per_kv_group)` picks the thread count for both the kernel and the warm-up decision, so the two cannot disagree. * The forward and indexer kernels take the sequence length at run time, so the warm-up builds the kernels training uses. The backward kernel takes the batch size and both sequence lengths at compile time, so training's first backward still compiles its own backward kernel; what the warm-up launch provides is the local-memory reservation, which covers the training-length launch (table). **`docs/code-docs/source/models/glm_moe_dsa.rst`** (new) and an entry in **`docs/code-docs/source/index.rst`** that lists every page in `models/`: usage, requirements, limits, and the API reference. **`tests/unit/v1/models/test_glm_moe_dsa.py`** (new): see Tests. ## Changes after review Rebased on master (`5f266e26d`, 2026-10-15). All review points of the first round: | Review point | Change | |---|---| | Kernels adapted from TileLang / THUDM carry only DeepSpeed's header | The three kernel files carry the upstream copyright (`Copyright (c) Tile-AI.`) and `SPDX-License-Identifier: Apache-2.0 AND MIT`, and point to a new TileLang section in `THIRD_PARTY_NOTICES.md` (files, TileLang source paths and revisions, the slime revision they came through, the full MIT text). `scripts/check-license.py` accepts the expression. `setup.py` now lists `THIRD_PARTY_NOTICES.md` in `license_files`; before, the notice was in neither the sdist nor the wheel (checked by building both). | | `output_attentions=True` returns `attentions=()` | Raises `NotImplementedError`: the kernels never form attention weights. | | Padding and packed-sequence masks are ignored | A padding mask, a packed-sequence mask or position ids that restart raise `NotImplementedError`. No mask and eager attention's full causal mask are accepted. The check waits for the GPU, so it runs once per model forward, not once per layer. | | Widths 1 and 2 pass validation | `kv_lora_rank` and `qk_rope_head_dim` must be powers of two of at least 4 (the backward kernel splits the width into groups of 4). | | The warm-up runs on GPU 0 in every process | It runs at the module's first forward, on the input's device. | | The warm-up's backward kernel is compiled for 128 tokens | Correct: see the kernel warm-up bullet above. The warm-up now runs only for the 128-thread backward kernel, the one whose first launch reserves local memory. | Two additions from running GLM-5.2 at scale: * **256-thread backward kernel for 64-head blocks** (128 threads otherwise, as in tile-ai/tilelang#2592): 3.09x faster per kernel at GLM-5.2's shapes on an H200, 34-40% more tokens per second in training. * **Sequence split (context parallel).** `deepspeed.models.glm_moe_dsa.set_context_parallel_group(group)`: every rank of the group holds a contiguous slice of each sequence with global positions; the latent keys and the indexer keys are all-gathered over the group and their gradients reduce-scattered back; the indexer's causal bounds use global positions. GLM-5.2's first 38 layers at 65,536 tokens on 4 nodes x 8 H200, each sequence over 2 GPUs, ZeRO-3 + AutoEP: 96.4 s per step, 9.44% MFU, losses within 0.03 and the step-1 gradient norm within 0.02% of the same run on an earlier tree. ## Measured The at-scale runs below used this code before it moved into `deepspeed/models/`. The move changed only import paths and the class and function names. The kernel files are byte-identical. The unit tests were rerun on this branch (see Tests). ### Real weights, against Megatron-LM, 4 and 8 nodes x 8 H200 (2026-10-14 and 2026-10-15) These runs used this branch's files unchanged: the DeepSpeed tree they ran on has the same `deepspeed/models/glm_moe_dsa/` files. On one node (first 4 layers), master plus this PR gives the same loss at every step as that tree. Setup: GLM-5.2 real checkpoint, PG-19, 65,536 tokens per sequence, ZeRO-3 + AutoEP (expert parallel 8), each sequence over 2 GPUs (`set_context_parallel_group`), bf16 compute with fp32 master weights and Adam states, 80% (38 layers) or 95% (78 layers) of the optimizer on the CPU, full activation recompute. Megatron-LM: Megatron-FSDP, context parallel 4, expert parallel 8, the same share of the optimizer on the CPU. | Model | Nodes | Sequences per step | DeepSpeed, s/step | Megatron-LM, s/step | How measured | |---|---|---|---|---|---| | first 38 layers (348B parameters) | 4 x 8 H200 | 32 | 62.03 | 63.73 | one job on the same nodes, the frameworks alternating, mean of steps 4-23 of 2 runs each | | all 78 layers (743B parameters) | 8 x 8 H200 | 64 | 130.58 | 135.56 | separate jobs on 7 of the same 8 nodes, mean of steps 6-10 | Mean loss over the 23 steps of the same-job runs (first run of each): 9.6060 DeepSpeed, 9.6207 Megatron-LM. The DeepSpeed runs also used the ZeRO-3 pinned copy-back and fused CPU Adam changes (separate PRs). ### Full GLM-5.2, all 78 layers, 8 nodes x 8 H200, 65,536 tokens per GPU Setup: * Model: config-only build of GLM-5.2 with all 78 layers. 743.4B parameters, 724.8B of them in 75 MoE layers of 256 experts (top-8). 21 layers run the indexer, 57 reuse its selection. * Parallelism: AutoEP expert parallel 16 (4 expert groups of 2 nodes), TP 1, ZeRO-3 with `leaf_module` on the AutoEP layer. * Memory: optimizer state offloaded to host memory. Activation checkpointing with the checkpointed layer inputs in host memory (`checkpoint_in_cpu`). bf16 master weights and optimizer states. * Data: micro-batch 1, which is one 65,536-token PG-19 book per GPU. Tiled loss (16 shards). Indexer frozen. * Steps: 1 warm-up + 3 measured, learning rate 1e-6. * Environment: `NCCL_RUNTIME_CONNECT=0` and `NCCL_NVLS_ENABLE=0`. With NCCL 2.27's default lazy connection, the first scalar all-reduce of the optimizer's gradient norm needed new NCCL buffers after the backward had filled the device, and it failed. This is a launch setting, not part of this PR. * Versions: torch 2.8.0+cu126, transformers 5.15.1, tilelang 0.1.14, NCCL 2.27.3. | measured | value | |---|---| | step time, mean of 3 measured steps | 252.56 s (251.3 / 253.7 / 252.7) | | throughput | 16,607 tokens/s over 64 GPUs (4,194,304 tokens per step) | | MFU / HFU, H200 dense bf16 peak 989 TFLOPS | **7.28 %** / 10.98 % (72.0 TFLOPS per GPU of model FLOPs) | | peak allocated, highest GPU | 116.54 GiB of 139.80 | | peak reserved, highest GPU | 132.34 GiB | | allocated between steps (weights, gradients, buffers) | 33.15 GiB | | loss / gradient norm (random initialisation) | 13.19 / 4.62 to 4.97 | Same setup with `OMP_NUM_THREADS=12` for the CPU Adam optimizer, and DeepSpeed's wall-clock breakdown timers on. The launcher sets 1 thread per rank by default, which leaves the offloaded optimizer on one CPU thread. This is a launch setting, not part of this PR. | measured | value | |---|---| | step time | 220.5 s: forward 39.2 s, backward 165.9 s, optimizer step 14.8 s | | throughput | 19,020 tokens/s over 64 GPUs | | MFU | 8.34 % | How MFU is counted, per token: | part | GFLOP per token | |---|---| | 6 x the 40.10B active matmul parameters (attention projections, dense MLPs, router, shared expert, 8 routed experts, output layer) | 240.6 | | sparse attention over the selected keys (2,016 on average at this length), model head dims, forward + backward | 30.9 | | the frozen indexer, forward only | 6.1 | | **total** | **277.6** | HFU adds the forward recompute of activation checkpointing and the absorbed attention form that the kernel executes: 418.7 GFLOP per token. The stock transformers path cannot run this configuration: its indexer alone allocates a 137 GB score tensor per layer at 32,768 tokens. ### GLM-5.2 cut to 8 layers, 2 nodes x 8 H200, ZeRO-3 + AutoEP Setup: * Model: config-only build of GLM-5.2 cut to 8 of 78 layers. 5 MoE layers with 256 experts, top-8. The indexer schedule keeps both modes: layers 0, 1, 2 and 6 run the indexer; layers 3, 4, 5 and 7 reuse the selection. 52.5B parameters, of which 48.3B are expert weights. * Parallelism and memory: expert parallel 16, TP 1, ZeRO-3 with `leaf_module` on the AutoEP layer, bf16 master weights and optimizer states, Hugging Face gradient checkpointing. * Data: micro-batch 1 per GPU. Tiled loss (16 shards) for the 154,880-token vocabulary. Real text: PG-19 books re-tokenized with the GLM-5.2 tokenizer, one book per row. Indexer frozen. * Steps: 10 (3 warm-up + 7 measured). * Versions: torch 2.8.0+cu126, transformers 5.15.1, tilelang 0.1.14. * Throughput is tokens per second over all 16 GPUs. | attention | seq | s / step | tokens / s (16 GPUs) | step peak allocated | peak reserved | |---|---|---|---|---|---| | DSA kernels | 16,384 | 4.65 | 56,429 | 54.6 GiB | 67.0 GiB | | DSA kernels | 32,768 | 9.26 | 56,621 | 73.6 GiB | 91.5 GiB | | DSA kernels | 65,536 | 18.46 | 56,798 | 112.0 GiB | 133.4 GiB | | stock SDPA (memory-efficient kernel, dense top-k mask), second run | 16,384 | 12.70 | 20,645 | 71.6 GiB | 93.7 GiB | | DSA kernels, second run | 16,384 | 4.73 | 55,477 | 55.8 GiB | 68.2 GiB | * At 16K the kernels are 2.7 times faster than the stock path and reserve 25 GiB less. * Tokens per second stay flat from 16K to 65K. The selection is fixed at 2,048 keys per query, so attention cost grows linearly with the token count, like the rest of the layer. * No stock number exists past 16K on a 141 GB card. At 32K the stock indexer needs 137 GB for the scores of one layer alone. * The first step at 16K took 148 s, which includes the TileLang compile of both kernels for the run's shapes. The 32K and 65K runs started at 59 s and 70 s: ZeRO-3 first-step setup only, with the compile cached on the node. ### Stock transformers attention against the DSA module, same data, seq 16,384 The same 8-layer model, same seed, same PG-19 rows, learning rate 1e-5. The printed loss is the running mean of the bf16 per-step losses since step 1. | step | stock: running mean loss | DSA: running mean loss | stock: grad norm | DSA: grad norm | |---|---|---|---|---| | 1 | 13.250000 | 13.250000 | 8.2648 | 8.2634 | | 2 | 13.093750 | 13.093750 | 7.8671 | 7.8675 | | 3 | 12.916667 | 12.916667 | 8.5182 | 8.5209 | | 4 | 12.796875 | 12.796875 | 8.7343 | 8.7375 | | 5 | 12.675000 | 12.675000 | 8.3782 | 8.3754 | | 6 | 12.531250 | 12.531250 | 8.3926 | 8.3821 | | 7 | 12.491071 | 12.491071 | 9.5111 | 9.5051 | | 8 | 12.335938 | 12.335938 | 7.7833 | 7.7907 | | 9 | 12.319444 | 12.319444 | 6.6761 | 6.6875 | | 10 | 12.206250 | 12.206250 | 8.8822 | 8.8952 | * Every running-mean loss agrees to the printed precision, so every per-step bf16 loss is identical. * The gradient norms agree within 0.16 %. * Other learning rates: at 1e-6, ten steps do not move the loss. At 1e-4 this randomly initialised model diverges after one step, which amplifies bf16 noise and top-k ties. Even there, the per-step losses were identical for the first three steps. ## Tests `tests/unit/v1/models/test_glm_moe_dsa.py` (new). It is skipped without TileLang or a CUDA device. | test | what it checks, and the wrong behaviour it would catch | |---|---| | `test_sparse_mla_matches_reference` (8 heads, 64 heads) | the output and both input gradients of `sparse_mla`, against the sparse softmax written out in float32, over a random causal selection with `-1` padding. 8 heads exercises the kernel's padding of heads to 16 | | `test_indexer_logits_and_selection_match_reference` (8 and 32 index heads) | the logits against the float32 formula, with `-inf` exactly on the future keys. `select_topk` returns the reference top-k on every row where the k-th and (k+1)-th scores are apart, the right number of valid slots on the early rows, and never a future key | | `test_sparse_mla_at_glm52_sizes` | the run's shapes: 64 heads, top-k 2048 (32 index blocks of 64 per row), 16,384 tokens. Output, `dq` and `dkv` against the float32 reference on 256 random query rows. A row's output and `dq` depend on that row alone; `dkv` is checked by sending a gradient into those rows only | | `test_indexer_selection_at_glm52_sizes` | 32 index heads, 16,384 tokens (two 8,192-row blocks in `select_topk`), top-k 2048: exactly k distinct causal keys per row, each scoring at least the k-th best float32 score minus a rounding allowance, so no better key was left out | | `test_replacement_matches_transformers_module` | on a small `GlmMoeDsaConfig`, the replacement's selection overlaps the stock indexer's on more than 90 % of slots (the two differ at ties). On a shared layer given the same indices, the output, the input gradient and the gradient of every parameter (`q_a_proj`, `q_a_layernorm`, `q_b_proj`, `kv_a_proj_with_mqa`, `kv_a_layernorm`, `kv_b_proj`, `o_proj`) match the stock module on every row with a complete selection | | `test_replace_walks_the_model_and_keeps_parameter_names` | `replace_attention` swaps every layer of `GlmMoeDsaForCausalLM`, and the parameter names do not change | | `TestDsaAttentionZeroStage3` (2 ranks, ZeRO-3, `torch_adam`) | the loss and the gradient of `kv_b_proj.weight`, the weight read directly, match a single-process run of the same replaced model. Without the external-parameter registration the weight is a 0-element placeholder in the forward | | `test_unsupported_inputs_raise` | `output_attentions=True`, a padding mask and position ids that restart all raise `NotImplementedError` | | `test_kernel_widths_below_four_are_rejected` | `kv_lora_rank` or `qk_rope_head_dim` below 4 raises `ValueError` | | `test_first_forward_under_activation_checkpointing` | the warm-up at the first forward leaves nothing saved for backward, so non-reentrant activation checkpointing's recomputation does not fail | | `test_warm_up_runs_on_the_input_device` (2 GPUs) | with the current device still GPU 0 at `replace_attention`, the warm-up allocates nothing on GPU 0 when the model runs on GPU 1 | | `TestDsaAttentionContextParallel` (2 ranks) | each sequence split over 2 ranks gives the logits, the summed loss and every parameter gradient of the whole sequence on one rank (`index_topk` = sequence length, so the selection has no near-ties) | Results on this branch (master `5f266e26d` + this PR, 2026-10-15): **14 passed** in 167 s on one node of 8 H200 (torch 2.8.0+cu126, transformers 5.15.1, tilelang 0.1.14). Tests of the attention alone build the model with dense MLPs (`_tiny_config(dense_mlps=True)`): the MoE backward can hang in torch 2.8's `_grouped_mm` when an expert receives no tokens. `pre-commit run --files` passes on every changed file. ## Duplicate check Open and recent pull requests searched on 2026-10-15 for "glm", "sparse attention", "DSA", "TileLang", "indexer": none adds GLM-5.2 or DeepSeek-sparse-attention training kernels. deepspeedai#8658 is the sibling for MiniMax-M3 (another family in the same `deepspeed/models/` folder; both add the same `deepspeed/models/__init__.py` and docs entry, byte for byte). ## Compatibility | Cell | Validated | How | |---|---|---| | ZeRO-3 + AutoEP, bf16, CPU optimizer offload, activation checkpointing | yes | full 78-layer GLM-5.2, 8 nodes x 8 H200, 65,536 tokens per GPU; 38-layer cut on 4 nodes | | Sequence split (context parallel) over 2 GPUs | yes | `TestDsaAttentionContextParallel`; 38 and 78 layers at 65,536 tokens | | ZeRO-3, 2 ranks, plain DeepSpeed (no AutoEP) | yes | `TestDsaAttentionZeroStage3` | | Heads split over tensor-parallel ranks (128-thread backward) | unit tests only | warm-up tests; no at-scale run | | ZeRO-1 / ZeRO-2, fp16, pipeline parallel | no | | | Accelerators other than CUDA | no | TileLang kernels; `replace_attention` raises `ImportError` without TileLang | Later measurement (not part of this PR's diff): the full 78-layer model at 65,536 tokens per GPU on 8 nodes x 8 H200 runs at 130.6 s per step (MFU 14.1 %) with this PR's kernels together with other DeepSpeed changes (prefetch settings, a pinned copy-back of offloaded master weights, a fused CPU Adam step, 5 % of the optimizer on the GPU). The 252.56 s above is the 128-thread backward kernel with bf16 optimizer states. ## AI assistance This change, its tests and this description were prepared with AI assistance (Claude). Signed-off-by: pengdurice <pengduhit@gmail.com>
This branch has not been deployed
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.
Add
deepspeed.models.minimax_m3_vl: block-sparse attention for training MiniMax-M3 at long sequence lengthsBranch:
peng-add-minimax-m3-sparse-attention-v1, rebased onmasterat5f266e26d(2026-10-15).Part of: #8672 (Q4 2026 roadmap), "Enable training of large scale models": "Test and verify support of SOTA
models" (PoC @pengdurice). Sibling: #8659 (GLM-5.2).
Summary
MiniMax-M3's stock transformers attention builds a dense
[batch, 64, S, S]mask in its 57 sparse layers (32 GiB at16,384 tokens), so the full 426B model stops at 14,336 tokens per GPU on 4 nodes of 8 H200. This PR adds a
replacement for those layers whose memory and time grow linearly with the sequence length:
deepspeed.models.minimax_m3_vl.replace_attention(model)swaps it in beforedeepspeed.initialize. Parameter namesand state-dict keys do not change.
fp16 on an accelerator that runs Triton), and plain PyTorch (CPU, float32, or shapes the kernels do not take).
set_context_parallel_group), for 65,536 tokens per sequence.index_block_max, samekernelchoice): one layer's selection for16,384 queries over 65,536 keys takes 2.8-5.7 ms instead of 60.5 ms on one H200, with exact float32 products. On
the full model (4 nodes, DeepSpeed study tree with CPU binding) 114.9 s per step with the old indexer (which ran in
bf16 under the engine's autocast, the bug fixed here) to 102.0 s with the kernel.
with the Triton kernels (1.67x), the same peak GPU memory, and losses within 0.003.
Duplicate check
Open PRs and issues searched on 2026-10-12 for "minimax", "sparse attention", "selected attention" and "NSA": the only
matches are this PR and #8659 (GLM-5.2 sparse attention, same author, a different model and kernel).
Problem
In each of MiniMax-M3's 57 sparse layers, a lightning indexer picks, for each query and key-value head, 16 blocks of
128 keys (2,048 keys per query). On its eager and SDPA paths, transformers'
MiniMaxM3VLAttention:[batch, 4, S, S]in the indexer;[batch, 64, S, S](build_block_mask): 32 GiB in bf16at S = 16,384;
On 4 nodes of 8 H200 the full model trained at 14,336 tokens and failed at 16,384 on the mask allocation.
Existing kernels, checked on H200 before writing this one:
ParallelNSAFunction(fla 0.5.2)1fe52b5d)example_tilelang_nsa_bwd.py(0.1.14)-1), and writes the mask by slot whilebwd_dkvreads it by block idThe change
deepspeed/models/minimax_m3_vl/selected_attention.py(new)fla/ops/nsa/parallel.pyandfla/ops/utils/csr.pyat1fe52b5d(MIT). Changes from fla: (1) the backward also takes queries that are the lastTQofTKkeys; (2) the softmax scale multiplies the float32 scores instead of roundingq * scaleto bf16 (output error 2.2-2.4e-3 instead of 2.7-3.4e-3); (3) a key block's list of selecting queries is split over programs of at most 1,024 queries that add float32 partial sums atomically, so block 0 (chosen by every query) no longer sets the dK/dV time; (4) only the fixed-count, equal-length path.selected_attention_supported()says which shapes it takes: query heads per key-value head, head dim and block size powers of 2 of at least 16deepspeed/models/minimax_m3_vl/block_sparse_attention.py(new)deepspeed/models/minimax_m3_vl/attention.py(new)DeepSpeedMiniMaxM3VLAttentionkeeps the source module's parameters and attribute names and changes onlyforward: projections, QK-norms and partial rotary as in transformers, then the indexer runindex_query_chunkrows at a time (same selection,[batch, 4, 2048, S]scores instead of[batch, 4, S, S]), then the attention.kernel="auto"(default),"triton"or"torch". Decoding with a cache and calls with an attention mask run the stock forward unchanged (a warning is logged once for the mask case). Withset_context_parallel_group(group), each rank holds consecutive equal chunks of one sequence; the 4 key-value heads and the indexer key are all-gathered, and their gradients reduce-scattered back.DeepSpeedMiniMaxM3VLDenseAttentiondoes the same for the 3 dense layers (replace_attention(..., dense=True))deepspeed/models/minimax_m3_vl/index_kernel.py(new)index_block_max(q, keys, positions, block_size): each query's maximum score per key block, causal by position,-inffor a block with no visible key. A program takes 128 queries of one index head and 8 key blocks;tl.doton the bf16/fp16 inputs with float32 accumulation (exact products, as the float32 matmul), mask, block maximum, store; blocks after every query of the tile are stored as-infwithout computing. Output[batch, heads, queries, blocks]float32 (128 MiB at 16,384 x 512 x 4 heads) instead of the 2 GiB of float32 scores per 2,048-query chunk.select_blocks(..., use_kernel=True)uses it for all local queries at once when the inputs are bf16/fp16 on an accelerator with Triton (kernelother than"torch"); otherwise the float32 matmul runs, with autocast disabled so it stays float32 under the engine's bf16torch_autocastdeepspeed/models/minimax_m3_vl/__init__.py,deepspeed/models/__init__.py(new)import deepspeeddoes not importdeepspeed.models.deepspeed/models/__init__.pyis byte-identical to #8659'sdocs/code-docs/source/models/minimax_m3_vl.rst(new),docs/code-docs/source/index.rstTHIRD_PARTY_NOTICES.md,scripts/check-license.py,setup.pycheck-licenseacceptsSPDX-License-Identifier: Apache-2.0 AND MIT;license_filesships the notices file in the wheel. Thecheck-license.pyandsetup.pyhunks are identical to #8659'stests/unit/v1/models/test_minimax_m3_vl.py(new)Size: about 990 added lines under
deepspeed/(361 of them the Triton kernels), so "High" by the checklist's linecount. All of it is in a new package that nothing else imports.
Measured
One attention call at MiniMax-M3's shapes, one H200, bf16
64 query heads on 4 key-value heads, head dim 128, 16 blocks of 128 keys per query, batch 1. Mean of the timed calls
after warm-up (
deepspeed-500b-study/minimax-m3-sparse-kernel/tools/kernel_bench.py). Error =||a - b|| / ||b||against float32, for out / dQ / dK / dV.Every error is about one bf16 rounding (2^-9 = 1.95e-3). The PyTorch path's errors are the same size (2.3-2.4e-3).
Full model, 4 nodes of 8 H200
MiniMax-M3 text model (60 layers, 426B parameters), real checkpoint, PG-19, 32 sequences of 65,536 tokens per step,
ZeRO-3 + AutoEP (expert parallel 8), sequence split over 4 GPUs, bf16, fp32 master weights and Adam states with 75%
of the optimizer on the CPU, full activation recompute. Same nodes, mean of steps 3-10 of each run:
These runs used the same module and kernel code before it was packaged into this PR (differences: the Triton import
guard, the device context, formatting, and the fix for selections that are not a power of 2, see Tests). On 1 node
(8 layers) the two paths gave the same losses to 6 digits and gradient norms within 0.03%.
Full model against Megatron-LM, 4 nodes of 8 H200 (2026-10-14 and 2026-10-15)
Later runs of the full model with this code and the index kernel: real checkpoint, PG-19, 32 sequences of 65,536
tokens per step, ZeRO-3 + AutoEP (expert parallel 8), each sequence over 2 GPUs, fp32 master weights and Adam states
with 80% of the optimizer on the CPU, full activation recompute. Megatron-LM: Megatron-FSDP, context parallel 8,
expert parallel 8, 80% of the optimizer on the CPU.
Mean loss over the 23 steps of the same-job runs (first run of each): 1.7438 DeepSpeed, 1.7345 Megatron-LM. The DeepSpeed tree
of these runs reached the index kernel through an earlier option name (
index_scores="fused") and also had theZeRO-3 pinned copy-back and fused CPU Adam changes (separate PRs). On one node (first 4 layers), master plus
this PR gives the same loss at every step as that tree (9.30 vs 9.23 s per step).
Tests
Command, from
tests/(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):
Result: 14 passed in 163 s. After the autocast fix (2026-10-13): 15 passed; the new
autocast test fails without the fix. With the indexer kernel: 18 passed in 156 s. On master
5f266e26d(2026-10-15): 18 passed in 131 s; with #8659 on the same master: the twofiles' tests together 32 passed.
References are independent of the code under test: dense masked attention written out in float32, and the stock
transformers model.
test_matches_dense_reference_float32(chunk 64 and 1,000), CPU-1slotstest_matches_dense_reference_bf16, CUDAtest_selected_attention_matches_dense_reference(203/203 and 256/1,000 tokens with 4 blocks; 256/1,000 with 3 blocks)test_key_gradients_summed_over_every_query_keep_float32_accuracy(torch, triton)test_replacement_matches_transformers_model, CPUtest_replace_keeps_names_and_runs_stock_forward_with_cache_or_mask, CPUTestMiniMaxM3AttentionZeroStage3(2 ranks)test_auto_kernel_runs_triton_for_bf16_on_gpukernel="auto"silently taking the slow path for bf16 on a GPU (attention and, since 2026-10-13, the indexer kernel: 2 calls each). It also caught a bug in the dK/dV query-list kernel:tl.arangeover the selected-block count failed to compile when the count was not a power of 2 (3 here). With MiniMax-M3's 16 blocks of 128 keys this happens for sequences of 257 to 1,920 tokens, the lengths with 3, 5-7 or 9-15 blocks. Fixed by rounding the range up to a power of 2 and masking the extra columnsTestMiniMaxM3AttentionContextParallel(2 ranks; torch, triton)test_index_block_max_matches_reference(queries from position 0 and 700; 1,000 keys, blocks of 128)-inftest_index_kernel_selects_the_float32_blockstest_block_selection_ignores_autocast, CUDAtorch_autocast): found in a 4-node MiniMax-M3 profile, where the score matmul, the mask and the block maxima ran in bf16 (3,648 bf16 GEMMs and bf16 max reductions per step on one rank).select_blocksnow computes the scores with autocast disabled. 2,048 tokens, 128 blocks per query, 3 selected; fails without the fixpre-commit run --filespasses on every changed file.Compatibility
kernel="auto"uses the PyTorch path whenget_accelerator().is_triton_supported()is false; the Triton launch sets the device withtorch.cuda.device(#ignore-cuda), as master's other Triton ops dotransformers.MiniMaxM3VLForCausalLM(transformers 5.15.1)AI assistance
This PR was written with AI assistance (Claude).
🤖 Generated with Claude Code