Article
DSA
On this page 17
DSA (DeepSeek Sparse Attention)
I’ve been reading about DSA to see whether there’s room to write or optimize a kernel. My CUDA skills are still basic, so I’m starting with the algorithm.
There are several pieces to cover, so I’ve organized my notes as follows:
Updated May 8, 2026. After rereading a few posts and working through the details, I had some new thoughts about MLA.
1.kv and kvcache
kv
This is a basic Transformer operation. I drew the diagram to explain it to a friend.

In the original implementation above, each layer computes the full attention matrix, with substantial redundant KV work. During decoding, only the last query row is needed. Caching KV lets each decode step do attention work.
kv-cache

The K and V vectors for earlier tokens stay fixed. We can cache the initial sequence’s vectors on the first pass and append the vectors for each new token. This avoids recomputing earlier KV entries and lets each decode step take just the newest token as input.
The first pass is called prefill, and the subsequent generation steps are called decode. I’ll return to this distinction in my post on prefill/decode disaggregation.
This trades memory for time. The trade-off can be uneven, as discussed in this Zhihu post and this one.


A Few Observations
Following this Zhihu post, here is what happens if we apply a LoRA-style projection to the hidden state.
Leaving RoPE aside, the core computation is:
Here , is the dimension of one head, and is the hidden dimension. The expression is for a single head.
The KV cache needs so much memory because it stores . To change the trade-off, we can cache a different representation and do more computation on demand.
For example, we can cache directly, using elements independent of the head count . The keys alone use , and in many large models is smaller than .
Applying associativity to the matrix products gives:
The head count varies by model. With , this example uses over 50 times as much computation to bring memory use down to roughly one third.
To shrink the cache further, we can apply another low-rank projection to and store the down-projected result.
The idea is straightforward until we introduce RoPE. Standard RoPE acts on the full Q and K vectors, and a conventional KV cache stores K after rotation. Applying RoPE in the same way would require reconstructing K from the compressed latent.
With RoPE in the low-rank formulation above, token attending to cached key needs a position-dependent rotation . Without RoPE, the intervening rotations drop out and the projection matrices can be combined into a fixed matrix. With RoPE, the term depends on position.
One option is to reconstruct the full keys and apply RoPE, which gives up much of the intended cache benefit if we then store those keys.
Computing for all relevant positions on the fly also adds work at every step. Over the sequence, those pairwise computations grow as .
The central question is how to combine the latent representation with RoPE while still being able to precompute the position-independent projection.
2.MLA
Implementation
How does MLA solve this?
It gives positional encoding its own small, low-dimensional vector. The model concatenates it with the content part of Q and K before taking the dot product:
This keeps positional encoding in a separate branch. DeepSeek’s official equations below correspond to the expression above.
Compare this with the MLA equations:

The diagram from my supervisor shows the extra RoPE branch.

Earlier notes, kept for reference.
DeepSeek uses a LoRA-like pair of projections to reduce the dimension of and expand it again. This has two advantages:
- There is less data to cache.
- By associativity, the up-projection can be combined with or in advance, reducing the work at inference time.
Without positional encoding, we can expand attention as follows:
The cache stores the down-projected , which reduces GPU memory use. We can precompute and , and even . This is central to MLA: attention can work with the compact latent without reconstructing the full K and V.
With positional encoding, ordinary RoPE is incompatible with that shortcut because a position-dependent rotation sits between the weight matrices.
We can no longer use associativity to combine those weights ahead of time. DeepSeek handles this by representing position with a separate low-dimensional vector, then concatenating that branch with the content part of Q and K before multiplying:
This gives the positional encoding its own branch.
Execution Modes
Separating the latent content from RoPE lets MLA reduce cache size.
Decoupling RoPE also makes weight absorption possible. By folding the up-projections into adjacent operations, MLA can use an MQA-like path suited to memory-bound workloads. The other option reconstructs K and V before attention. In the prefill example, that takes roughly a quarter of the arithmetic of the absorbed path, at the cost of more memory traffic.
The two modes give implementations different choices for compute-bound and memory-bound work.

Absorbed Mode / MQA Mode
Separating RoPE lets us absorb the K up-projection into the query path, giving without materializing full-dimensional K. We can also take the weighted sum of first and apply the value up-projection afterward, avoiding full-dimensional V in memory.
Non-absorbed Mode / MHA Mode
Training and prefill can use the non-absorbed path.
Earlier note: MLA trades compute for memory. Decode puts pressure on memory, while training and prefill are often compute bound. In the prefill comparison below, absorption takes about three to four times as much arithmetic.
Comparing the Work
Following this Zhihu derivation, the non-absorbed cost is:

The absorbed cost is:

Here is the positional-encoding dimension and is the query length. The difference is .
In prefill, . The two expressions reduce to terms on the order of and , with roughly a fourfold difference for the dimensions considered here.
In decode, . The corresponding expressions are on the order of and , with roughly a 128-fold difference in the example.
The Design Story
This is about as far as my understanding of MLA goes. The account above is my interpretation of the math.
The equations are fixed, but they allow more than one account of how the design came about. The comments on Why MLA Works Well discuss both the MQA and latent-compression perspectives. Both are useful. I wonder which was closer to the DeepSeek team’s original reasoning.
An explanation usually tells a continuous story from one starting point. As Su Jianlin’s post suggests, handling RoPE involved some trial and error. The team found a balance between separating the RoPE branch and using low-rank projections to compress the cache.
I’ve been thinking about whether reconstructing the story can teach me how to design algorithms. Algorithms seldom emerge fully formed. A tidy retrospective account can only tell me so much about how to discover one.
I can try to reconstruct the reasoning the DeepSeek team presents in the paper. To build that skill myself, I need practice noticing conflicting requirements, proposing solutions, and deciding what to trade off.
thinking & TODO
- Quantify how much work combining weight matrices can save.
- Look into why the low-rank representation works and what it costs in quality.
- How does it stay competitive with MHA after reducing the dimensionality?
- A few implementation updates:
- In the original official demo, prefill uses MHA and decode uses MQA.
- The DSA demo reportedly inherited this split from the MLA implementation.
- The SGLang implementation appears to choose by sequence length during prefill. Short sequences use standard MHA and populate the latent cache, while long sequences use MLA in MQA mode.
- Standard MHA makes sense for short sequences. Why does SGLang pick MQA mode for longer sequences instead of MLA in MHA mode? Does memory access become the bottleneck even during prefill?
- Could MQA simply make better use of the hardware?
- The two modes are mathematically equivalent. Does changing the order of floating-point operations introduce enough rounding error to matter?
3.DSA

