Article

DSA

#deepseek
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.

transformer

In the original implementation above, each layer computes the full N×NN\times N attention matrix, with substantial redundant KV work. During decoding, only the last query row is needed. Caching KV lets each decode step do O(N)O(N) attention work.

kv-cache

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.

mem

calcu

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:

o=softmax⁡(x⊤Wq⏟qR1×dh  Wk⊤X⏟k⊤Rdh×N)X⊤WvWo⏟vRN×dho = \operatorname{softmax}\bigg( \underbrace{x^\top W_q}_{\substack{q \\ \mathbb{R}^{1 \times d_h}}} \; \underbrace{W_k^\top X}_{\substack{k^\top \\ \mathbb{R}^{d_h \times N}}} \bigg) \underbrace{X^\top W_v W_o}_{\substack{v \\ \mathbb{R}^{N \times d_h}}}

Here x=X[:−1]x=X[:-1], dhd_h is the dimension of one head, and dd is the hidden dimension. The expression is for a single head.

The KV cache needs so much memory because it stores K=WkTX,V=WvTXK=W_{k}^TX,V=W_{v}^TX. To change the trade-off, we can cache a different representation and do more computation on demand.

For example, we can cache XX directly, using d×Nd \times N elements independent of the head count hch_c. The keys alone use dh×N×hcd_h \times N \times h_c, and in many large models dd is smaller than dhhcd_h h_c.

Applying associativity to the matrix products gives:

Work per head: 1×d×dh⏟compute q+1×dh×d⏟q×W⊤+1×d×N⏟qk⊤+1×N×d⏟sv+1×d×dh⏟Wv+1×dh×d⏟compute o=4ddh+2Nd\text{Work per head: } \begin{aligned} & \underbrace{1 \times d \times d_h}_{\text{compute }q} + \underbrace{1 \times d_h \times d}_{q \times W^\top} + \underbrace{1 \times d \times N}_{qk^\top} + \underbrace{1 \times N \times d}_{sv} + \underbrace{1 \times d \times d_h}_{W_v} + \underbrace{1 \times d_h \times d}_{\text{compute }o} \\ &= 4 d d_h + 2 N d \end{aligned} Work per KV-cached decode step: 1×d×dh⏟compute q+1×d×dh⏟new k+1×d×dh⏟new v+1×dh×(N+1)⏟qk⊤+1×(N+1)×dh⏟sv+1×dh×d⏟compute o=4ddh+2(N+1)dh≈4ddh+2Ndh\text{Work per KV-cached decode step: } \begin{aligned} &\underbrace{1 \times d \times d_h}_{\text{compute }q} +\underbrace{1 \times d \times d_h}_{\text{new }k} +\underbrace{1 \times d \times d_h}_{\text{new }v} +\underbrace{1 \times d_h \times (N+1)}_{qk^\top} +\underbrace{1 \times (N+1) \times d_h}_{sv} +\underbrace{1 \times d_h \times d}_{\text{compute }o} \\ &= 4dd_h + 2(N+1)d_h \approx 4dd_h + 2Nd_h\end{aligned}

The head count varies by model. With hc=64h_c=64, 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 XX and store the down-projected result.

Sm(xTWDqWUq⏟queryWkTWUTWDTX⏟down-projection⏟up-projection⏟key path)(XTWD)⏟down-projectionWU⏟up-projectionWv⏟value pathWoSm\left( \underbrace{x^T W_{Dq} W_{Uq}}_{\text{query}} \underbrace{W_k^T \underbrace{W_U^T \underbrace{W_D^T X}_{\text{down-projection}} }_{\text{up-projection}} }_{\text{key path}} \right) \underbrace{ \underbrace{\underbrace{(X^T W_D)}_{\text{down-projection}} W_U}_{\text{up-projection}} W_v }_{\text{value path}} W_o

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.

qtkiT=(xiWDqWUqRi)(XjWD⏟ciWUWkRj)T=xt(Wq′RiRjTWk′T)ciq_t k_i^T = (x_i W_{Dq} W_{Uq} R_i)(\underbrace{X_j W_D}_{c_i} W_U W_k R_j)^T=x_t (W_q' R_i R_j^T W_k'^T) c_i

