perf(models): DSA sparse prefill for DeepSeek-V3.2 and GLM-MoE-DSA
メンテナーはふだん 1 日以内に返信
まだ誰も着手していません。
評価
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 初心者へのやさしさ
- 6/100
- issue の種類
- 機能追加
- 明瞭さ
- おおむね明確
- 活発さ
- 活発
調査の方向性
Start in src/models/deepseek_v32_indexer.rs (indexer_top_indices) and the l > 1 branch of src/models/deepseek_v32.rs, then read mla/stats.rs. The issue is blocked by #3178, so confirm that lands first. Done means the listed src/lib/mlxcel-core/src/ and deepseek_v32_indexer_tests.rs tests pass, including the planted-keys test past 128k.
索引モデルが issue の本文から書いたものです。
説明
Summary
DeepSeek-V3.2 (deepseek_v32) and GLM-MoE-DSA (glm_moe_dsa, built on the same model) prefill long prompts by computing attention over every cached key and masking all but the indexer's top-k to -inf. The indexer itself materializes a [b, index_n_heads, s, kv_len] score tensor and reduces it over heads in one sum_axis. Upstream mlx-lm replaced both: sparse prefill gathers only each query's top-k latent rows, the top-k is computed one key block at a time with a running merge, a fused Metal kernel runs the gathered attention without materializing the gather, and the indexer head sum is a compiled, head-ordered accumulation. This issue ports all four for single-sequence prefill and keeps every other path unchanged.
Blocked by #3178: DeepSeek-V3.2 fp16 output degrades past 4096 tokens of context (leading suspect: YaRN RoPE not applied). Every acceptance number here is measured at 16k to 160k tokens, where the reference is currently broken, so this work starts after #3178 lands.
Upstream reference
All in ml-explore/mlx-lm; helpers now live in https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/layers/attention.py after the directory move (ml-explore/mlx-lm#2082), the kernel in https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/kernels/sparse_mla.py, the call sites in https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/deepseek_v32/layers.py and https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/glm_moe_dsa/layers.py.
- ml-explore/mlx-lm#1997 (
dc2012b, GLM) and ml-explore/mlx-lm#2013 (1f7057c, DeepSeek-V3.2, shareddsa.py): whensparse_prefillandB == 1andL > 1and the latent cache holds at leastsparse_prefill_min_context(16384) rows, computeblocked_topkand runsparse_attention: absorbed form,kv_full = concat(kv_latent, k_pe)([N, 576]),gathered = kv_full[topk]([L, K, 576], shared by all heads), scores in float32 timesscale, invalid gathered positions (by the mask) set to-inf, softmax,probs @ gathered[..., :kv_lora_rank], thenunembed_outando_proj. Queries are processed in blocks ofSPARSE_QUERY_BLOCK = 1024.blocked_topkscores key blocks of 4096, applies the mask per block, and keeps a running top-index_topkby concatenating the previous best values and indices with the new block and re-partitioning; it returnsNonewhenkv_len <= index_topk(dense path). - ml-explore/mlx-lm#2027 (
56230fa):sparse_mla_attention(q, q_pe, kv, k_pe, idx, scale)in one Metal kernel: one threadgroup per (query, 16 heads), keys in blocks of32 * WNselected indices read by index straight from the latent and rope caches, online softmax in float32, only the[heads, L, r]latent output written; index-1is skipped (the caller writes-1where the mask rejects a gathered key). Two variants:simdgroup_matrix(every Apple GPU) andtensor_ops(Metal 4matmul2d, GPU generation 17+ / 18+ for p GPUs, macOS 26.2+).supports()requires bf16 or f16, matching dtypes, heads a multiple of 16 and a latent width the simdgroups can split. With the kernel the sparse path starts as soon as the indexer selects (sparse_prefill_fused_min_context = 0). - ml-explore/mlx-lm#2046 (
1bf8da0):head_sum(scores, weights)ismx.compile(shapeless=True)over per-head slices, accumulatingrelu(score_h) * weight_hin head order, so it equals the stock ordered sum bit for bit (tested on CPU and GPU, bf16/f16/f32). The indexer uses it fors > 1;blocked_topkalso uses it, withmx.dependsso only one block's scores are alive at a time. The upstream source still says "remove once ml-explore/mlx#3784 is merged".
ml-explore/mlx#3784 is the defect class this guards against: mx.sum over a non-last axis returned zeros for tensors of 2^34 elements and partially zeroed output above that (a 32-bit grid overflow in the strided reduction). The indexer's head reduction hits that size at DeepSeek-V3.2's 64 indexer heads with a 2048-token prefill chunk behind 131072 keys, which is the "corrupt top-k past 128k" failure. It was fixed by ml-explore/mlx#4437 (merge 9cb9c06f, 2026-10-07), and mlxcel's pin fc344c98 contains it (121 commits ahead, 0 behind, per the GitHub compare API). The related overflow fixes ml-explore/mlx#4540 (split-view data_size) and ml-explore/mlx#4717 (softmax / layer_norm grid) are also in the pin. Nothing in mlxcel tests any of this.
Current mlxcel behavior
src/models/deepseek_v32.rs:504-530: thel > 1branch builds the folded mask withapply_sparse_prefill_mask(:803), which scatters 1.0 into a[b, 1, s, kv_len]float32 buffer at the top-k indices and thresholds it, then runsmlxcel_core::mla::rope_folded_attention(src/lib/mlxcel-core/src/mla/prefill.rs:75) over allkv_lenkeys. Cost and memory stay dense inkv_len.src/models/deepseek_v32_indexer.rs:199indexer_top_indices:matmul(q, k^T)into[b, n_heads, s, kv_len],relu, multiply by the scaled weights,sum_axis(&scores, 1, true)(:227), add the additive mask,argpartitionover the whole key axis (:237). Called fromdeepseek_v32.rs:476-478for prefill and:719for batched decode.deepseek_v32.rs:425-443: a quantized latent window (#3163, #3189) is dequantized withinto_dense()for every multi-token step, and:446-454slices the indexer key off the shared cache buffer (kv_latentthen the indexer key, concatenated on the feature axis). The causal fallback mask is additive (0/-inf,:455-470).src/models/glm_moe_dsa.rs:168to_dsv32_argsbuilds aDeepSeekV32Model, so GLM-MoE-DSA runs the same attention and indexer code.- Fused-kernel pattern to follow:
src/lib/mlxcelverse/kernels/mla_absorbed_decode.{cpp,h}(registered insrc/lib/mlxcelverse/kernels/CMakeLists.txt:50,64) behindffi::mla_absorbed_decode_fused, wrapped byfused_absorbed_decodeinsrc/lib/mlxcel-core/src/mla/decode.rs:129with a shape/dtype support check and anOptionfallback. (CLAUDE.md still namessrc/lib/mlx-cpp/; the kernels are undersrc/lib/mlxcelverse/now.) - Dispatch counters:
MlaDecodePathinsrc/lib/mlxcel-core/src/mla/stats.rs(absorbed_prefill,absorbed_fused, ...), printed byMLXCEL_TRACE_MLA_STATS=1.
Required changes
- Head sum (
src/lib/mlxcel-core/cpp/mlx_cxx_bridge.cppplus a binding insrc/lib/mlxcel-core/src/lib.rs): addcompiled_indexer_head_sum(scores [b, H, s, n], weights [b, H, s, 1]) -> [b, 1, s, n], a shapelessmlx::core::compileover the H slices that accumulatesmaximum(score_h, 0) * weight_hin head order, in the input dtype. Use it inindexer_top_indicesfors > 1; keep the existingrelu, multiply andsum_axisfors == 1(decode), as upstream does. - Blocked top-k (
src/models/deepseek_v32_indexer.rs): addindexer_top_indices_blocked(q, k, weights, mask, n_heads, softmax_scale, index_topk, block = 4096)that scoresk[.., s0..s1, ..]per block with the head sum, applies the mask slice (additive:scores + mask[.., s0..s1]), and merges into a running best ofindex_topkvalues and absolute indices withargpartitionoverconcat(best, block). Evaluate each block before scoring the next so one block's[b, H, s, block]is alive at a time. ReturnsNonewhenkv_len <= index_topk, like the dense function. It selects the same key set asindexer_top_indicesup to the order of equal scores. - Composed sparse attention (new
src/models/dsa_sparse_prefill.rs):sparse_prefill_attention(q_absorbed [1, H, L, r], q_pe [1, H, L, p], kv_latent [1, 1, N, r], k_pe [1, 1, N, p], topk [1, 1, L, K], mask: Option<additive [.., L, N]>, scale) -> latent_out [1, H, L, r], following upstreamsparse_attention: query blocks of 1024, gatherconcat(kv_latent, k_pe)rows bytopk, float32 scores, a gathered position is valid whentake_along_axis(mask, topk)is finite (the mask is additive here, unlike upstream's boolean one), invalid scores to-inf, softmax, multiply by the latent columns. The caller appliesunembed_outand the output projection. Name the two callers in// Used by: DeepSeekV32Model, GlmMoeDsaModel (via DeepSeekV32Model). - Fused kernel (new
src/lib/mlxcelverse/kernels/sparse_mla_prefill.{cpp,h}with Metal source, registered in the kernelsCMakeLists.txt, FFIsparse_mla_prefill_fused, wrapperfused_sparse_prefillin newsrc/lib/mlxcel-core/src/mla/sparse_prefill.rsreturningOption): a port of upstream'ssimdgroup_matrixvariant with the same contract (index-1skipped, float32 online softmax, output in the input dtype, bf16 / f16 only, heads a multiple of 16). The composed path from step 3 writes-1for invalid gathered indices before calling it, and falls back to step 3 when the wrapper returnsNone. Thetensor_opsvariant is optional; if ported it must gate onhw.has_neural_accelerator && hw.macos_supports_naper CLAUDE.md, not on the GPU architecture string alone. Attribute the port per CLAUDE.md "Third-party attribution" (MIT, ml-explore/mlx-lm) in the file header andNOTICE. - Dispatch (
src/models/deepseek_v32.rs, thel > 1branch): take the sparse path when all hold: batch 1,l > 1, the indexer returned indices, the latent window is dense afterinto_dense()(quantized windows dequantize first, so they qualify; the sparse path reads the dequantized f16 latent exactly as the masked path does today), andkv_len >= threshold, where threshold is 0 whenfused_sparse_prefillsupports the shapes and 16384 otherwise (upstream's two defaults). Sparse eligibility overrides theuse_absorbed_mlacost model (src/lib/mlxcel-core/src/mla/mod.rs:343): the sparse path always runs in absorbed form, as upstream's does. That model compares dense absorbed against dense decompressed cost over allkv_lenkeys and, for DeepSeek-V3.2's rank 512 and head dims 128 + 128, picks decompressed for any step wider than about 170 tokens, so a 2048-token prefill chunk is decompressed today; the gather makes the sparse cost proportional toindex_topk, notkv_len, so the model does not apply. Computeq_absorbed = embed_q(q_nope)on the sparse path regardless of the model's answer. Use blocked top-k on the sparse path. Batches above 1, decode and short contexts keep today's masked path, with the cost model choosing absorbed or decompressed exactly as now. - Kill switches and counters:
MLXCEL_DSA_SPARSE_PREFILL=0forces the masked dense path,MLXCEL_DSA_SPARSE_PREFILL_FUSED=0forces the composed sparse path; both are read once per process. AddMlaDecodePath::SparsePrefillandMlaDecodePath::SparsePrefillFusedtomla/stats.rs(labelssparse_prefill,sparse_prefill_fused, included inMLA_DECODE_PATHSand the summary) and record them on each step. - CUDA: out of scope for the fused kernel (upstream ships Metal only); the composed path from step 3 is plain MLX ops and runs on CUDA as is. If a CUDA port of the kernel is added later, its
template_argsmust name the dtype of every input whose dtype can vary ({"T", q.dtype()}at least), per CLAUDE.md "JIT kernel cache keys" andmake verify-kernel-dtype-keys.
Acceptance criteria
-
src/lib/mlxcel-core/src/tests (beside the binding):indexer_head_sum_matches_ordered_opsassertscompiled_indexer_head_sumequals the head-orderedrelu * wsum bit for bit for(1, 8, 33, 300)bf16,(2, 8, 17, 129)bf16,(1, 8, 33, 300)f16 and(1, 8, 5, 1000)f32, all through one compiled graph (shape changes between calls). -
src/models/deepseek_v32_indexer_tests.rs(new, beside the code, wired with#[cfg(test)] #[path]from the indexer module, which is itself#[path]-mounted atdeepseek_v32.rs:36):blocked_topk_matches_dense_selectioncompares the selected key sets of the blocked and dense functions forkv_lenin {4097, 9000} with a causal additive mask. - Same file, the head-sum regression past 128k:
blocked_topk_finds_planted_keys_past_128kbuildskv_len = 140000,s = 256, 64 heads, head dim 128 (about 36 MB of keys), plantsindex_topkkeys at positions above 131072 whose scores dominate by construction, and asserts every planted position is selected. It must run insidemake verify-teston a 128 GB machine. - Same file,
#[ignore = "needs ~40 GB"]dense_head_reduction_survives_2_pow_34_elements: scores[1, 64, 2048, 131072]f16 through the denseindexer_top_indicesagainst the blocked result; documents ml-explore/mlx#3784 / ml-explore/mlx#4437 and fails if a pin bump reintroduces the reduction overflow. Run it by hand on the validation host and record the result in the PR. -
src/models/dsa_sparse_prefill_tests.rs:sparse_prefill_matches_masked_denseruns the composed sparse attention and today's maskedrope_folded_attentionon the same random inputs (H 16, r 512, p 64, N 5000, K 2048, L 1500 so the query blocking runs) and asserts the latent outputs agree within 2e-2 (f16) and 1e-4 (f32); one case with masked-out gathered positions. -
src/lib/mlxcel-core/src/mla/sparse_prefill_tests.rs:fused_sparse_prefill_matches_reference(upstream's test shape: H 16, L 7, N 300, K 100, r 512, p 64, 10%-1entries, bf16 and f16, tolerance 2e-2) andunsupported_shapes_return_none(r 32, f32, H 8, p 0). - A dispatch test asserting that a B=1 prefill above the threshold records
sparse_prefill_fused(orsparse_prefillwith the fused switch off) even at a width whereuse_absorbed_mlareturns false, thatMLXCEL_DSA_SPARSE_PREFILL=0records whatever the cost model picks today (decompressedorabsorbed_prefill) and no sparse counter, and that B=2 never takes the sparse path. -
make verify-kernel-dtype-keyspasses. - Wired into the real flow:
mlxcel generate,mlxcel-serverchunked prefill andexamples/logit_traceall reach the sparse path on DeepSeek-V3.2 and GLM-MoE-DSA with no flag.
Validation
Checkpoints: mlx-community/DeepSeek-V3.2-4bit (378 GB) and mlx-community/GLM-5-4bit (419 GB) or mlx-community/GLM-5.2-4bit (418 GB, which also exercises #2964's shared indexer if that has landed). Both need the 512 GB host (the M3 Ultra #3178 was measured on).
This changes attention arithmetic and selection, so follow CLAUDE.md "Changes that move the numbers" and the four conditions in docs/benchmarks.md ("Judging a change that moves the numbers"):
make verify-test
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
make verify-kernel-dtype-keys
cargo build --release --features metal,accelerate --example logit_trace
# Context past the branch threshold and past 128k. The context pass runs in
# 2048-token forwards (the generator's prefill shape, and the width the changed
# code runs at); the traced rows then decode behind that cache.
for ctx in 16384 65536 135000; do
MLXCEL_TRACE_BATCH_ROWS=1 MLXCEL_TRACE_PREFILL_CHUNK=2048 MLXCEL_TRACE_MLA_STATS=1 \
./target/release/examples/logit_trace models/DeepSeek-V3.2-4bit corpus.txt 64 1 8 $ctx > sparse-$ctx.tsv
MLXCEL_DSA_SPARSE_PREFILL=0 MLXCEL_TRACE_BATCH_ROWS=1 MLXCEL_TRACE_PREFILL_CHUNK=2048 MLXCEL_TRACE_MLA_STATS=1 \
./target/release/examples/logit_trace models/DeepSeek-V3.2-4bit corpus.txt 64 1 8 $ctx > dense-$ctx.tsv
python3 scripts/compare_logit_traces.py dense-$ctx.tsv sparse-$ctx.tsv --decided 2
done
MLXCEL_TRACE_PREFILL_CHUNK needs MLXCEL_TRACE_BATCH_ROWS (see the usage comment in examples/logit_trace.rs); without it the context pass is one forward over the whole context, whose [1, 64, L, L] indexer scores alone exceed any host's memory at 65k (about 550 GB in f16). The traced rows are width-one decodes, so the comparison measures what the sparse prefill left in the cache, which is the effect that matters; time the context pass from the harness's stderr for throughput, or with mlxcel generate on a prompt of the same length. Optionally add scripts/mlx_lm_logit_trace.py (same arguments) as an mlx-lm main reference arm. Report per context: decided-position disagreement of sparse against the masked dense arm (the arm with the change switched off), the # mla_paths line of each arm proving which branch ran, perplexity of both arms, and prefill throughput (tok/s) and peak memory for dense, composed sparse and fused sparse at 16k, 64k and 128k+. Repeat on the GLM checkpoint at one context. A pass is no increase in decided-position disagreement over the dense arm, the stats line showing sparse_prefill_fused on the sparse arm and no sparse counter on the dense arm, and higher prefill tok/s for the fused arm from the threshold up.
Related
Blocked by #3178. Related: #2964 (GLM-5.2 IndexShare, cross-layer indexer sharing, ml-explore/mlx-lm#1410; do not duplicate it here), #3231 (Mistral Large 4, another MLA + DSA family that should reuse this path), #3071 (dense rope-score tensor in MLA prefill), #3121 (fused absorbed decode kernel, the pattern for step 4), #3163 and #3189 (quantized MLA latent), #2965 (GLM-5.3-Flash). Upstream: ml-explore/mlx-lm#1997, ml-explore/mlx-lm#2013, ml-explore/mlx-lm#2027, ml-explore/mlx-lm#2046, ml-explore/mlx#3784, ml-explore/mlx#4437.
- 主要言語
- Rust
- スター
- 505
- フォーク
- 81
- 平均マージ
- 14時間 2分
- マージ済み PR(30日)
- 448
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
lablup/mlxcel のほかの issue
-
area:core priority:high status:ready type:security
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
メンテナーはふだん 1 日以内に返信
-
priority:medium status:ready type:security
難易度 4/5 3〜5日 初心者へのやさしさ 45/100
メンテナーはふだん 1 日以内に返信
-
area:models modeltype:text priority:medium status:in-progress type:bug
難易度 4/5 3〜5日 初心者へのやさしさ 57/100
メンテナーはふだん 1 日以内に返信
-
area:models priority:low status:ready type:test
難易度 4/5 3〜5日 初心者へのやさしさ 48/100
メンテナーはふだん 1 日以内に返信
-
area:models modeltype:omni priority:medium status:ready type:bug
難易度 4/5 3〜5日 初心者へのやさしさ 48/100
メンテナーはふだん 1 日以内に返信
似ている issue
-
psmux-resurrect: restoring a session with a numeric name puts its windows into the wrong session (`new-window -t 4` is read as window 4)対応中かも @ealwanlee が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 88/100
psmux/psmux-plugins#47 ·
-
Link Checker Reportオープンautomated issue report
難易度 1/5 1時間未満 初心者へのやさしさ 76/100
ratatui/awesome-ratatui#598 ·
メンテナーはふだん 1 日以内に返信
-
release
難易度 1/5 1時間未満 初心者へのやさしさ 75/100
github/gh-aw-mcpg#17603 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
-
C-Bug S-Needs-Triage
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
bevyengine/bevy#26718 ·
メンテナーはふだん 2 日以内に返信