Why did DeepSeek Sparse Attention succeed?
· Pranay Kundu · 6 min read
DeepSeek Sparse Attention has gained a lot of traction as the go-to implementation for scaling attention and long context. Recently, the GLM team used DSA to compete with Claude Opus 4.5 successfully. So why is it successful?
DSA is a two-kernel pipeline for calculating attention. The first kernel is where the trick lies: the Lightning Indexer, which produces top-k global KV indices. We compute attention over a selected set of tokens rather than every token in the context.
How to read this post
We’ll understand DSA by mapping each term in the attention equation to the corresponding lines in the reference implementation. For each block: term in the equation → exact code → what it means.
Lightning Indexer
Compute index scores: ReLU → weighted head sum
The indexer ranks KV tokens and outputs top-k global KV token indices. These scores are pre-attention ranking signals. Index scores produce topk_indices: the candidate tokens to attend to for each query token.
The left-hand side gives the raw scores used to rank tokens. This is a ranking function that decides which KV tokens deserve the full attention computation.
scores = q_b @ K.T
scores_relu = torch.relu(scores)
w = weights[b] # Per-sequence head weights in this implementation.
weighted_scores = scores_relu * w[:, None]
final_scores = weighted_scores.sum(dim=0)
Why ReLU here?
For two simple reasons:
- ReLU keeps positive dot products and sets negative ones to zero before they contribute to a token’s ranking score.
- ReLU is cheap to compute when the same operation must run repeatedly for every query.
Top-k: convert local indices to global KV token indices
Top-k is computed in local sequence-token space. Sparse attention needs global KV addresses, so we convert using global_page * page_size + offset.
The KV cache is a flattened store with multiple pages. For the packed layout shown in the screenshots, you cannot simply split [..., :128] and [..., 128:] from the [pages, 64, 1, 132] view: that interleaves data and scales incorrectly. Flatten to [pages, 64 * 132] first, then split at the 64 * 128 boundary.
topk_indices, shaped [B, 2048] in this example, contains global flat indices into the KV cache. These become sparse_indices in stage two.
actual_topk = min(topk, seq_len)
_, topk_idx = torch.topk(final_scores, actual_topk)
page_idx_per_token = topk_idx // page_size
offset_per_token = topk_idx % page_size
global_page_idx = page_indices[page_idx_per_token]
topk_tokens = global_page_idx * page_size + offset_per_token
topk_indices[b, :actual_topk] = topk_tokens.to(torch.int32)
Sparse attention
Stage two runs attention only on the top-k indices selected using the indexer’s scores.
- Kernel two flattens the KV cache into a global token array, and
sparse_indicesdirectly indexes it. - This is where the first kernel’s global KV indices pay off.
Kc_all = ckv_cache.reshape(-1, head_dim_ckv).to(torch.float32)
Kp_all = kpe_cache.reshape(-1, head_dim_kpe).to(torch.float32)
indices = sparse_indices[t]
valid_mask = indices != -1
valid_indices = indices[valid_mask]
tok_idx = valid_indices.to(torch.long)
Kc = Kc_all[tok_idx]
Kp = Kp_all[tok_idx]
Compute logits: content dot product + positional dot product, then scale
This is standard attention scoring, restricted to the selected set. In this example, stage two runs full attention over the 2,048 tokens selected by stage one. There are two variants: page_size=1 for an unpaged cache and page_size=64 for a paged cache. The core computation is identical.
qn = q_nope[t].to(torch.float32)
qp = q_pe[t].to(torch.float32)
logits = (qn @ Kc.T) + (qp @ Kp.T)
logits_scaled = logits * sm_scale
Core attention loop
for t in range(num_tokens):
indices = sparse_indices[t] # [2048]
valid_mask = indices != -1 # Filter padding.
valid_indices = indices[valid_mask]
# Gather: scattered reads from the KV cache.
tok_idx = valid_indices.to(torch.long)
Kc = Kc_all[tok_idx] # [num_valid, 512]
Kp = Kp_all[tok_idx] # [num_valid, 64]
qn = q_nope[t].to(torch.float32) # [16, 512]
qp = q_pe[t].to(torch.float32) # [16, 64]
# Split attention logit.
logits = (qn @ Kc.T) + (qp @ Kp.T) # [16, num_valid]
logits_scaled = logits * sm_scale
# Base-2 LSE, for merging with dense attention.
lse[t] = torch.logsumexp(logits_scaled, dim=-1) / math.log(2.0)
# Softmax + output: the compressed KV tensor is also the value.
attn = torch.softmax(logits_scaled, dim=-1)
out = attn @ Kc # [16, 512]
output[t] = out.to(torch.bfloat16)
The final MLA trick: why V = K in compressed KV
DSA builds on MLA: Multi-head Latent Attention. In DeepSeek’s MLA, both K and V are derived from the same compressed latent representation, ckv: the compressed KV cache.
There is no separate V tensor in this reference attention loop. The line out = attn @ Kc is intentional: compressed KV is used as the value. The 512-dimensional latent carries information for both key matching and value retrieval. Separate positional information goes through the kpe / q_pe path.