With RoPE in the low-rank formulation above, token tt attending to cached key ii needs a position-dependent rotation Rt−iR_{t-i}. Without RoPE, the intervening rotations drop out and the projection matrices can be combined into a fixed matrix. With RoPE, the term Wq′(RiRjT)Wk′TW_q' (R_i R_j^T) W_k'^T 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 Rt−iR_{t-i} for all relevant positions on the fly also adds work at every step. Over the sequence, those pairwise computations grow as O(N2)O(N^2).

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:

qt,iT×kj,i=[qt,iC,qt,iR]T×[kj,iC,kj,iR]=qt,iCkj,iC+qt,iRkj,iRq_{t,i}^T \times k_{j,i} = \left[ q_{t,i}^C, q_{t,i}^R \right]^T \times \left[ k_{j,i}^C, k_{j,i}^R \right] = q_{t,i}^C k_{j,i}^C + q_{t,i}^R k_{j,i}^R

This keeps positional encoding in a separate branch. DeepSeek’s official equations below correspond to the expression above.

Sm(xTWDqWUq⏟queryWkTWUTWDTX⏟down-projection⏟up-projection⏟key path)(XTWD)⏟down-projectionWU⏟up-projectionWv⏟value pathWoSm\left( \underbrace{x^T W_{Dq} W_{Uq}}_{\text{query}} \underbrace{W_k^T \underbrace{W_U^T \underbrace{W_D^T X}_{\text{down-projection}} }_{\text{up-projection}} }_{\text{key path}} \right) \underbrace{ \underbrace{\underbrace{(X^T W_D)}_{\text{down-projection}} W_U}_{\text{up-projection}} W_v }_{\text{value path}} W_o

Compare this with the MLA equations:

Sm(xTWDq⏟cqWUqWkTWUT⏟WUKWDTX⏟ckv)(XTWD)⏟ckvWUWv⏟WUVWoSm( \underbrace{x^T W_{Dq}}_{c_q} W_{Uq}\underbrace{W_k^T W_U^T}_{W_{UK}} \underbrace{W_D^T X}_{c_{kv}}) \underbrace{(X^T W_D)}_{c_{kv}} \underbrace{W_U W_v }_{W_{UV}} W_o

dsformula

The diagram from my supervisor shows the extra RoPE branch.

image-20260509102525826

Earlier notes, kept for reference.

DeepSeek uses a LoRA-like pair of projections to reduce the dimension of XX and expand it again. This has two advantages:

  • There is less data to cache.
  • By associativity, the up-projection WUW_U can be combined with WvW_v or WkW_k in advance, reducing the work at inference time.

Without positional encoding, we can expand attention as follows:

Sm(xTWDqWUq⏟queryWkTWUTWDTX⏟down-projection⏟up-projection⏟key path)(XTWD)⏟down-projectionWU⏟up-projectionWv⏟value pathWoSm\left( \underbrace{x^T W_{Dq} W_{Uq}}_{\text{query}} \underbrace{W_k^T \underbrace{W_U^T \underbrace{W_D^T X}_{\text{down-projection}} }_{\text{up-projection}} }_{\text{key path}} \right) \underbrace{ \underbrace{\underbrace{(X^T W_D)}_{\text{down-projection}} W_U}_{\text{up-projection}} W_v }_{\text{value path}} W_o

The cache stores the down-projected ckvc_{kv}, which reduces GPU memory use. We can precompute WUKW_{UK} and WUVW_{UV}, and even WqWUKTW_qW_{UK}^T. 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.

qt,iT×kj,i=(RtW(i)UQctQ)T×RjW(i)UKcjKV=(ctQ)T×(W(i)UQ)TRtTRjW(i)UKcjKV=(ctQ)T×(W(i)UQ)TRt−jW(i)UK×cjKV\begin{aligned} q_{t,i}^T \times k_{j,i} &= (\mathcal{R}_t W_{(i)}^{UQ} c_t^Q)^T \times \mathcal{R}_j W_{(i)}^{UK} c_j^{KV} \\ &= (c_t^Q)^T \times (W_{(i)}^{UQ})^T \mathcal{R}_t^T \mathcal{R}_j W_{(i)}^{UK} c_j^{KV} \\ &= (c_t^Q)^T \times (W_{(i)}^{UQ})^T \mathcal{R}_{t-j} W_{(i)}^{UK} \times c_j^{KV} \quad \end{aligned}

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:

