The design-space lesson found that at 128K, dense attention is 97% of DeepSeek-V3’s decode FLOPs, and the attention lesson showed why: MLA’s decode reads a small entry per token but does a lot of work on it, so the only lever left is to read fewer entries. That is what sparse attention does. It does not change what an entry is or how many layers keep entries; it changes which entries a query looks at.
Four designs shipped between February 2025 and September 2026. They look different, but each has the same three steps:
where is whatever the scorer looks at (a token’s indexer key, a compressed block key), and is an optional local window that is always included. With candidates, a scoring cost per candidate and a core cost per attended key, the cost per query is
Everything that differs between the designs is a choice about these two terms.
| candidates scored | scorer | selected | always included | how it is trained | |
|---|---|---|---|---|---|
| NSA (paper, 27B) | compressed blocks: , stride 16 | the compression branch’s own attention probabilities, summed over the GQA group | 16 blocks of 64 tokens (incl. 1 initial, 2 local) | 512-token window; output = gated sum of compressed, selected and window branches | natively, from scratch |
| DSA (DeepSeek-V3.2) | every token | lightning indexer: , 64 heads × 128, FP8 | top-2048 tokens | – | continued pre-training: dense KL warm-up of the indexer, then sparse |
| QSA (Qwen3.8-Flash-Next) | mean-pooled key blocks, , RoPE added after pooling | MQA indexer, 4 heads + 1 shared key, head 128 | 512 blocks (2,048 tokens) | the query’s own incomplete block | continued pre-training: indexer distilled from max-pooled dense attention, then sparse |
| CSA (DeepSeek-V4) | compressed entries, (overlapping windows) | lightning indexer on compressed keys, FP4 | top-1024 entries (Pro), 512 (Flash) | 128-token uncompressed window, sink | sparse after a dense phase |
| HCA (DeepSeek-V4) | – (no selection) | – | all compressed entries, | 128-token window, sink | – |
Three choices, three trade-offs
What a candidate is: tokens or blocks. DSA scores every token, which is the most precise but has two costs: the scorer is per query (so per sequence), and the selected keys are scattered, so the core attention needs a gather. Block designs (NSA, QSA) score candidates and then read contiguous runs of keys, which is what GPU memory systems like; NSA also shares one selection across all heads of a GQA group “so KV is loaded once per group”. DSA gets the same sharing differently: on MLA’s MQA mode there is one KV head to begin with, so all 128 query heads reuse the 2,048 selected latents.
How a block is summarised. A block score has to stand in for its tokens. If the block key is a mean (QSA’s AvgPool, NSA’s learned φ is an MLP over the block), a single important token in a block of has its logit margin divided by while the noise of the others shrinks only by : lone needles get diluted. Qwen3.8 uses and trains the indexer against a max-pooled teacher “so that a single important token in a block is not diluted”; V4 compresses with learned, per-channel softmax weights rather than a plain mean. The second figure measures this.
Where the remaining cost goes. Selection caps the core term at , so at long context the scorer is what is left. From V3.2’s config, the indexer is multiply-adds per token against for the core; at 128K the indexer is already ~80% of what remains (V3.2 lesson). That is the reason for each later design: QSA scores blocks with a 4-head indexer; CSA scores compressed entries in FP4; HCA has no scorer at all and simply reads entries densely.
설계 공간 레슨에서 128K의 dense attention이 DeepSeek-V3 decode FLOPs의 97%라는 것을 봤고, attention 레슨이 그 이유를 보였다. MLA decode는 토큰마다 작은 항목을 읽지만 그 위에서 많은 일을 하므로, 남은 손잡이는 더 적은 항목을 읽는 것뿐이다. sparse attention이 하는 일이 그것이다. 항목이 무엇인지, 몇 개 층이 항목을 들고 있는지는 바꾸지 않는다. query가 어느 항목을 보는지를 바꾼다.
2025년 2월부터 2026년 9월 사이에 네 가지 설계가 나왔다. 모양은 다르지만 모두 같은 세 단계를 가진다.
는 점수기가 보는 것(토큰의 indexer key, 압축된 block key)이고 는 늘 포함되는 선택적 지역 window다. 후보 개, 후보당 점수 비용 , attention하는 key당 core 비용 이면 query당 비용은
설계들 사이의 차이는 전부 이 두 항에 대한 선택이다.
| 점수 매기는 후보 | 점수기 | 고르는 것 | 늘 포함 | 학습 방법 | |
|---|---|---|---|---|---|
| NSA (논문, 27B) | 압축 block: , stride 16 | 압축 갈래 자신의 attention 확률을 GQA 그룹에서 합산 | 64토큰 block 16개(초기 1, 지역 2 포함) | 512토큰 window. 출력 = 압축·선택·window 갈래의 gate 가중합 | 처음부터 native로 |
| DSA (DeepSeek-V3.2) | 모든 토큰 | lightning indexer: , 64 head × 128, FP8 | top-2048 토큰 | – | 연속 사전학습: indexer의 dense KL warm-up 뒤 sparse |
| QSA (Qwen3.8-Flash-Next) | 평균 pooling한 key block, , pooling 뒤 RoPE | MQA indexer, head 4 + 공유 key 1, head 128 | block 512개(2,048토큰) | query 자신의 미완성 block | 연속 사전학습: max pooling한 dense attention으로 indexer 증류 뒤 sparse |
| CSA (DeepSeek-V4) | 압축 항목, (겹치는 window) | 압축 key 위의 lightning indexer, FP4 | top-1024 항목(Pro), 512(Flash) | 압축 안 한 128토큰 window, sink | dense 단계 뒤 sparse |
| HCA (DeepSeek-V4) | –(선택 없음) | – | 모든 압축 항목, | 128토큰 window, sink | – |
선택 셋, 거래 셋
후보가 무엇인가: 토큰이냐 block이냐. DSA는 모든 토큰에 점수를 매긴다. 가장 정밀하지만 비용이 둘이다. 점수기가 query당 (시퀀스당 )이고, 고른 key가 흩어져 있어 core attention에 gather가 필요하다. block 설계(NSA, QSA)는 후보 개에 점수를 매기고 연속된 key 구간을 읽는다. GPU 메모리 시스템이 좋아하는 방식이다. NSA는 GQA 그룹의 모든 head가 선택 하나를 공유해 “KV를 그룹마다 한 번만 읽는다”. DSA는 같은 공유를 다른 길로 얻는다. MLA의 MQA 모드에는 애초에 KV head가 하나뿐이라 query head 128개가 고른 latent 2,048개를 모두 재사용한다.
block을 어떻게 요약하나. block 점수는 그 안의 토큰들을 대신해야 한다. block key가 평균이면(QSA의 AvgPool; NSA의 학습된 φ는 block 위의 MLP), 크기 인 block 안의 중요한 토큰 하나는 logit 여유가 로 나뉘고 나머지의 잡음은 로만 준다. 혼자 있는 needle이 희석된다. Qwen3.8은 를 쓰고 indexer를 max pooling한 teacher로 학습해 “block 안의 중요한 토큰 하나가 희석되지 않게” 한다. V4는 단순 평균 대신 채널별 softmax 가중치를 학습해 압축한다. 두 번째 그림이 이것을 잰다.
남은 비용은 어디로 가나. 선택은 core 항을 로 묶으므로 긴 문맥에서 남는 것은 점수기다. V3.2 config로 indexer는 토큰당 곱셈-덧셈 , core는 이고, 128K에서 이미 남은 비용의 ~80%가 indexer다(V3.2 레슨). 이후 설계 각각의 이유가 이것이다. QSA는 head 4개짜리 indexer로 block 개에 점수를 매기고, CSA는 압축 항목 개에 FP4로 점수를 매기며, HCA는 점수기 없이 항목 개를 그냥 dense하게 읽는다.
Read the table under the chart at 32K, 128K and 1M. In every design the selected part is flat (2,048 tokens, 1,024 compressed entries, 512 blocks) while the scoring part grows with , so each design has a crossover after which scoring dominates. With FP8/FP4 weighting it comes at about 16K for NSA (whose scorer is its compressed branch, keys at full core cost), 70K for DSA, 200K for QSA and 260K for CSA. Compressing before scoring (QSA, CSA) and low precision (CSA) push the crossover out by roughly the compression ratio times the precision factor. Halve or double the selection budget to see which designs are bound by selection and which by scoring. These are multiply-add counts on each model’s head configuration; measured kernel speed-ups are smaller (QSA reports 7.6× prefill and 4.9× decode at 1M against a theoretical ratio “in the tens”), because memory traffic, gathers and kernel efficiency are not in the count.
Does selection find the right keys?
The cost model assumes the scorer picks what dense attention would have used. The toy below tests that for the three scorer types, on keys where the “needles” are set to a chosen logit and everything else is noise.
차트 아래 표를 32K, 128K, 1M에서 읽어 보자. 모든 설계에서 고른 부분은 평평하고(토큰 2,048개, 압축 항목 1,024개, block 512개) 점수 부분은 과 함께 자라므로, 설계마다 점수가 지배하기 시작하는 교차점이 있다. FP8/FP4 가중을 반영하면 NSA(점수기가 압축 갈래, 즉 key 개를 core 비용 그대로 읽는 것)는 약 16K, DSA는 70K, QSA는 200K, CSA는 260K다. 점수 전에 압축하는 것(QSA, CSA)과 낮은 정밀도(CSA)가 교차점을 대략 압축비 × 정밀도 배수만큼 뒤로 민다. 선택 예산을 절반이나 두 배로 해서 어느 설계가 선택에, 어느 설계가 점수에 묶여 있는지 보자. 이 숫자는 각 모델의 head 설정으로 센 곱셈-덧셈이다. 측정된 커널 속도 향상은 이보다 작다(QSA는 이론적 비율이 “수십 배”인데 1M에서 prefill 7.6배, decode 4.9배를 보고한다). 메모리 트래픽, gather, 커널 효율은 이 셈에 들어 있지 않기 때문이다.
선택은 맞는 key를 찾는가?
비용 모델은 점수기가 dense attention이 썼을 것을 고른다고 가정한다. 아래 장난감은 needle을 고른 logit으로 올리고 나머지는 잡음인 key 위에서 세 종류의 점수기를 시험한다.
What to look for.
- Scattered needles, r = 16: the token indexer has found most needles by , and the mean-pooled block scorer lags behind — each needle’s margin is divided by 16 inside its block. The block oracle (max of exact scores) is nearly perfect: the problem is the summary, not the block granularity.
- One contiguous span: now the mean-pooled block scorer is as good as the oracle at a tiny budget, because a block full of needles has a full-strength average. Real documents are somewhere in between (a relevant function, a paragraph, a table row), which is why blocks of 4–64 tokens work in practice and why NSA keeps a window and a compressed branch next to the selected blocks.
- Indexer dimension: lower to 2–4 and the token indexer degrades quickly; it recovers as grows. A trained indexer does better than a random projection, but it is the same trade: the indexer must be cheap enough that scoring all tokens is affordable, and rich enough to rank them.
- Recent window finds nothing (the needles are placed outside the last 2,048 tokens on purpose), which is why every design that relies on selection keeps the window only as a complement.
Building it
import numpy as np
rs = np.random.default_rng(0)
n, d = 4096, 64
def softmax(x):
x = x - x.max(); e = np.exp(x); return e / e.sum()
# one query, n keys/values; 12 "relevant" keys scattered in the past
K = rs.standard_normal((n, d)); Vv = rs.standard_normal((n, d)); q = rs.standard_normal(d)
needles = rs.choice(n - 1024, 12, replace=False)
K[needles] += 0.9 * q # relevant keys lean towards q
logit = K @ q / np.sqrt(d)
p_dense = softmax(logit)
o_dense = p_dense @ Vv
def sparse_attend(sel):
"""the common last step: exact softmax attention over the selected keys only"""
sel = np.unique(sel)
w = softmax(logit[sel]); return w @ Vv[sel], p_dense[sel].sum()
# ---- 1. the pattern: score -> top-k -> attend exactly ---------------------------
o_all, _ = sparse_attend(np.arange(n))
print("k = n reproduces dense attention:", np.allclose(o_all, o_dense))
# ---- 2. scorers -----------------------------------------------------------------
def lightning_indexer(H_I=4, d_I=16, noise=0.5):
"""DSA eq. 1: I_s = sum_j w_j ReLU(q_j . k_s), with one key per token shared by all indexer heads.
Stand-in for a trained indexer: k_s = P^T k, q_j = (P + noise_j)^T q, P a random d -> d_I projection."""
P = rs.standard_normal((d, d_I)) / np.sqrt(d_I)
kI = K @ P # [n, d_I] (cached, FP8 in DSA)
qI = np.stack([q @ (P + noise * rs.standard_normal((d, d_I)) / np.sqrt(d_I)) for _ in range(H_I)])
w = np.abs(rs.standard_normal(H_I)) # per-head weights w_j(h_t)
return (w[:, None] * np.maximum(qI @ kI.T, 0)).sum(0)
def block_scores(r, pool='mean'):
"""QSA/NSA-style: score blocks of r tokens with a pooled key (mean) or the block oracle (max of exact logits)."""
L = logit.reshape(-1, r)
return L.mean(1) if pool == 'mean' else L.max(1)
def select_tokens(score, k):
return np.argsort(-score)[:k]
def select_blocks(bscore, r, k):
top = np.argsort(-bscore)[: max(1, k // r)]
return (top[:, None] * r + np.arange(r)).ravel()
idx = lightning_indexer()
print("\nneedles found (of 12) / dense attention mass captured, by selector and budget k")
print(f"{'k':>5s} {'exact top-k':>12s} {'indexer':>12s} {'blk-mean r16':>13s} {'blk-max r16':>12s} {'window':>10s}")
for k in (64, 256, 1024):
row = []
for sel in (select_tokens(logit, k), select_tokens(idx, k), select_blocks(block_scores(16, 'mean'), 16, k),
select_blocks(block_scores(16, 'max'), 16, k), np.arange(n - k, n)):
_, m = sparse_attend(sel); row.append(f"{np.isin(needles, sel).sum():2d} / {m:.2f}")
print(f"{k:5d} " + " ".join(f"{x:>12s}" for x in row))
# ---- 3. NSA: three branches, gated ------------------------------------------------
l, stride, lsel, nsel, win = 32, 16, 64, 16, 512 # NSA paper settings
starts = np.arange(0, n - l + 1, stride)
Kc = np.stack([K[s:s + l].mean(0) for s in starts]); Vc = np.stack([Vv[s:s + l].mean(0) for s in starts]) # phi = mean here (an MLP in NSA)
p_cmp = softmax(Kc @ q / np.sqrt(d))
o_cmp = p_cmp @ Vc
# selection scores: sum the compression probabilities that overlap each 64-token block (NSA eq. 9, l'=64, d=16, l=32)
nblk = n // lsel
p_slc = np.zeros(nblk)
for i, s in enumerate(starts):
for b in range(s // lsel, (s + l - 1) // lsel + 1):
p_slc[b] += p_cmp[i]
forced = [0, nblk - 2, nblk - 1] # 1 initial + 2 local blocks always selected
rest = [b for b in np.argsort(-p_slc) if b not in forced][: nsel - len(forced)]
blocks = np.array(forced + rest)
o_slc, m_slc = sparse_attend((blocks[:, None] * lsel + np.arange(lsel)).ravel())
o_win, m_win = sparse_attend(np.arange(n - win, n))
g = np.array([1 / 3, 1 / 3, 1 / 3]) # gates come from a sigmoid MLP in NSA
o_nsa = g[0] * o_cmp + g[1] * o_slc + g[2] * o_win
print(f"\nNSA: {len(starts)} compressed keys + {nsel}x{lsel} selected + {win} window = {len(starts)+nsel*lsel+win} keys read of {n}")
print(f" selected blocks hold {m_slc:.3f} of the dense attention mass; needles covered:",
np.isin(needles // lsel, blocks).sum(), "/ 12")
# ---- 4. why mean-pooling dilutes a lone needle -----------------------------------
for r in (4, 16, 64):
b = block_scores(r, 'mean')
nb = needles // r
z = (b[nb] - b.mean()) / b.std() # needle blocks in units of block-score std
print(f" r={r:3d}: needle-block z-score {z.mean():5.2f} (a lone needle: signal divided by r, noise only by sqrt(r))")Part 2 is the same experiment as the figure with an indexer in DSA’s functional form (per-head ReLU dot products against one shared key, positive head weights). Part 3 builds NSA’s branches with the paper’s sizes (, stride 16, 16 selected blocks of 64 with the initial and two local blocks forced, window 512) and derives the selection scores from the compression branch’s probabilities, as NSA does; it reads 1,791 of 4,096 keys. Part 4 shows the dilution numerically: the z-score of a needle’s block falls as grows.
The PyTorch version below is the DSA pattern on a single shared KV head: a lightning indexer, a top-k gather attention that every head shares, and the KL loss of the dense warm-up that aligns the indexer with the main attention.
import torch
import torch.nn as nn
import torch.nn.functional as F
class LightningIndexer(nn.Module):
"""DSA-style indexer: I[t, s] = sum_j w_j(h_t) * ReLU(q_j(h_t) . k(h_s)); one key per token for all heads."""
def __init__(self, d, n_heads=64, d_idx=128):
super().__init__()
self.h, self.di = n_heads, d_idx
self.wq = nn.Linear(d, n_heads * d_idx, bias=False)
self.wk = nn.Linear(d, d_idx, bias=False)
self.ww = nn.Linear(d, n_heads, bias=False)
def forward(self, h): # h: [T, d] -> scores [T, T]
T = h.shape[0]
q = self.wq(h).view(T, self.h, self.di)
k = self.wk(h) # [T, d_idx], cached next to the KV
s = F.relu(torch.einsum("thd,sd->ths", q, k)) # [T, H, T]
return torch.einsum("ths,th->ts", s, self.ww(h))
def topk_sparse_attention(q, k, v, scores, topk):
"""q: [T, H, dh]; k, v: [T, dh] (one shared KV head, as in MLA's MQA mode); scores: [T, T]."""
T = q.shape[0]
causal = torch.ones(T, T, dtype=torch.bool, device=q.device).tril()
scores = scores.masked_fill(~causal, float("-inf"))
kk = min(topk, T)
idx = scores.topk(kk, dim=-1).indices # [T, kk]: same selection for every head
valid = torch.gather(causal, 1, idx) # early rows have fewer than kk past tokens
ks, vs = k[idx], v[idx] # [T, kk, dh] gather
logits = torch.einsum("thd,tkd->thk", q, ks) / q.shape[-1] ** 0.5
logits = logits.masked_fill(~valid[:, None, :], float("-inf"))
return torch.einsum("thk,tkd->thd", logits.softmax(-1), vs)
def indexer_kl_loss(attn_probs, idx_scores):
"""Dense warm-up: make softmax(indexer) imitate the main attention summed over heads (V3.2 eq. 3).
attn_probs: [T, H, T] (detached), idx_scores: [T, T] with -inf above the diagonal."""
target = attn_probs.sum(1)
target = target / target.sum(-1, keepdim=True)
logp = F.log_softmax(idx_scores.masked_fill(torch.isinf(idx_scores), -1e9), -1) # finite where target = 0
return F.kl_div(logp, target, reduction="batchmean")
T, d, H, dh = 32, 64, 4, 16
h = torch.randn(T, d)
idx = LightningIndexer(d, n_heads=4, d_idx=16)
q, k, v = torch.randn(T, H, dh), torch.randn(T, dh), torch.randn(T, dh)
print(topk_sparse_attention(q, k, v, idx(h), topk=8).shape) # torch.Size([32, 4, 16])At very long context, which term dominates the per-query cost of DeepSeek-V3.2's DSA, and what did QSA and CSA change to shrink it?
Selection caps the core at , but the indexer still scores all previous tokens, so its term grows without bound and dominates at long context (V3.2: 8,192 vs 139,264 multiply-adds per key, but vs 2,048 keys). QSA scores mean-pooled blocks with a 4-head indexer; CSA scores compressed entries with an FP4 indexer; HCA drops scoring altogether.
Summary
- Every 2025–26 sparse attention is “score cheaply, select top-k, attend exactly”: cost ≈ .
- Token-level selection (DSA) is precise but its scorer is per query and its reads are gathers; block selection (NSA, QSA) is kernel-friendly and shares selection across heads, at the risk of diluting lone tokens when blocks are summarised by a mean.
- Once selection caps the core, the scorer dominates at long context; QSA and CSA compress before scoring (and CSA scores in FP4), HCA reads heavily compressed entries without scoring.
- Windows and sinks stay next to selection to cover recent tokens and “nothing relevant”.
- Trained either natively (NSA) or by continued pre-training with an indexer warm-up distilled from dense attention (DSA, QSA).
볼 것.
- 흩어진 needle, r = 16: token indexer는 까지 needle 대부분을 찾고, 평균 pooling block 점수기는 뒤처진다. needle마다 block 안에서 여유가 16으로 나뉘기 때문이다. block 오라클(정확한 점수의 max)은 거의 완벽하다. 문제는 block 단위가 아니라 요약 방식이다.
- 한 구간에 모인 needle: 이제 평균 pooling block 점수기는 아주 작은 예산에서도 오라클만큼 좋다. needle로 가득한 block의 평균은 온전한 세기이기 때문이다. 실제 문서는 그 사이 어딘가(관련 함수 하나, 문단 하나, 표의 행 하나)에 있고, 그래서 4–64토큰 block이 실제로 통하며 NSA가 고른 block 옆에 window와 압축 갈래를 둔다.
- indexer 차원: 를 2–4로 낮추면 token indexer가 빠르게 나빠지고, 가 커지면 회복한다. 학습된 indexer는 무작위 투영보다 낫지만 거래는 같다. 모든 개 토큰에 점수를 매길 수 있을 만큼 싸야 하고, 순위를 매길 만큼 풍부해야 한다.
- recent window는 아무것도 찾지 못한다(needle을 일부러 마지막 2,048토큰 밖에 두었다). 선택에 기대는 설계가 모두 window를 보완으로만 두는 이유다.
직접 만들기
import numpy as np
rs = np.random.default_rng(0)
n, d = 4096, 64
def softmax(x):
x = x - x.max(); e = np.exp(x); return e / e.sum()
# query 하나, key/value n개, 과거에 흩어진 "관련" key 12개
K = rs.standard_normal((n, d)); Vv = rs.standard_normal((n, d)); q = rs.standard_normal(d)
needles = rs.choice(n - 1024, 12, replace=False)
K[needles] += 0.9 * q # 관련 key는 q 쪽으로 기운다
logit = K @ q / np.sqrt(d)
p_dense = softmax(logit)
o_dense = p_dense @ Vv
def sparse_attend(sel):
"""the common last step: exact softmax attention over the selected keys only"""
sel = np.unique(sel)
w = softmax(logit[sel]); return w @ Vv[sel], p_dense[sel].sum()
# ---- 1. 패턴: 점수 -> top-k -> 정확한 attention -----------------------------------
o_all, _ = sparse_attend(np.arange(n))
print("k = n reproduces dense attention:", np.allclose(o_all, o_dense))
# ---- 2. 점수기 ---------------------------------------------------------------------
def lightning_indexer(H_I=4, d_I=16, noise=0.5):
"""DSA eq. 1: I_s = sum_j w_j ReLU(q_j . k_s), with one key per token shared by all indexer heads.
Stand-in for a trained indexer: k_s = P^T k, q_j = (P + noise_j)^T q, P a random d -> d_I projection."""
P = rs.standard_normal((d, d_I)) / np.sqrt(d_I)
kI = K @ P # [n, d_I] (cached, FP8 in DSA)
qI = np.stack([q @ (P + noise * rs.standard_normal((d, d_I)) / np.sqrt(d_I)) for _ in range(H_I)])
w = np.abs(rs.standard_normal(H_I)) # per-head weights w_j(h_t)
return (w[:, None] * np.maximum(qI @ kI.T, 0)).sum(0)
def block_scores(r, pool='mean'):
"""QSA/NSA-style: score blocks of r tokens with a pooled key (mean) or the block oracle (max of exact logits)."""
L = logit.reshape(-1, r)
return L.mean(1) if pool == 'mean' else L.max(1)
def select_tokens(score, k):
return np.argsort(-score)[:k]
def select_blocks(bscore, r, k):
top = np.argsort(-bscore)[: max(1, k // r)]
return (top[:, None] * r + np.arange(r)).ravel()
idx = lightning_indexer()
print("\nneedles found (of 12) / dense attention mass captured, by selector and budget k")
print(f"{'k':>5s} {'exact top-k':>12s} {'indexer':>12s} {'blk-mean r16':>13s} {'blk-max r16':>12s} {'window':>10s}")
for k in (64, 256, 1024):
row = []
for sel in (select_tokens(logit, k), select_tokens(idx, k), select_blocks(block_scores(16, 'mean'), 16, k),
select_blocks(block_scores(16, 'max'), 16, k), np.arange(n - k, n)):
_, m = sparse_attend(sel); row.append(f"{np.isin(needles, sel).sum():2d} / {m:.2f}")
print(f"{k:5d} " + " ".join(f"{x:>12s}" for x in row))
# ---- 3. NSA: gate로 묶은 세 갈래 ----------------------------------------------------
l, stride, lsel, nsel, win = 32, 16, 64, 16, 512 # NSA paper settings
starts = np.arange(0, n - l + 1, stride)
Kc = np.stack([K[s:s + l].mean(0) for s in starts]); Vc = np.stack([Vv[s:s + l].mean(0) for s in starts]) # phi = mean here (an MLP in NSA)
p_cmp = softmax(Kc @ q / np.sqrt(d))
o_cmp = p_cmp @ Vc
# selection scores: sum the compression probabilities that overlap each 64-token block (NSA eq. 9, l'=64, d=16, l=32)
nblk = n // lsel
p_slc = np.zeros(nblk)
for i, s in enumerate(starts):
for b in range(s // lsel, (s + l - 1) // lsel + 1):
p_slc[b] += p_cmp[i]
forced = [0, nblk - 2, nblk - 1] # 초기 1 + 지역 2 block은 항상 선택
rest = [b for b in np.argsort(-p_slc) if b not in forced][: nsel - len(forced)]
blocks = np.array(forced + rest)
o_slc, m_slc = sparse_attend((blocks[:, None] * lsel + np.arange(lsel)).ravel())
o_win, m_win = sparse_attend(np.arange(n - win, n))
g = np.array([1 / 3, 1 / 3, 1 / 3]) # NSA에서 gate는 sigmoid MLP에서 나온다
o_nsa = g[0] * o_cmp + g[1] * o_slc + g[2] * o_win
print(f"\nNSA: {len(starts)} compressed keys + {nsel}x{lsel} selected + {win} window = {len(starts)+nsel*lsel+win} keys read of {n}")
print(f" selected blocks hold {m_slc:.3f} of the dense attention mass; needles covered:",
np.isin(needles // lsel, blocks).sum(), "/ 12")
# ---- 4. 평균 pooling이 혼자 있는 needle을 희석하는 이유 -----------------------------
for r in (4, 16, 64):
b = block_scores(r, 'mean')
nb = needles // r
z = (b[nb] - b.mean()) / b.std() # needle block을 block 점수 표준편차 단위로
print(f" r={r:3d}: needle-block z-score {z.mean():5.2f} (a lone needle: signal divided by r, noise only by sqrt(r))")2번은 그림과 같은 실험을 DSA의 함수 꼴(공유 key 하나에 대한 head별 ReLU 내적, 양수 head 가중치)의 indexer로 한다. 3번은 논문의 크기(, stride 16, 64토큰 block 16개 중 초기 1·지역 2 강제, window 512)로 NSA의 갈래를 만들고, NSA처럼 압축 갈래의 확률에서 선택 점수를 유도한다. key 4,096개 중 1,791개를 읽는다. 4번은 희석을 숫자로 보인다. 이 커질수록 needle block의 z-score가 떨어진다.
아래 PyTorch 판은 공유 KV head 하나 위의 DSA 패턴이다. lightning indexer, 모든 head가 공유하는 top-k gather attention, 그리고 indexer를 주 attention에 맞추는 dense warm-up의 KL 손실.
import torch
import torch.nn as nn
import torch.nn.functional as F
class LightningIndexer(nn.Module):
"""DSA-style indexer: I[t, s] = sum_j w_j(h_t) * ReLU(q_j(h_t) . k(h_s)); one key per token for all heads."""
def __init__(self, d, n_heads=64, d_idx=128):
super().__init__()
self.h, self.di = n_heads, d_idx
self.wq = nn.Linear(d, n_heads * d_idx, bias=False)
self.wk = nn.Linear(d, d_idx, bias=False)
self.ww = nn.Linear(d, n_heads, bias=False)
def forward(self, h): # h: [T, d] -> scores [T, T]
T = h.shape[0]
q = self.wq(h).view(T, self.h, self.di)
k = self.wk(h) # [T, d_idx], KV 옆에 캐시
s = F.relu(torch.einsum("thd,sd->ths", q, k)) # [T, H, T]
return torch.einsum("ths,th->ts", s, self.ww(h))
def topk_sparse_attention(q, k, v, scores, topk):
"""q: [T, H, dh]; k, v: [T, dh] (one shared KV head, as in MLA's MQA mode); scores: [T, T]."""
T = q.shape[0]
causal = torch.ones(T, T, dtype=torch.bool, device=q.device).tril()
scores = scores.masked_fill(~causal, float("-inf"))
kk = min(topk, T)
idx = scores.topk(kk, dim=-1).indices # [T, kk]: 모든 head가 같은 선택
valid = torch.gather(causal, 1, idx) # 앞쪽 행은 과거 토큰이 kk개보다 적다
ks, vs = k[idx], v[idx] # [T, kk, dh] gather
logits = torch.einsum("thd,tkd->thk", q, ks) / q.shape[-1] ** 0.5
logits = logits.masked_fill(~valid[:, None, :], float("-inf"))
return torch.einsum("thk,tkd->thd", logits.softmax(-1), vs)
def indexer_kl_loss(attn_probs, idx_scores):
"""Dense warm-up: make softmax(indexer) imitate the main attention summed over heads (V3.2 eq. 3).
attn_probs: [T, H, T] (detached), idx_scores: [T, T] with -inf above the diagonal."""
target = attn_probs.sum(1)
target = target / target.sum(-1, keepdim=True)
logp = F.log_softmax(idx_scores.masked_fill(torch.isinf(idx_scores), -1e9), -1) # target = 0인 곳도 유한하게
return F.kl_div(logp, target, reduction="batchmean")
T, d, H, dh = 32, 64, 4, 16
h = torch.randn(T, d)
idx = LightningIndexer(d, n_heads=4, d_idx=16)
q, k, v = torch.randn(T, H, dh), torch.randn(T, dh), torch.randn(T, dh)
print(topk_sparse_attention(q, k, v, idx(h), topk=8).shape) # torch.Size([32, 4, 16])아주 긴 문맥에서 DeepSeek-V3.2 DSA의 query당 비용을 지배하는 항은 무엇이고, QSA와 CSA는 그것을 줄이려고 무엇을 바꿨나?
선택은 core를 로 묶지만 indexer는 여전히 이전 토큰 개 모두에 점수를 매기므로 항이 끝없이 자라 긴 문맥에서 지배한다(V3.2: key당 곱셈-덧셈은 8,192 대 139,264이지만 key 수는 대 2,048). QSA는 head 4개짜리 indexer로 평균 pooling block 개에, CSA는 FP4 indexer로 압축 항목 개에 점수를 매기고, HCA는 점수 매기기를 아예 없앤다.
정리
- 2025–26년의 sparse attention은 모두 “싸게 점수 매기고, top-k를 고르고, 정확히 attention”이다. 비용 ≈ .
- 토큰 단위 선택(DSA)은 정밀하지만 점수기가 query당 이고 읽기가 gather다. block 선택(NSA, QSA)은 커널 친화적이고 head들이 선택을 공유하지만, block을 평균으로 요약하면 혼자 있는 토큰이 희석될 위험이 있다.
- 선택이 core를 묶고 나면 긴 문맥에서는 점수기가 지배한다. QSA와 CSA는 점수 전에 압축하고(CSA는 FP4로 점수), HCA는 점수 없이 크게 압축한 항목을 읽는다.
- window와 sink는 최근 토큰과 “관련된 것 없음”을 맡기 위해 선택 옆에 남는다.
- 학습은 native(NSA)이거나, dense attention에서 증류한 indexer warm-up을 곁들인 연속 사전학습(DSA, QSA)이다.
더 읽을거리Further reading
- Yuan et al., Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse Attention (2025) — 압축(l=32, stride 16)·선택(64토큰 block 16개, 초기 1 + 지역 2 포함)·window(512) 세 갈래와 sigmoid gate. 64K에서 forward 9.0배, backward 6.0배, decode 11.6배(메모리 접근량 기반 기대값).Compression (l = 32, stride 16), selection (16 blocks of 64, including 1 initial and 2 local) and window (512) branches with sigmoid gates; at 64K, 9.0× forward, 6.0× backward and 11.6× decode (an expected speed-up from memory access).
- DeepSeek-AI, DeepSeek-V3.2 (2025) — lightning indexer(64 head × 128, FP8)와 토큰 단위 top-2048, MLA의 MQA 모드 위에서. dense warm-up KL → sparse 학습.The lightning indexer (64 heads × 128, FP8) and token-level top-2048 on MLA's MQA mode; dense KL warm-up, then sparse training.
- Qwen Team, On the Design of Qwen3.8-Next Architecture (2026) — key를 r=4 block으로 평균 압축한 뒤 점수를 매기는 QSA. 1M에서 attention 커널이 prefill 7.6배, decode 4.9배.QSA scores average-compressed blocks of r = 4 keys; attention kernels 7.6× faster in prefill and 4.9× in decode at 1M.
- DeepSeek-AI, DeepSeek-V4 (2026) — CSA(m=4 압축 + indexer top-k, Pro 1024)와 HCA(m'=128 압축 + dense), 128 토큰 window, FP4 indexer.CSA (m = 4 compression + indexer top-k, 1024 in Pro) and HCA (m' = 128 compression, read densely), a 128-token window and an FP4 indexer.
- Hugging Face config.json of DeepSeek-V3.2, DeepSeek-V4-Pro and Qwen3.8-Flash-Next — index_n_heads, index_head_dim, index_topk, compress_ratios, indexer_budget, indexer_compress_ratio 값.The index_n_heads, index_head_dim, index_topk, compress_ratios, indexer_budget and indexer_compress_ratio values.