perf(models): DSA sparse prefill for DeepSeek-V3.2 and GLM-MoE-DSA

Aperta
#3,240 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
6/100
Tipo di issue
Funzionalità
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
cpp, rust

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

arch:moe area:core area:inference area:models modelsize:xlarge modeltype:text priority:medium status:blocked type:performance

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, shared dsa.py): when sparse_prefill and B == 1 and L > 1 and the latent cache holds at least sparse_prefill_min_context (16384) rows, compute blocked_topk and run sparse_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 times scale, invalid gathered positions (by the mask) set to -inf, softmax, probs @ gathered[..., :kv_lora_rank], then unembed_out and o_proj. Queries are processed in blocks of SPARSE_QUERY_BLOCK = 1024. blocked_topk scores key blocks of 4096, applies the mask per block, and keeps a running top-index_topk by concatenating the previous best values and indices with the new block and re-partitioning; it returns None when kv_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 of 32 * WN selected indices read by index straight from the latent and rope caches, online softmax in float32, only the [heads, L, r] latent output written; index -1 is skipped (the caller writes -1 where the mask rejects a gathered key). Two variants: simdgroup_matrix (every Apple GPU) and tensor_ops (Metal 4 matmul2d, 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) is mx.compile(shapeless=True) over per-head slices, accumulating relu(score_h) * weight_h in head order, so it equals the stock ordered sum bit for bit (tested on CPU and GPU, bf16/f16/f32). The indexer uses it for s > 1; blocked_topk also uses it, with mx.depends so 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: the l > 1 branch builds the folded mask with apply_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 runs mlxcel_core::mla::rope_folded_attention (src/lib/mlxcel-core/src/mla/prefill.rs:75) over all kv_len keys. Cost and memory stay dense in kv_len.
  • src/models/deepseek_v32_indexer.rs:199 indexer_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, argpartition over the whole key axis (:237). Called from deepseek_v32.rs:476-478 for prefill and :719 for batched decode.
  • deepseek_v32.rs:425-443: a quantized latent window (#3163, #3189) is dequantized with into_dense() for every multi-token step, and :446-454 slices the indexer key off the shared cache buffer (kv_latent then the indexer key, concatenated on the feature axis). The causal fallback mask is additive (0 / -inf, :455-470).
  • src/models/glm_moe_dsa.rs:168 to_dsv32_args builds a DeepSeekV32Model, 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 in src/lib/mlxcelverse/kernels/CMakeLists.txt:50,64) behind ffi::mla_absorbed_decode_fused, wrapped by fused_absorbed_decode in src/lib/mlxcel-core/src/mla/decode.rs:129 with a shape/dtype support check and an Option fallback. (CLAUDE.md still names src/lib/mlx-cpp/; the kernels are under src/lib/mlxcelverse/ now.)
  • Dispatch counters: MlaDecodePath in src/lib/mlxcel-core/src/mla/stats.rs (absorbed_prefill, absorbed_fused, ...), printed by MLXCEL_TRACE_MLA_STATS=1.