qt,iT×kj,i=[qt,iC,qt,iR]T×[kj,iC,kj,iR]=qt,iCkj,iC+qt,iRkj,iRq_{t,i}^T \times k_{j,i} = \left[ q_{t,i}^C, q_{t,i}^R \right]^T \times \left[ k_{j,i}^C, k_{j,i}^R \right] = q_{t,i}^C k_{j,i}^C + q_{t,i}^R k_{j,i}^R

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.

mode

Absorbed Mode / MQA Mode

Separating RoPE lets us absorb the K up-projection into the query path, giving qcWUqWUKTq_cW_{Uq}W_{UK}^T without materializing full-dimensional K. We can also take the weighted sum of ctKVc_t^{KV} 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:

hcNqdq(dh+dr)⏟q to 128 heads+2hcNcdh⏟c to k 128 heads+hcNqN(2dh+dr)⏟qk⊤+sv+hcNqdhd⏟o\underbrace{h_c N_q d_q (d_h + d_r)}_{\text{q to 128 heads}} + \underbrace{2h_c N c d_h}_{\text{c to k 128 heads}} + \underbrace{h_c N_q N (2d_h + d_r)}_{qk^\top + sv} + \underbrace{h_c N_q d_h d}_{o}

mla_mha_diagram

The absorbed cost is:

hcNqdq(dh+dr)+hcNqdhc⏟q with WqWk⊤+hcNqN(2c+dr)⏟qk+sv+hcNqcdh⏟Wv+hcNqdhd⏟Wo\underbrace{h_c N_q d_q (d_h + d_r) + h_c N_q d_h c}_{\text{q with } W_q W_k^\top} + \underbrace{h_c N_q N (2c + d_r)}_{qk + sv} + \underbrace{h_c N_q c d_h}_{W_v} + \underbrace{h_c N_q d_h d}_{W_o}

mla_mqa_flow

Here drd_r is the positional-encoding dimension and NqN_q is the query length. The difference is 2hcNqN(dh−c)+2hcdhc(N−Nq)2 h_c N_q N (d_h - c) + 2 h_c d_h c ( N - N_q).

In prefill, N=NqN=N_q. The two expressions reduce to terms on the order of O(N2(2dh+dr))O(N^2(2d_h + d_r)) and O(N2(2c+dr))O(N^2(2c + d_r)), with roughly a fourfold difference for the dimensions considered here.

In decode, Nq=1N_q=1. The corresponding expressions are on the order of O(N(2cdh+2dh+dr))O(N(2 c d_h + 2d_h + d_r)) and O(N(2c+dr))O(N(2c + d_r)), 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

dsa-idea

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:

It,s=∑j=1HIwi,jI⋅ReLU(qi,jI⋅ksI)I_{t,s} = \sum_{j=1}^{H^I} w_{i,j}^I \cdot \text{ReLU}(q_{i,j}^I \cdot k_s^I)

Here It,sI_{t,s} is the relevance score, tt is the query token index, and ss is the earlier token index. The query token supplies qi,jIq_{i,j}^I and wi,jIw_{i,j}^I, and the earlier token supplies ksIk_s^I. The index jj identifies a head, HH 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 wi,jIw_{i,j}^I 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.

  1. Memory bandwidth: dense kernels exploit locality. Sparse access can trigger many noncontiguous reads and reduce cache hit rates.
  2. Load balancing: uneven work across threads can cause warp divergence and reduce utilization.
  3. 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:

  1. Fused Q projection: combine wq_a → norm → wq_b → split → rope → cat to reduce memory traffic.

  2. Fused KV up-projection: combine wkv_a → split → norm → wkv_b → split.

  3. 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.

  4. Fused softmax and weighted sum: combine softmax + dropout + scale + bmm to 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
  1. Sparse KV Load

  2. 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.

  1. Fused low-rank absorption kernel

  2. 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.

nsakernel

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.

Reference