The diagram shows DSA adding sparse attention on top of MLA in MQA mode. It needs two components:
- Rank the candidate K/V entries by relevance.
- Compute attention over the highest-scoring entries.
These jobs correspond to the two modules in the diagram:
- Lightning Indexer
- Top-k Selector
lightning indexer
Attention itself normally determines how relevant K/V entries are. DSA first runs a lighter computation to estimate token relevance at lower cost:
Here is the relevance score, is the query token index, and is the earlier token index. The query token supplies and , and the earlier token supplies . The index identifies a head, is the head count, and ReLU gates the dot-product scores.
One way to relate this to ordinary attention is to view ReLU as a simpler scoring function and as playing a role analogous to V.
The indexer uses a separate RoPE branch, as in MLA.
TODO: Estimate the computation cost.
topk selector
The relevance scores determine a dynamic sparsity pattern. A sparse kernel can skip unselected K/V entries outright, saving work compared with computing dense scores and masking entries with negative infinity. The main challenge is the irregular memory access caused by those skips.
- Memory bandwidth: dense kernels exploit locality. Sparse access can trigger many noncontiguous reads and reduce cache hit rates.
- Load balancing: uneven work across threads can cause warp divergence and reduce utilization.
- Indexing overhead: the kernel needs additional index data.
thinking.part2
Is hardware utilization the main reason DSA uses MLA in MQA mode?
MHA gives each query head its own K/V head. If query heads select different top-K indices, packing them into a large Tensor Core GEMM is difficult. A dense mask or many small GEMMs can leave the Tensor Cores underused.
In MLA’s MQA mode, the query heads share K/V. A common top-K selection lets the kernel load the sparse keys and values once and pack the queries into larger, regular tiles. This is a better fit for Tensor Core GEMMs.
MLA in MQA mode can require more FLOPs in prefill than standard MHA. On long sequences, however, memory bandwidth and compute utilization may matter more. Loading only the selected K/V and using regular GEMM shapes can outweigh the cost of the extra arithmetic.
Kernel Design
TODO·······
This seems like a useful place to investigate.
An MHA-Mode Example
# Excerpt from the MLA forward pass ---------------------:
def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]):
bsz, seqlen, _ = x.size()
end_pos = start_pos + seqlen
# TODO: Why compress and then reconstruct Q as well?
qr = self.q_norm(self.wq_a(x))
q = self.wq_b(qr)
# TODO: Reshape to add the head dimension.
q = q.view(bsz, seqlen, self.n_local_heads, self.qk_head_dim)
q_nope, q_pe = torch.split(q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
q_pe = apply_rotary_emb(q_pe, freqs_cis)
kv = self.wkv_a(x)
kv, k_pe = torch.split(kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
kv = self.kv_norm(kv)
k_pe = apply_rotary_emb(k_pe.unsqueeze(2), freqs_cis)
self.kv_cache[:bsz, start_pos:end_pos] = kv
self.pe_cache[:bsz, start_pos:end_pos] = k_pe.squeeze(2)
if mask is not None: # MHA prefill
q = torch.cat([q_nope, q_pe], dim=-1)
kv = self.wkv_b(kv)
kv = kv.view(bsz, seqlen, self.n_local_heads, self.qk_nope_head_dim + self.v_head_dim)
k_nope, v = torch.split(kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
k = torch.cat([k_nope, k_pe.expand(-1, -1, self.n_local_heads, -1)], dim=-1)
scores = torch.einsum("bshd,bthd->bsht", q.float(), k.float()) * self.softmax_scale
# Run the indexer to find the top-k positions.
topk_indices = self.indexer(x, qr, start_pos, freqs_cis, mask)
# The mask is applied by addition here:
index_mask = torch.full((bsz, seqlen, seqlen), float("-inf"), device=x.device).scatter_(-1, topk_indices, 0)
index_mask += mask
scores += index_mask.unsqueeze(2)
scores = scores.softmax(dim=-1, dtype=torch.float32)
x = torch.einsum("bsht,bthd->bshd", scores.type_as(x), v)
# End of excerpt --------------------------------------.
This demo illustrates the logic with a mask. It does not use sparsity to skip the dense computation.
An optimized implementation might use four kernels:
-
Fused Q projection: combine
wq_a → norm → wq_b → split → rope → catto reduce memory traffic. -
Fused KV up-projection: combine
wkv_a → split → norm → wkv_b → split. -
Sparse QKᵀ and top-K selection: the PyTorch demo computes all scores and masks after selecting top-K. A custom attention kernel can compute only the selected Q/K pairs.
-
Fused softmax and weighted sum: combine
softmax + dropout + scale + bmmto avoid repeated reads and writes.
The sparse attention kernel is the main design problem. There are two paths to explore:
- Skip the unselected entries to save computation.
- Handle the cost of irregular memory accesses.
- A gather might help, but its overhead needs to be measured.
- Use a mask as in the demo.
- Look for properties of the mask that make the computation faster.
MQA
else: # MQA decode
if self.dequant_wkv_b is None and self.wkv_b.scale is not None:
self.dequant_wkv_b = weight_dequant(self.wkv_b.weight, self.wkv_b.scale)
wkv_b = self.wkv_b.weight if self.dequant_wkv_b is None else self.dequant_wkv_b
wkv_b = wkv_b.view(self.n_local_heads, -1, self.kv_lora_rank)
q_nope = torch.einsum("bshd,hdc->bshc", q_nope, wkv_b[:, :self.qk_nope_head_dim])
scores = (torch.einsum("bshc,btc->bsht", q_nope, self.kv_cache[:bsz, :end_pos]) +
torch.einsum("bshr,btr->bsht", q_pe, self.pe_cache[:bsz, :end_pos])) * self.softmax_scale
# indexer
topk_indices = self.indexer(x, qr, start_pos, freqs_cis, mask)
index_mask = torch.full((bsz, 1, end_pos), float("-inf"), device=x.device).scatter_(-1, topk_indices, 0)
scores += index_mask.unsqueeze(2)
scores = scores.softmax(dim=-1)
x = torch.einsum("bsht,btc->bshc", scores, self.kv_cache[:bsz, :end_pos])
x = torch.einsum("bshc,hdc->bshd", x, wkv_b[:, -self.v_head_dim:])
x = self.wo(x.flatten(2))
return x
-
Sparse KV Load
-
CTA-level tiled sparse attention
One CTA (thread block) handles:
A tile of 128 queries A tile of shared top-K K/V entries It computes only Q_tile × KV_topk_tile. This skips unselected pairs.
-
Fused low-rank absorption kernel
-
Fused RoPE kernel
NSA Kernel
The diagram below shows the kernel design for native sparse attention (NSA). I may cover it separately.
At first glance, it looks like FlashAttention adapted to skip tiles according to a sparsity pattern.
To be continued.
Afterword
This post stops at the compute analysis. My notes on DSA in SGLang cover kernels and trade-offs between compute and memory bandwidth.
MLA also left me thinking about how we explain the design process.