Required changes

  1. Head sum (src/lib/mlxcel-core/cpp/mlx_cxx_bridge.cpp plus a binding in src/lib/mlxcel-core/src/lib.rs): add compiled_indexer_head_sum(scores [b, H, s, n], weights [b, H, s, 1]) -> [b, 1, s, n], a shapeless mlx::core::compile over the H slices that accumulates maximum(score_h, 0) * weight_h in head order, in the input dtype. Use it in indexer_top_indices for s > 1; keep the existing relu, multiply and sum_axis for s == 1 (decode), as upstream does.
  2. Blocked top-k (src/models/deepseek_v32_indexer.rs): add indexer_top_indices_blocked(q, k, weights, mask, n_heads, softmax_scale, index_topk, block = 4096) that scores k[.., s0..s1, ..] per block with the head sum, applies the mask slice (additive: scores + mask[.., s0..s1]), and merges into a running best of index_topk values and absolute indices with argpartition over concat(best, block). Evaluate each block before scoring the next so one block's [b, H, s, block] is alive at a time. Returns None when kv_len <= index_topk, like the dense function. It selects the same key set as indexer_top_indices up to the order of equal scores.
  3. 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 upstream sparse_attention: query blocks of 1024, gather concat(kv_latent, k_pe) rows by topk, float32 scores, a gathered position is valid when take_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 applies unembed_out and the output projection. Name the two callers in // Used by: DeepSeekV32Model, GlmMoeDsaModel (via DeepSeekV32Model).
  4. Fused kernel (new src/lib/mlxcelverse/kernels/sparse_mla_prefill.{cpp,h} with Metal source, registered in the kernels CMakeLists.txt, FFI sparse_mla_prefill_fused, wrapper fused_sparse_prefill in new src/lib/mlxcel-core/src/mla/sparse_prefill.rs returning Option): a port of upstream's simdgroup_matrix variant with the same contract (index -1 skipped, float32 online softmax, output in the input dtype, bf16 / f16 only, heads a multiple of 16). The composed path from step 3 writes -1 for invalid gathered indices before calling it, and falls back to step 3 when the wrapper returns None. The tensor_ops variant is optional; if ported it must gate on hw.has_neural_accelerator && hw.macos_supports_na per 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 and NOTICE.
  5. Dispatch (src/models/deepseek_v32.rs, the l > 1 branch): take the sparse path when all hold: batch 1, l > 1, the indexer returned indices, the latent window is dense after into_dense() (quantized windows dequantize first, so they qualify; the sparse path reads the dequantized f16 latent exactly as the masked path does today), and kv_len >= threshold, where threshold is 0 when fused_sparse_prefill supports the shapes and 16384 otherwise (upstream's two defaults). Sparse eligibility overrides the use_absorbed_mla cost 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 all kv_len keys 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 to index_topk, not kv_len, so the model does not apply. Compute q_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.
  6. Kill switches and counters: MLXCEL_DSA_SPARSE_PREFILL=0 forces the masked dense path, MLXCEL_DSA_SPARSE_PREFILL_FUSED=0 forces the composed sparse path; both are read once per process. Add MlaDecodePath::SparsePrefill and MlaDecodePath::SparsePrefillFused to mla/stats.rs (labels sparse_prefill, sparse_prefill_fused, included in MLA_DECODE_PATHS and the summary) and record them on each step.
  7. 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_args must name the dtype of every input whose dtype can vary ({"T", q.dtype()} at least), per CLAUDE.md "JIT kernel cache keys" and make verify-kernel-dtype-keys.

Acceptance criteria

  • src/lib/mlxcel-core/src/ tests (beside the binding): indexer_head_sum_matches_ordered_ops asserts compiled_indexer_head_sum equals the head-ordered relu * w sum 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 at deepseek_v32.rs:36): blocked_topk_matches_dense_selection compares the selected key sets of the blocked and dense functions for kv_len in {4097, 9000} with a causal additive mask.
  • Same file, the head-sum regression past 128k: blocked_topk_finds_planted_keys_past_128k builds kv_len = 140000, s = 256, 64 heads, head dim 128 (about 36 MB of keys), plants index_topk keys at positions above 131072 whose scores dominate by construction, and asserts every planted position is selected. It must run inside make verify-test on 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 dense indexer_top_indices against 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_dense runs the composed sparse attention and today's masked rope_folded_attention on 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% -1 entries, bf16 and f16, tolerance 2e-2) and unsupported_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 (or sparse_prefill with the fused switch off) even at a width where use_absorbed_mla returns false, that MLXCEL_DSA_SPARSE_PREFILL=0 records whatever the cost model picks today (decompressed or absorbed_prefill) and no sparse counter, and that B=2 never takes the sparse path.
  • make verify-kernel-dtype-keys passes.
  • Wired into the real flow: mlxcel generate, mlxcel-server chunked prefill and examples/logit_trace all 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.

Lingua principale
Rust
Stelle
505
Fork
81
Merge medio
14h 2m
PR unite (30g)
448

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di lablup/mlxcel

Tutte le issue di lablup/mlxcel

Issue simili

Altre issue su Rust

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.