The design-space lesson showed that the cache bill grows only through full-attention layers, as (bytes per entry) × (entries) × (layers that keep them). This lesson is about the first and third factors. The second — storing fewer entries per token, or reading fewer of them — is the sparse-attention lesson; replacing attention by a fixed-size state is linear attention and SSMs.
We take three questions in turn. How small can one entry be before quality suffers, and what does each answer do to the speed of decode (not only its memory)? Why does MLA need a separate positional key, and what did later models do instead? And if most layers only look at a window, what do we lose?
Sharing heads: MHA → GQA → MQA
Multi-head attention keeps a key and a value per head: numbers per token and layer. MQA (Shazeer 2019) lets all query heads share one K/V head; GQA (Ainslie et al. 2023) shares one K/V head per group of query heads:
Mathematically GQA is MHA with the K/V heads repeated times (the code below checks it), so an MHA checkpoint can be “uptrained” into GQA by mean-pooling its K/V heads; the GQA paper does it with 5% of the original pre-training compute. Qwen3-235B uses 64 query heads over 4 KV heads (), gpt-oss 64 over 8, MAI-Base-2’s global layers 96 over 2.
The less obvious consequence is on speed. In decode, each cached K/V byte is read once per step and used by the query heads of its group. Per cached token and layer, the attention core does FLOPs (QK and AV) and reads bytes in BF16, so
With between 1 and 16, decode attention sits far below an H100’s ridge of roughly 295 FLOPs/byte (989 TFLOP/s BF16 ÷ 3.35 TB/s): it is memory-bound, and its time is the KV bytes divided by bandwidth. Batching does not help, because every sequence has its own KV. So for GQA, fewer bytes is the same thing as faster.
A low-rank latent: MLA
MLA (DeepSeek-V2) caches one latent per token and reconstructs per-head keys and values, , . Unlike GQA, every head keeps its own K and V; the constraint is on rank, not on sharing. The equation that matters is the one for decode. Substituting,
Absorb into the query and into the output projection, and decode becomes multi-query attention over the latent itself: one shared “head” of width (plus the RoPE key, below), read by all query heads. That is the “MQA mode” of DeepSeek-V3.1/V3.2’s inference code, used for decode, while training and prefill use “MHA mode” and expand the latent into per-head K and V once per token (V3.2 lesson).
Now redo the intensity count. Per cached token: bytes; FLOPs for QK and for AV. For DeepSeek-V3 (, , ):
MLA moves decode attention to the ridge. The cache is 57× smaller than MHA’s, but the FLOPs per cached token are 3.4× larger than in MHA mode (where each head works on a 192-wide key and a 128-wide value) — in decode every head works on the 512-wide latent. That is why the head count is an expensive knob in MLA: Kimi K2 halved it to 64 (intensity ~121) citing long-context inference FLOPs, and the design-space lesson reproduced its +83%. It is also why DeepSeek’s next step (DSA) attacks the number of entries read, not their size.
→ Go deeper: the ridge point and why decode attention has a fixed arithmetic intensity are built up in The roofline and inference metrics.
설계 공간 레슨은 cache 청구서가 full attention 층을 통해서만, (항목당 바이트) × (항목 수) × (그것을 들고 있는 층 수)로 커진다는 것을 보였다. 이 레슨은 첫째와 셋째 인수를 다룬다. 둘째, 토큰당 항목을 덜 저장하거나 덜 읽는 것은 sparse attention 레슨이고, attention을 고정 크기 state로 바꾸는 것은 linear attention과 SSM이다.
질문 세 개를 차례로 다룬다. 항목 하나를 품질 손실 없이 얼마나 작게 만들 수 있고, 각 답은 decode의 메모리뿐 아니라 속도에 무엇을 하는가? MLA는 왜 별도의 위치 key가 필요하고, 이후 모델들은 대신 무엇을 했는가? 대부분의 층이 window만 본다면 무엇을 잃는가?
Head 공유: MHA → GQA → MQA
multi-head attention은 head마다 key와 value를 둔다. 토큰·층당 개다. MQA(Shazeer 2019)는 모든 query head가 K/V head 하나를 공유하고, GQA(Ainslie et al. 2023)는 query head 개로 된 그룹마다 K/V head 하나를 공유한다.
수학적으로 GQA는 K/V head를 번 반복한 MHA다(아래 코드가 확인한다). 그래서 MHA checkpoint의 K/V head를 평균 내 GQA로 “uptrain”할 수 있고, GQA 논문은 원래 사전학습 계산의 5%로 그렇게 한다. Qwen3-235B는 query head 64개에 KV head 4개(), gpt-oss는 64 대 8, MAI-Base-2의 전역 층은 96 대 2다.
덜 뻔한 결과는 속도에 있다. decode에서 캐시된 K/V 바이트는 step마다 한 번 읽히고 그 그룹의 query head 개가 쓴다. 캐시된 토큰·층당 attention core는 FLOPs(QK와 AV)를 하고 BF16으로 바이트를 읽으므로
가 1에서 16 사이이면 decode attention은 H100의 ridge 약 295 FLOPs/바이트(BF16 989 TFLOP/s ÷ 3.35 TB/s)보다 한참 아래에 있다. memory-bound이고, 시간은 KV 바이트 ÷ 대역폭이다. batching도 소용없다. 시퀀스마다 KV가 따로 있기 때문이다. 그래서 GQA에서는 바이트를 줄이는 것이 곧 빨라지는 것이다.
저차원 latent: MLA
MLA(DeepSeek-V2)는 토큰마다 latent 하나를 캐시하고 head별 key와 value를 복원한다. , . GQA와 달리 모든 head가 자기 K와 V를 가진다. 제약은 공유가 아니라 rank다. 중요한 식은 decode의 식이다. 대입하면
를 query에, 를 출력 projection에 흡수하면 decode는 latent 자체 위의 multi-query attention이 된다. 폭 인 공유 “head” 하나(아래의 RoPE key 포함)를 query head 개가 모두 읽는다. DeepSeek-V3.1/V3.2 추론 코드의 “MQA 모드”가 이것이고 decode에 쓰며, 학습과 prefill은 “MHA 모드”로 토큰마다 한 번 latent를 head별 K, V로 펼친다(V3.2 레슨).
이제 강도를 다시 세자. 캐시된 토큰당 바이트, FLOPs는 QK에 , AV에 . DeepSeek-V3(, , )이면
MLA는 decode attention을 ridge로 옮긴다. cache는 MHA보다 57배 작지만, 캐시된 토큰당 FLOPs는 MHA 모드(head마다 폭 192인 key와 폭 128인 value)보다 3.4배 크다. decode에서는 모든 head가 폭 512인 latent 위에서 일하기 때문이다. 그래서 MLA에서 head 수는 비싼 손잡이다. Kimi K2는 긴 문맥 추론 FLOPs를 이유로 head를 64개(강도 ~121)로 줄였고, 설계 공간 레슨에서 그 +83%를 재현했다. DeepSeek의 다음 단계(DSA)가 항목의 크기가 아니라 읽는 항목의 수를 공략하는 이유이기도 하다.
→ 더 깊이: ridge point와, decode attention의 산술 강도가 왜 고정되는지는 Roofline과 추론 지표에서 차근차근 쌓는다.
Things to see: the GQA points lie on one line of slope −1 in log–log (halving halves the bytes and doubles the intensity), and no GQA setting reaches the ridge without collapsing to MQA with 256+ heads. MLA leaves that line. Drag from 512 to 2048: the cache quadruples but the intensity barely moves (it saturates at about ). Note what the chart does not show: the quality side. The V2 report compared MLA with MHA and GQA directly and found MLA at least as good as MHA at much smaller cache (V3 lesson); GQA at very small loses quality, which is why nobody ships .
RoPE and the latent
Absorption needs to sit directly between and . RoPE rotates keys by an angle that depends on their position : . The matrix between query and latent now changes with every cached position, so it cannot be pre-multiplied into the query. Three answers are in use:
- Decoupled RoPE key (DeepSeek-V2/V3, Kimi K2). Put position in a separate small key shared by all heads, and concatenate: logit . The cache becomes numbers.
- No positional encoding in the global layers (NoPE). Kimi K3’s MLA layers have no RoPE at all and let the KDA layers carry recency; MAI-Base’s global layers and Nemotron 3’s attention layers are NoPE as well, with position carried by local RoPE layers or Mamba. Absorption is then exact. The cost is that the global layers can only match on content. Qwen3.8-Flash-Next tried NoPE full-attention layers and kept RoPE: pre-training looked identical but post-trained models fell into endless generation far more often (Qwen3.8 lesson).
- Partial RoPE on a single shared head (DeepSeek-V4). Its compressed entries are one 512-wide MQA head that serves as both key and value; RoPE is applied to the last 64 dimensions only, and the output’s last 64 dimensions are rotated back by so that only relative position survives (V4 lesson).
Fields of view: sliding windows, sinks and interleaving
A sliding-window layer attends to the last tokens only; its cache is entries regardless of and its attention cost is per token. Alone it cannot retrieve anything older than , so windows are always interleaved with full layers. Released ratios:
| Model | local : global | window | sink |
|---|---|---|---|
| Gemma 2 → Gemma 3 | 1:1 → 5:1 | 4096 → 1024 | – |
| gpt-oss | 1:1 | 128 | learned per-head scalar |
| MiMo-V2-Flash | 5:1 | 128 | learned sink bias |
| MAI-Base-1/2 | 5:1 | 512 (Base-1) | – |
Gemma 3 reports “minimal impact on perplexity … even with 7-to-1”, and MiMo-V2 found its 128 window better at long context than 512, hypothesising a division of labour: small windows do local work and leave long-range work to the global layers (MiMo lesson).
Sinks. A softmax must put mass 1 somewhere. When nothing in the window is relevant, trained models dump the mass on the first tokens (the “attention sink”); with a window, those tokens slide out and the model breaks. StreamingLLM keeps the KV of a few initial tokens; gpt-oss and MiMo add a learned logit per head to the denominator, i.e. a virtual key with value 0:
With all logits near 0 in a 128-token window, the sink takes half the mass at (checked below).
What interleaving costs. Memory falls almost in proportion to the share of local layers. Single retrievals are unaffected as long as one global layer exists. What can break is composition: a chain of long-range lookups, each depending on the previous one, needs one global layer per hop, because a layer retrieves at most once before the next layer can use the result. The figure makes that argument quantitative with a toy (stated assumptions in the caption); the per-hop success uses the softmax mass of a needle among distractors, which the NumPy block checks against real random keys.
볼 것. GQA 점들은 log–log에서 기울기 −1인 한 직선 위에 있다(를 절반으로 하면 바이트는 절반, 강도는 두 배). head가 256개 이상인 MQA로 무너지지 않는 한 어떤 GQA 설정도 ridge에 닿지 않는다. MLA는 그 직선을 벗어난다. 를 512에서 2048로 끌면 cache는 네 배가 되지만 강도는 거의 그대로다(약 에서 포화). 그림이 보여 주지 않는 것은 품질 쪽이다. V2 보고서는 MLA를 MHA, GQA와 직접 비교해 훨씬 작은 cache로 MHA 이상이라고 보고했다(V3 레슨). 가 아주 작은 GQA는 품질을 잃고, 그래서 아무도 를 내놓지 않는다.
RoPE와 latent
흡수가 되려면 가 와 사이에 바로 있어야 한다. RoPE는 key를 위치 에 따라 회전한다. . query와 latent 사이의 행렬이 캐시된 위치마다 달라지니 query에 미리 곱해 둘 수 없다. 쓰이는 답은 세 가지다.
- 분리된 RoPE key(DeepSeek-V2/V3, Kimi K2). 위치를 모든 head가 공유하는 작은 별도 key 에 싣고 이어 붙인다. logit . cache는 개가 된다.
- 전역 층에 위치 인코딩 없음(NoPE). Kimi K3의 MLA 층에는 RoPE가 아예 없고 최근성은 KDA 층이 맡는다. MAI-Base의 전역 층과 Nemotron 3의 attention 층도 NoPE이고, 위치는 local RoPE 층이나 Mamba가 나른다. 그러면 흡수가 정확하다. 대가는 전역 층이 내용으로만 맞출 수 있다는 것이다. Qwen3.8-Flash-Next는 NoPE full attention을 시도했다가 RoPE를 유지했다. 사전학습에서는 똑같아 보였지만 사후학습된 모델이 훨씬 자주 끝없는 생성에 빠졌다(Qwen3.8 레슨).
- 공유 head 하나에 partial RoPE(DeepSeek-V4). 압축 항목은 key와 value를 겸하는 폭 512짜리 MQA head 하나이고, RoPE는 마지막 64차원에만 걸며, 출력의 마지막 64차원을 만큼 되돌려 상대 위치만 남긴다(V4 레슨).
시야: sliding window, sink, 섞어 쌓기
sliding window 층은 최근 개 토큰만 본다. cache는 와 무관하게 개이고 attention 비용은 토큰당 다. 혼자서는 보다 오래된 것을 꺼낼 수 없으니 window는 늘 full 층과 섞어 쌓는다. 공개된 비율:
| 모델 | local : global | window | sink |
|---|---|---|---|
| Gemma 2 → Gemma 3 | 1:1 → 5:1 | 4096 → 1024 | – |
| gpt-oss | 1:1 | 128 | head마다 학습되는 스칼라 |
| MiMo-V2-Flash | 5:1 | 128 | 학습되는 sink bias |
| MAI-Base-1/2 | 5:1 | 512 (Base-1) | – |
Gemma 3는 “7:1에서도 perplexity 영향이 미미하다”고 보고하고, MiMo-V2는 긴 문맥에서 window 128이 512보다 낫다는 것을 발견하고 분업 가설을 냈다. 작은 window는 지역 일을 하고 먼 거리 일은 전역 층에 맡긴다는 것이다(MiMo 레슨).
Sink. softmax는 질량 1을 어딘가에 놓아야 한다. window 안에 관련된 것이 없으면 학습된 모델은 질량을 첫 토큰들에 버린다(“attention sink”). window가 있으면 그 토큰들이 밀려나고 모델이 무너진다. StreamingLLM은 초기 토큰 몇 개의 KV를 남겨 두고, gpt-oss와 MiMo는 head마다 학습되는 logit 를 분모에 더한다. 값이 0인 가상 key다.
128 토큰 window에서 logit이 모두 0 근처이면 에서 sink가 질량의 절반을 가져간다(아래에서 확인한다).
섞어 쌓기의 대가. 메모리는 local 층 비율에 거의 비례해 준다. 전역 층이 하나라도 있으면 단일 검색은 영향을 받지 않는다. 깨질 수 있는 것은 합성이다. 앞의 결과에 의존하는 먼 거리 조회의 사슬은 hop마다 전역 층 하나가 필요하다. 한 층은 다음 층이 결과를 쓰기 전에 최대 한 번 꺼내기 때문이다. 그림은 이 논증을 장난감으로 정량화한다(가정은 캡션에 있다). hop 성공 확률은 방해 key 개 사이 needle의 softmax 질량을 쓰고, NumPy 블록이 그것을 실제 무작위 key로 확인한다.
At the default (5:1, W = 1K, T = 128K) the layout keeps 8 global layers and 17% of the all-global KV; chains of 1–4 hops succeed as often as with all-global layers, 6 hops drop to 0.91, 8 hops to 0.38 and longer chains essentially never finish. Push the ratio to 11:1 (4 global layers) and 4-hop chains fall to 0.63, 6-hop chains to 0.03. Lower the needle margin or raise and every curve sinks: dilution makes each hop less certain, and a chain multiplies those uncertainties. Raising helps only when is a sizeable fraction of . Real models are not this crisp (they can also compose inside the residual stream and use the local layers for nearby hops), but the toy explains why designers keep a floor on global layers, and why multi-hop long-context benchmarks are where aggressive ratios show their cost.
Building it
import numpy as np
rs = np.random.default_rng(0)
def softmax(x, axis=-1):
x = x - x.max(axis, keepdims=True); e = np.exp(x); return e / e.sum(axis, keepdims=True)
def rope(x, pos, base=10000.0): # rotate pairs (2i, 2i+1) of the last axis by pos * theta_i
half = x.shape[-1] // 2
ang = np.asarray(pos)[..., None] * base ** (-np.arange(half) / half)
c, s = np.cos(ang), np.sin(ang)
out = np.empty_like(x)
out[..., 0::2] = x[..., 0::2] * c - x[..., 1::2] * s
out[..., 1::2] = x[..., 0::2] * s + x[..., 1::2] * c
return out
# ---- 1. GQA is MHA with K/V heads repeated -------------------------------------
T, d, nh, nkv, dh = 12, 64, 8, 2, 16
X = rs.standard_normal((T, d))
Wq, Wk, Wv = (rs.standard_normal((d, n * dh)) / np.sqrt(d) for n in (nh, nkv, nkv))
q = (X @ Wq).reshape(T, nh, dh); k = (X @ Wk).reshape(T, nkv, dh); v = (X @ Wv).reshape(T, nkv, dh)
mask = np.tril(np.ones((T, T), bool))
def attn(q, k, v): # q, k, v: [T, H, dh] with the same H
s = np.einsum('thd,shd->hts', q, k) / np.sqrt(q.shape[-1])
return np.einsum('hts,shd->thd', softmax(np.where(mask, s, -np.inf)), v)
g = nh // nkv
out_rep = attn(q, np.repeat(k, g, axis=1), np.repeat(v, g, axis=1)) # materialise the repeat
qg = q.reshape(T, nkv, g, dh) # or group the queries
s = np.einsum('tkgd,skd->kgts', qg, k) / np.sqrt(dh)
out_grp = np.einsum('kgts,skd->tkgd', softmax(np.where(mask, s, -np.inf)), v).reshape(T, nh, dh)
print("GQA: repeat-KV == grouped queries:", np.allclose(out_rep, out_grp), f"| KV per token: {2*nkv*dh} numbers vs MHA {2*nh*dh}")
# ---- 2. MLA: training (MHA) mode == decode (absorbed MQA) mode ------------------
d, nh, dn, dr, dv, dc, T = 64, 4, 16, 8, 16, 12, 10
W_DKV = rs.standard_normal((d, dc)) / np.sqrt(d) # h -> latent c (cached)
W_KR = rs.standard_normal((d, dr)) / np.sqrt(d) # h -> shared RoPE key (cached)
W_UK = rs.standard_normal((nh, dc, dn)) / np.sqrt(dc) # latent -> per-head content key
W_UV = rs.standard_normal((nh, dc, dv)) / np.sqrt(dc) # latent -> per-head value
W_Q = rs.standard_normal((nh, d, dn + dr)) / np.sqrt(d)
W_O = rs.standard_normal((nh, dv, d)) / np.sqrt(nh * dv)
H = rs.standard_normal((T, d)); pos = np.arange(T); t = T - 1
c = H @ W_DKV # [T, dc] cache
kR = rope(H @ W_KR, pos) # [T, dr] cache
qa = np.einsum('d,hde->he', H[t], W_Q)
qC, qR = qa[:, :dn], rope(qa[:, dn:], t)
scale = 1 / np.sqrt(dn + dr)
# MHA mode: expand the latent into per-head K and V (what training/prefill does)
kC = np.einsum('tc,hcn->htn', c, W_UK); V = np.einsum('tc,hcv->htv', c, W_UV)
a = softmax((np.einsum('hn,htn->ht', qC, kC) + qR @ kR.T) * scale)
o_mha = np.einsum('ht,htv,hvd->d', a, V, W_O)
# MQA mode: absorb W_UK into the query and W_UV into the output; attend over the shared latent entry
q_lat = np.einsum('hn,hcn->hc', qC, W_UK) # [nh, dc]
a2 = softmax((q_lat @ c.T + qR @ kR.T) * scale) # every head reads the same [c ; kR]
ctx_lat = a2 @ c # [nh, dc] attention over the latent itself
W_OV = np.einsum('hcv,hvd->hcd', W_UV, W_O) # absorbed output projection
o_mqa = np.einsum('hc,hcd->d', ctx_lat, W_OV)
print("MLA: MHA mode == absorbed MQA mode:", np.allclose(o_mha, o_mqa))
# cost per cached token for one decoded query (multiply-adds)
for name, nh_, dc_, dn_, dr_, dv_ in [("toy", nh, dc, dn, dr, dv), ("DeepSeek-V3", 128, 512, 128, 64, 128)]:
mha_macs = nh_ * ((dn_ + dr_) + dv_) + dc_ * nh_ * (dn_ + dv_) # + re-expanding this token's K,V
mqa_macs = nh_ * ((dc_ + dr_) + dc_)
byts = (dc_ + dr_) * 2
print(f" {name:12s} bytes/entry {byts:5d} | MQA mode {mqa_macs:7d} MAC -> {2*mqa_macs/byts:6.1f} FLOP/B"
f" | MHA mode if K,V were re-expanded every step {mha_macs:8d} MAC")
# ---- 3. why RoPE cannot live inside the latent --------------------------------
kC_rot = np.stack([rope(kC[:, j], j) for j in range(T)], 1) # RoPE on the up-projected key
target = np.einsum('hn,htn->ht', rope(qC, t), kC_rot)
fixed = np.einsum('hc,tc->ht', np.einsum('hn,hcn->hc', rope(qC, t), W_UK), c)
print("absorb W_UK with RoPE inside k^C: max logit error", np.abs(target - fixed).max().round(3),
"| content part without RoPE (position in k^R):", np.abs(np.einsum('hn,htn->ht', qC, kC) - q_lat @ c.T).max() < 1e-12)
# ---- 4. sliding window + a learned sink -----------------------------------------
def window_attn(scores, W, sink=None):
s = scores.copy(); n = len(s); s[: max(0, n - W)] = -np.inf # keep only the last W keys
if sink is not None: s = np.append(s, sink) # virtual key with value 0
p = softmax(s); return p[:n].sum()
noise = rs.normal(0, 0.3, 4096) # no relevant key in the window
for sink in (None, 0.0, np.log(128), 8.0):
print(f" window 128, sink logit {sink if sink is None else round(sink, 2)}: mass on real tokens {window_attn(noise, 128, sink):.3f}")
# ---- 5. dilution: how sure is a single retrieval at context n? ----------------
dk, s_needle = 128, 14.0
for n in (4096, 32768):
K = rs.standard_normal((n, dk)) / np.sqrt(dk) # q.k ~ N(0, 1)
q = rs.standard_normal(dk); q *= np.sqrt(dk) / np.linalg.norm(q)
logits = K @ q
logits[n // 3] = s_needle
p = softmax(logits)[n // 3]
print(f" n={n:6d}: needle mass {p:.3f} vs formula e^s/(e^s+(n-1)e^0.5) = {np.exp(s_needle)/(np.exp(s_needle)+(n-1)*np.exp(0.5)):.3f}")Part 2 is the important check: the two modes produce the same output to machine precision, so the choice between them is purely about cost. Re-expanding the cache every decode step would cost about 120× more multiply-adds per cached token than the absorbed form for V3; absorbing costs 3.4× more than MHA mode on its narrower per-head keys and values, but reads 57× fewer bytes than an MHA cache. Part 4 reproduces the sink arithmetic ( → half the mass), and part 5 confirms the dilution formula used in the figure.
import torch
import torch.nn as nn
class MLA(nn.Module):
"""Single-layer MLA (no query compression), decoupled RoPE key. rope(x, pos) rotates the last dim."""
def __init__(self, d, nh, dn=128, dr=64, dv=128, dc=512):
super().__init__()
self.nh, self.dn, self.dr, self.dv, self.dc = nh, dn, dr, dv, dc
self.wq = nn.Linear(d, nh * (dn + dr), bias=False)
self.wdkv = nn.Linear(d, dc + dr, bias=False) # latent c and the shared RoPE key
self.wuk = nn.Parameter(torch.randn(nh, dc, dn) / dc**0.5)
self.wuv = nn.Parameter(torch.randn(nh, dc, dv) / dc**0.5)
self.wo = nn.Linear(nh * dv, d, bias=False)
def cache_entry(self, h, pos, rope): # what decode stores: [T, dc + dr]
c, kr = self.wdkv(h).split([self.dc, self.dr], -1)
return torch.cat([c, rope(kr, pos)], -1)
@torch.no_grad()
def decode(self, h_t, t, cache, rope): # h_t: [d], cache: [T, dc + dr]
q = self.wq(h_t).view(self.nh, self.dn + self.dr)
qc, qr = q.split([self.dn, self.dr], -1)
qr = rope(qr, t)
q_lat = torch.einsum("hn,hcn->hc", qc, self.wuk) # absorb W_UK into the query
c, kr = cache.split([self.dc, self.dr], -1)
logits = (q_lat @ c.T + qr @ kr.T) / (self.dn + self.dr) ** 0.5 # [nh, T]: MQA over the latent
ctx = logits.softmax(-1) @ c # [nh, dc]
out = torch.einsum("hc,hcv->hv", ctx, self.wuv) # apply W_UV after attention
return self.wo(out.reshape(-1))DeepSeek-V3 decodes with absorbed MLA: 128 heads read a shared 576-entry (1,152 bytes in BF16) per cached token. Roughly how many FLOPs per byte does the attention core perform, and what does that imply on an H100?
FLOPs per cached token ; bytes ; ratio ≈ 242. GQA’s intensity equals its group size (1–16), so it is memory-bound; MLA sits near the ridge. That is why halving the heads (Kimi K2) or reading fewer entries (DSA) is what speeds up MLA decode, not shrinking the cache further.
Summary
- KV per token per layer: (GQA), (MLA). GQA = MHA with repeated K/V; MLA keeps per-head K/V at rank .
- Decode intensity of the attention core: for GQA (memory-bound), for V3’s MLA (near the ridge) — so MLA’s cost lever is the head count and the number of entries read.
- MLA’s MHA mode (training, prefill) and absorbed MQA mode (decode) are the same function. RoPE breaks absorption, fixed by a decoupled key (V3), NoPE global layers (K3, MAI, Nemotron) or partial RoPE with output counter-rotation (V4).
- Sliding windows need sinks (initial tokens or a learned per-head logit) and interleaving; ratios of 1:1 to 5:1 with windows of 128–1024 are the 2025–26 norm.
- Interleaving cuts memory in proportion and keeps single retrievals, but every dependent long-range hop needs a global layer.
기본값(5:1, W = 1K, T = 128K)에서 이 배치는 전역 층 8개와 전부 전역인 KV의 17%를 유지한다. 1–4 hop 사슬은 전부 전역일 때만큼 성공하고, 6 hop은 0.91, 8 hop은 0.38로 떨어지며, 더 긴 사슬은 거의 끝나지 않는다. 비율을 11:1(전역 층 4개)로 올리면 4 hop 사슬이 0.63, 6 hop이 0.03으로 떨어진다. needle 강도 를 낮추거나 를 올리면 모든 곡선이 가라앉는다. 희석 때문에 hop 하나하나가 덜 확실해지고 사슬은 그 불확실성을 곱한다. 를 키우는 것은 가 의 상당한 비율일 때만 도움이 된다. 실제 모델은 이렇게 칼같지 않다(residual stream 안에서 합성할 수도 있고 가까운 hop에는 local 층을 쓸 수 있다). 그래도 이 장난감은 설계자들이 전역 층 수에 하한을 두는 이유, 그리고 공격적인 비율의 대가가 다중 hop 긴 문맥 벤치마크에서 드러나는 이유를 설명한다.
직접 만들기
import numpy as np
rs = np.random.default_rng(0)
def softmax(x, axis=-1):
x = x - x.max(axis, keepdims=True); e = np.exp(x); return e / e.sum(axis, keepdims=True)
def rope(x, pos, base=10000.0): # 마지막 축의 (2i, 2i+1) 쌍을 pos * theta_i만큼 회전
half = x.shape[-1] // 2
ang = np.asarray(pos)[..., None] * base ** (-np.arange(half) / half)
c, s = np.cos(ang), np.sin(ang)
out = np.empty_like(x)
out[..., 0::2] = x[..., 0::2] * c - x[..., 1::2] * s
out[..., 1::2] = x[..., 0::2] * s + x[..., 1::2] * c
return out
# ---- 1. GQA는 K/V head를 반복한 MHA다 ------------------------------------------
T, d, nh, nkv, dh = 12, 64, 8, 2, 16
X = rs.standard_normal((T, d))
Wq, Wk, Wv = (rs.standard_normal((d, n * dh)) / np.sqrt(d) for n in (nh, nkv, nkv))
q = (X @ Wq).reshape(T, nh, dh); k = (X @ Wk).reshape(T, nkv, dh); v = (X @ Wv).reshape(T, nkv, dh)
mask = np.tril(np.ones((T, T), bool))
def attn(q, k, v): # q, k, v: [T, H, dh], H가 같다
s = np.einsum('thd,shd->hts', q, k) / np.sqrt(q.shape[-1])
return np.einsum('hts,shd->thd', softmax(np.where(mask, s, -np.inf)), v)
g = nh // nkv
out_rep = attn(q, np.repeat(k, g, axis=1), np.repeat(v, g, axis=1)) # 반복을 실제로 만든다
qg = q.reshape(T, nkv, g, dh) # 또는 query를 묶는다
s = np.einsum('tkgd,skd->kgts', qg, k) / np.sqrt(dh)
out_grp = np.einsum('kgts,skd->tkgd', softmax(np.where(mask, s, -np.inf)), v).reshape(T, nh, dh)
print("GQA: repeat-KV == grouped queries:", np.allclose(out_rep, out_grp), f"| KV per token: {2*nkv*dh} numbers vs MHA {2*nh*dh}")
# ---- 2. MLA: 학습(MHA) 모드 == decode(흡수된 MQA) 모드 --------------------------
d, nh, dn, dr, dv, dc, T = 64, 4, 16, 8, 16, 12, 10
W_DKV = rs.standard_normal((d, dc)) / np.sqrt(d) # h -> latent c (캐시)
W_KR = rs.standard_normal((d, dr)) / np.sqrt(d) # h -> 공유 RoPE key (캐시)
W_UK = rs.standard_normal((nh, dc, dn)) / np.sqrt(dc) # latent -> head별 내용 key
W_UV = rs.standard_normal((nh, dc, dv)) / np.sqrt(dc) # latent -> head별 value
W_Q = rs.standard_normal((nh, d, dn + dr)) / np.sqrt(d)
W_O = rs.standard_normal((nh, dv, d)) / np.sqrt(nh * dv)
H = rs.standard_normal((T, d)); pos = np.arange(T); t = T - 1
c = H @ W_DKV # [T, dc] 캐시
kR = rope(H @ W_KR, pos) # [T, dr] 캐시
qa = np.einsum('d,hde->he', H[t], W_Q)
qC, qR = qa[:, :dn], rope(qa[:, dn:], t)
scale = 1 / np.sqrt(dn + dr)
# MHA 모드: latent를 head별 K, V로 펼친다 (학습/prefill)
kC = np.einsum('tc,hcn->htn', c, W_UK); V = np.einsum('tc,hcv->htv', c, W_UV)
a = softmax((np.einsum('hn,htn->ht', qC, kC) + qR @ kR.T) * scale)
o_mha = np.einsum('ht,htv,hvd->d', a, V, W_O)
# MQA 모드: W_UK는 query에, W_UV는 출력에 흡수하고 공유 latent 항목 위에서 attention
q_lat = np.einsum('hn,hcn->hc', qC, W_UK) # [nh, dc]
a2 = softmax((q_lat @ c.T + qR @ kR.T) * scale) # 모든 head가 같은 [c ; kR]를 읽는다
ctx_lat = a2 @ c # [nh, dc] latent 자체 위의 attention
W_OV = np.einsum('hcv,hvd->hcd', W_UV, W_O) # 흡수된 출력 projection
o_mqa = np.einsum('hc,hcd->d', ctx_lat, W_OV)
print("MLA: MHA mode == absorbed MQA mode:", np.allclose(o_mha, o_mqa))
# decode query 하나에 대해 캐시된 토큰당 비용 (곱셈-덧셈)
for name, nh_, dc_, dn_, dr_, dv_ in [("toy", nh, dc, dn, dr, dv), ("DeepSeek-V3", 128, 512, 128, 64, 128)]:
mha_macs = nh_ * ((dn_ + dr_) + dv_) + dc_ * nh_ * (dn_ + dv_) # + 이 토큰의 K,V를 다시 펼치는 비용
mqa_macs = nh_ * ((dc_ + dr_) + dc_)
byts = (dc_ + dr_) * 2
print(f" {name:12s} bytes/entry {byts:5d} | MQA mode {mqa_macs:7d} MAC -> {2*mqa_macs/byts:6.1f} FLOP/B"
f" | MHA mode if K,V were re-expanded every step {mha_macs:8d} MAC")
# ---- 3. RoPE가 latent 안에 있을 수 없는 이유 ------------------------------------
kC_rot = np.stack([rope(kC[:, j], j) for j in range(T)], 1) # up-projection한 key에 RoPE
target = np.einsum('hn,htn->ht', rope(qC, t), kC_rot)
fixed = np.einsum('hc,tc->ht', np.einsum('hn,hcn->hc', rope(qC, t), W_UK), c)
print("absorb W_UK with RoPE inside k^C: max logit error", np.abs(target - fixed).max().round(3),
"| content part without RoPE (position in k^R):", np.abs(np.einsum('hn,htn->ht', qC, kC) - q_lat @ c.T).max() < 1e-12)
# ---- 4. sliding window + 학습되는 sink -------------------------------------------
def window_attn(scores, W, sink=None):
s = scores.copy(); n = len(s); s[: max(0, n - W)] = -np.inf # 최근 W개 key만 남긴다
if sink is not None: s = np.append(s, sink) # 값이 0인 가상 key
p = softmax(s); return p[:n].sum()
noise = rs.normal(0, 0.3, 4096) # window 안에 관련 key 없음
for sink in (None, 0.0, np.log(128), 8.0):
print(f" window 128, sink logit {sink if sink is None else round(sink, 2)}: mass on real tokens {window_attn(noise, 128, sink):.3f}")
# ---- 5. 희석: 문맥 n에서 검색 한 번은 얼마나 확실한가 --------------------------
dk, s_needle = 128, 14.0
for n in (4096, 32768):
K = rs.standard_normal((n, dk)) / np.sqrt(dk) # q.k ~ N(0, 1)
q = rs.standard_normal(dk); q *= np.sqrt(dk) / np.linalg.norm(q)
logits = K @ q
logits[n // 3] = s_needle
p = softmax(logits)[n // 3]
print(f" n={n:6d}: needle mass {p:.3f} vs formula e^s/(e^s+(n-1)e^0.5) = {np.exp(s_needle)/(np.exp(s_needle)+(n-1)*np.exp(0.5)):.3f}")중요한 확인은 2번이다. 두 모드는 기계 정밀도까지 같은 출력을 내므로 둘 사이의 선택은 순전히 비용 문제다. V3에서 decode step마다 cache를 다시 펼치면 캐시된 토큰당 곱셈-덧셈이 흡수된 형태보다 약 120배 많다. 흡수는 더 좁은 head별 key·value 위의 MHA 모드보다 3.4배 많은 계산을 하지만, MHA cache보다 읽는 바이트가 57배 적다. 4번은 sink 산수( → 질량 절반)를, 5번은 그림에 쓴 희석 식을 확인한다.
import torch
import torch.nn as nn
class MLA(nn.Module):
"""MLA 한 층 (query 압축 없음), 분리된 RoPE key. rope(x, pos)는 마지막 차원을 회전한다."""
def __init__(self, d, nh, dn=128, dr=64, dv=128, dc=512):
super().__init__()
self.nh, self.dn, self.dr, self.dv, self.dc = nh, dn, dr, dv, dc
self.wq = nn.Linear(d, nh * (dn + dr), bias=False)
self.wdkv = nn.Linear(d, dc + dr, bias=False) # latent c와 공유 RoPE key
self.wuk = nn.Parameter(torch.randn(nh, dc, dn) / dc**0.5)
self.wuv = nn.Parameter(torch.randn(nh, dc, dv) / dc**0.5)
self.wo = nn.Linear(nh * dv, d, bias=False)
def cache_entry(self, h, pos, rope): # decode가 저장하는 것: [T, dc + dr]
c, kr = self.wdkv(h).split([self.dc, self.dr], -1)
return torch.cat([c, rope(kr, pos)], -1)
@torch.no_grad()
def decode(self, h_t, t, cache, rope): # h_t: [d], cache: [T, dc + dr]
q = self.wq(h_t).view(self.nh, self.dn + self.dr)
qc, qr = q.split([self.dn, self.dr], -1)
qr = rope(qr, t)
q_lat = torch.einsum("hn,hcn->hc", qc, self.wuk) # W_UK를 query에 흡수
c, kr = cache.split([self.dc, self.dr], -1)
logits = (q_lat @ c.T + qr @ kr.T) / (self.dn + self.dr) ** 0.5 # [nh, T]: latent 위의 MQA
ctx = logits.softmax(-1) @ c # [nh, dc]
out = torch.einsum("hc,hcv->hv", ctx, self.wuv) # W_UV는 attention 뒤에
return self.wo(out.reshape(-1))DeepSeek-V3는 흡수된 MLA로 decode한다. head 128개가 캐시된 토큰마다 공유 576개 항목(BF16으로 1,152바이트)을 읽는다. attention core는 바이트당 대략 몇 FLOPs를 하고, H100에서 그것은 무엇을 뜻하는가?
캐시된 토큰당 FLOPs , 바이트 , 비는 약 242다. GQA의 강도는 그룹 크기 (1–16)라 memory-bound이고, MLA는 ridge 근처에 있다. 그래서 MLA decode를 빠르게 하는 것은 cache를 더 줄이는 것이 아니라 head를 절반으로 줄이거나(Kimi K2) 읽는 항목 수를 줄이는 것(DSA)이다.
정리
- 토큰·층당 KV: GQA , MLA . GQA = K/V를 반복한 MHA, MLA는 rank 에서 head별 K/V를 유지한다.
- attention core의 decode 강도: GQA는 (memory-bound), V3의 MLA는 (ridge 근처). 그래서 MLA의 비용 손잡이는 head 수와 읽는 항목 수다.
- MLA의 MHA 모드(학습, prefill)와 흡수된 MQA 모드(decode)는 같은 함수다. RoPE는 흡수를 깨고, 해법은 분리된 key(V3), NoPE 전역 층(K3, MAI, Nemotron), 출력 역회전을 곁들인 partial RoPE(V4)다.
- sliding window에는 sink(초기 토큰 또는 head별 학습 logit)와 섞어 쌓기가 필요하다. 2025–26년의 표준은 window 128–1024에 1:1–5:1이다.
- 섞어 쌓기는 메모리를 비례해 줄이고 단일 검색은 지키지만, 서로 의존하는 먼 거리 hop마다 전역 층이 하나씩 필요하다.
더 읽을거리Further reading
- Ainslie et al., GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (2023) — MHA와 MQA 사이의 그룹 공유, 원래 사전학습 계산의 5%로 MHA checkpoint를 uptrain.Group sharing between MHA and MQA; uptraining an MHA checkpoint with 5% of the original pre-training compute.
- Shazeer, Fast Transformer Decoding: One Write-Head is All You Need (2019) — MQA의 원 논문. decode가 메모리 대역폭에 묶인다는 분석.The original MQA paper and its analysis of decode as memory-bandwidth bound.
- DeepSeek-AI, DeepSeek-V2 (2024) and DeepSeek-V3 Technical Report (2024) — MLA와 decoupled RoPE. V3 설정(d_c 512, d_r 64, head 128)이 이 레슨의 기준값.MLA and decoupled RoPE. The V3 configuration (d_c 512, d_r 64, 128 heads) is this lesson's reference.
- Xiao et al., Efficient Streaming Language Models with Attention Sinks (ICLR 2024) — 초기 토큰의 KV를 남기면 window attention이 회복된다. 4M 토큰 스트리밍, sliding-window 재계산 대비 최대 22.2배.Keeping the KV of the initial tokens recovers window attention; streaming up to 4M tokens, up to 22.2× faster than sliding-window recomputation.
- Gemma Team, Gemma 3 Technical Report (2025) — local:global 5:1, window 1024(Gemma 2는 1:1, 4096). 7:1에서도 perplexity 영향이 미미, global RoPE base 1M / local 10k.Local:global 5:1 with a 1024 window (Gemma 2 was 1:1, 4096); minimal perplexity impact even at 7:1; RoPE base 1M for global and 10k for local layers.
- OpenAI, gpt-oss-120b & gpt-oss-20b Model Card (2025) — 128-token window와 dense를 번갈아, head마다 학습되는 sink 스칼라.128-token windows alternating with dense layers, and a learned per-head sink scalar.