Repository navigation
Add deepspeed.models.glm_moe_dsa: TileLang sparse attention for GLM-5.2 - #8659
Conversation
|
Can the model integration be separated from the TileLang backend, so DeepSpeedGlmMoeDsaAttention owns the model semantics while sparse MLA/indexer implementations are backend-pluggable? |
7baad04 to
e78ac54
Compare
tohtana
left a comment
There was a problem hiding this comment.
Hi @pengdurice,
Thank you for the optimization! This is a significant improvement.
The followings are not about code, but can we consider addressing them?
-
The order in the document (
replace_attention()before
deepspeed.initialize()), every local process can warm on GPU 0. Shouldn't we
bind warm-up on the intended local device by deferring the call? -
indexer_fwd.py,sparse_mla_fwd.py, andsparse_mla_bwd.pyare adapted from TileLang/THUDM sources but retain only DeepSpeed's Apache-2.0 header. Please follow AutoEP's existing header pattern:
add a TileLang section to THIRD_PARTY_NOTICES.md,
listing these files and their source revisions, with the upstream copyright
and full MIT license from those revisions. Preserve any applicable
THUDM/slime notices too. Each derived file should retain the upstream
copyright and reference that notice. Following AutoEP's combined-license
convention, use an SPDX expression reflecting the actual sources (e.g.
Apache-2.0 AND MIT), and updatescripts/check-license.pyif needed to
accept it. Please also make sure that the notice is included in source and
wheel distributions.
I also found some issues in the code:
- Attention outputs:
output_attentions=Truesilently returns
attentions=()after replacement. Can we explicitly reject or warn if it's unsupported? - Masks: Nontrivial
attention_maskvalues are silently ignored. Can we
reject unsupported padding/packing masks? - Dimensions: Widths 1 and 2 pass validation but violate the backward
kernel's requirement (it must be mulltiple of four). The results might be incorrect.
I have a question about warmup. Backward kernels are precompiled for a specific sequence length (128 tokens), but the precompiled kernel won't be used for the actual training. As this PR says "Sequence lengths are dynamic in the kernels, so the short warm-up builds exactly the kernels that training uses," I wonder if it is not intended. I still agree that it is still useful to avoid OOM, though.
…ing GLM-5.2 Signed-off-by: pengdurice <pengduhit@gmail.com>
e78ac54 to
df9412f
Compare
|
Hi @pengdurice @tohtana I have some thoughts about platform agnostic kernel language integration. We are thinking maybe using We have an issue discussing this and hope to get your inputs. If we could reach an consensus among accelerator owners, maybe we can add it to 27Q1 plan. Also @PKUWZP @sfc-gh-truwase for discussion. |
Hi @delock , thank you so much for this review, yes. Let me take a look at the issue and @VenusTZZ 's PR mentioned in that issue and come back to you. I totally get you that some gating mechanism is needed due to universal portability issues across accelerators. |
@delock , should we review this PR as is and add the op_builder later? Since it needs time for the other PRs to check in and careful design of TileLang probes. Thanks! |
Hi @pengdurice, yes we can review this PR as is. Refractory can be done later. Thanks! |
|
Also @tohtana for whether request for change could be resolved. |
tohtana
left a comment
There was a problem hiding this comment.
Hi @pengdurice,
Thank you for the update, this looks good now.
One remaining concern is that the CP could silently produce the wrong results when position_ids is not passed. But the injected module can't detect it as HF transformers generates and passes it to the modules in the model.
Currently we don't have a good solution, so let's leave it for now.
Add
deepspeed.models.glm_moe_dsa: TileLang sparse attention for training GLM-5.2Part of: #8672 (Q4 2026 roadmap), "Enable training of large scale models": "Test and verify support of SOTA
models" (PoC @pengdurice). Sibling: #8658 (MiniMax-M3).
Summary
scores and its attention mask are both dense
seq x seqtensors.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.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.
deepspeed/models/<family>/, for training code that belongs to one modelfamily.
Why a
deepspeed/models/folderSome 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'ssrc/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 onepreset file per model in
deepspeed/module_inject/auto_ep_presets/.The convention this PR starts:
deepspeed/models/, named after the model's folder intransformers.models. Here that isglm_moe_dsa. A reader goes from a Hugging Face model to itsDeepSpeed code without a lookup table.
the TileLang kernels in
kernels/and the replacement module inattention.py.deepspeed.initialize. Herethat is
replace_attention.import deepspeeddoes not importdeepspeed.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 PRsadd the same
deepspeed/models/__init__.pyand the same docs index entry, byte for byte, so they mergein either order without conflicts.
Problem
GLM-5.2 (transformers
glm_moe_dsa, DeepSeek Sparse Attention) cannot train at long sequence lengthson the stock transformers path, whatever DeepSpeed does about parameters and optimizer state:
GlmMoeDsaIndexer.forwardscores 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 atS = 32,768, for each layer, before the relu copy and the head-weighted sum.
GlmMoeDsaAttention.forwardthen turns the top-k indices into a dense[batch, 1, S, S]additivemask. 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.AttentionInterfacedoes not help. By the time theinterface 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:
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. Itimports nothing.
deepspeed/models/glm_moe_dsa/kernels/(new): the kernels. They are adapted from thedeepseek_v32examples 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.
sparse_mla_fwd.py-1indices masked; returns the output and the log-sum-expsparse_mla_bwd.pydqkernel and the atomically accumulateddkvkernel, postprocesssparse_mla.pysparse_mla(q, kv, indices, scale, d_v): thetorch.autograd.Functionaround the twoindexer_fwd.py[rows, keys]float32,-infoutside each row's windowindexer.pyselect_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], andindices [tokens, 1, topk]int32 with-1for unused slots.topkmust be a multiple of 64.deepspeed/models/glm_moe_dsa/attention.py(new):DeepSpeedGlmMoeDsaAttention(source)andreplace_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
forwardis different.Forward, step by step:
kv_b_proj.weight:q_nope . (W_kc kv) == (W_kc^T q_nope) . kv.sum_h w_h relu(scale q_h . k). The scale is folded into the weights, which is exact becauserelu is positively homogeneous.
sparse_mlaattends over the selected latent keys.kv_b_proj.weightmaps the output back to value space beforeo_proj.Layers of type
"shared"reuseprev_topk_indicesfrom the previous full layer, as the stockmodule does.
The module reads
kv_b_proj.weightas a tensor and never callskv_b_proj, so ZeRO-3 gets noforward 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 andbackward 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 theyalready must on the stock path.
Training only:
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 receiveindices from a layer of its own kind.
Constructor checks:
kv_lora_rankandqk_rope_head_dimare powers of two;index_topk % 64 == 0;replace_attentionchecks for TileLang first and raisesImportErrorwith the install command.Kernel warm-up. With
warm_up=True(the default), when the backward kernel uses 128 threads (headblocks 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_MEMORYon 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:
kernels/sparse_mla_bwd.pybackward_threads(heads_per_kv_group)picks the thread count for both thekernel 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 indocs/code-docs/source/index.rstthat lists every page inmodels/: 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:Copyright (c) Tile-AI.) andSPDX-License-Identifier: Apache-2.0 AND MIT, and point to a new TileLang section inTHIRD_PARTY_NOTICES.md(files, TileLang source paths and revisions, the slime revision they came through, the full MIT text).scripts/check-license.pyaccepts the expression.setup.pynow listsTHIRD_PARTY_NOTICES.mdinlicense_files; before, the notice was in neither the sdist nor the wheel (checked by building both).output_attentions=Truereturnsattentions=()NotImplementedError: the kernels never form attention weights.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.kv_lora_rankandqk_rope_head_dimmust be powers of two of at least 4 (the backward kernel splits the width into groups of 4).Two additions from running GLM-5.2 at scale:
faster per kernel at GLM-5.2's shapes on an H200, 34-40% more tokens per second in training.
deepspeed.models.glm_moe_dsa.set_context_parallel_group(group): everyrank 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 onlyimport 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 sameloss 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) or95% (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.
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:
layers of 256 experts (top-8). 21 layers run the indexer, 57 reuse its selection.
leaf_moduleon the AutoEP layer.layer inputs in host memory (
checkpoint_in_cpu). bf16 master weights and optimizer states.frozen.
NCCL_RUNTIME_CONNECT=0andNCCL_NVLS_ENABLE=0. With NCCL 2.27's default lazyconnection, 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.
Same setup with
OMP_NUM_THREADS=12for the CPU Adam optimizer, and DeepSpeed's wall-clock breakdowntimers 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.
How MFU is counted, per token:
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:
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.
leaf_moduleon the AutoEP layer,bf16 master weights and optimizer states, Hugging Face gradient checkpointing.
PG-19 books re-tokenized with the GLM-5.2 tokenizer, one book per row. Indexer frozen.
attention cost grows linearly with the token count, like the rest of the layer.
scores of one layer alone.
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.
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_sparse_mla_matches_reference(8 heads, 64 heads)sparse_mla, against the sparse softmax written out in float32, over a random causal selection with-1padding. 8 heads exercises the kernel's padding of heads to 16test_indexer_logits_and_selection_match_reference(8 and 32 index heads)-infexactly on the future keys.select_topkreturns 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 keytest_sparse_mla_at_glm52_sizesdqanddkvagainst the float32 reference on 256 random query rows. A row's output anddqdepend on that row alone;dkvis checked by sending a gradient into those rows onlytest_indexer_selection_at_glm52_sizesselect_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 outtest_replacement_matches_transformers_moduleGlmMoeDsaConfig, 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 selectiontest_replace_walks_the_model_and_keeps_parameter_namesreplace_attentionswaps every layer ofGlmMoeDsaForCausalLM, and the parameter names do not changeTestDsaAttentionZeroStage3(2 ranks, ZeRO-3,torch_adam)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 forwardtest_unsupported_inputs_raiseoutput_attentions=True, a padding mask and position ids that restart all raiseNotImplementedErrortest_kernel_widths_below_four_are_rejectedkv_lora_rankorqk_rope_head_dimbelow 4 raisesValueErrortest_first_forward_under_activation_checkpointingtest_warm_up_runs_on_the_input_device(2 GPUs)replace_attention, the warm-up allocates nothing on GPU 0 when the model runs on GPU 1TestDsaAttentionContextParallel(2 ranks)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 backwardcan hang in torch 2.8's
_grouped_mmwhen an expert receives no tokens.pre-commit run --filespasses on everychanged 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. #8658 is the sibling for MiniMax-M3 (another
family in the same
deepspeed/models/folder; both add the samedeepspeed/models/__init__.pyand docs entry,byte for byte).
Compatibility
TestDsaAttentionContextParallel; 38 and 78 layers at 65,536 tokensTestDsaAttentionZeroStage3replace_attentionraisesImportErrorwithout TileLangLater 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).