Track VII · Architecture Deep Dives · 03/12

Attention과 KV: MHA → GQA → MLA, sliding window·sink, local/globalAttention and KV: MHA → GQA → MLA, sliding windows and sinks, local/global

KV cache를 줄이는 세 갈래(head 공유 GQA/MQA, 저차원 latent MLA, 층마다 다른 시야 sliding window)를 식과 NumPy로 유도한다. MLA의 학습(MHA) 모드와 decode(흡수된 MQA) 모드가 같은 함수임을 확인하고, RoPE가 왜 latent 밖으로 나가야 하는지와 세 가지 해법(decoupled key, NoPE, partial RoPE)을 비교한다. decode 산술 강도로 MLA가 memory-bound를 벗어나는 이유를, 장난감 다중 hop 검색으로 local:global 비율의 KV–recall 거래를 본다.Derive, with equations and NumPy, the three ways to shrink the KV cache — sharing heads (GQA/MQA), a low-rank latent (MLA), and giving layers different fields of view (sliding windows). Check that MLA's training (MHA) mode and decode (absorbed MQA) mode are the same function, see why RoPE has to live outside the latent and compare the three fixes (decoupled key, NoPE, partial RoPE). Use decode arithmetic intensity to see why MLA leaves the memory-bound regime, and a toy multi-hop retrieval to see the KV-versus-recall trade-off of local:global ratios.

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: 2nhdh2n_hd_h 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 g=nh/nkvg=n_h/n_{kv} query heads:

ot,i=∑s≤tsoftmax⁡s ⁣(qt,i⊤ks,⌈i/g⌉dh) vs,⌈i/g⌉,KV/token/layer=2nkvdh.\mathbf o_{t,i} = \sum_{s\le t}\operatorname{softmax}_s\!\Big(\tfrac{\mathbf q_{t,i}^\top\mathbf k_{s,\lceil i/g\rceil}}{\sqrt{d_h}}\Big)\,\mathbf v_{s,\lceil i/g\rceil},\qquad \text{KV/token/layer} = 2n_{kv}d_h .

Mathematically GQA is MHA with the K/V heads repeated gg 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 (g=16g=16), 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 gg query heads of its group. Per cached token and layer, the attention core does 4nhdh4n_hd_h FLOPs (QK and AV) and reads 2nkvdh⋅22n_{kv}d_h\cdot 2 bytes in BF16, so

arithmetic intensity=4nhdh4nkvdh=gFLOPs per byte.\text{arithmetic intensity} = \frac{4n_hd_h}{4n_{kv}d_h} = g \quad \text{FLOPs per byte}.

With gg 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 ct=WDKVht∈Rdc\mathbf c_t = W^{DKV}\mathbf h_t\in\mathbb R^{d_c} per token and reconstructs per-head keys and values, kt,iC=WiUKct\mathbf k^C_{t,i} = W^{UK}_i\mathbf c_t, vt,i=WiUVct\mathbf v_{t,i}=W^{UV}_i\mathbf c_t. 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,

qt,iC⊤ks,iC=(WiUK⊤qt,iC)⊤cs,ot=∑iWiO∑sat,s,i WiUVcs=∑i(WiOWiUV)∑sat,s,i cs.\mathbf q_{t,i}^{C\top}\mathbf k^C_{s,i} = \big(W^{UK\top}_i\mathbf q^C_{t,i}\big)^\top\mathbf c_s,\qquad \mathbf o_t = \sum_i W^O_i \sum_s a_{t,s,i}\,W^{UV}_i\mathbf c_s = \sum_i \big(W^O_iW^{UV}_i\big)\sum_s a_{t,s,i}\,\mathbf c_s .

Absorb WiUKW^{UK}_i into the query and WiUVW^{UV}_i into the output projection, and decode becomes multi-query attention over the latent itself: one shared “head” of width dcd_c (plus the RoPE key, below), read by all nhn_h 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: (dc+dr)⋅2(d_c+d_r)\cdot 2 bytes; FLOPs 2nh(dc+dr)2n_h(d_c+d_r) for QK and 2nhdc2n_hd_c for AV. For DeepSeek-V3 (nh=128n_h=128, dc=512d_c=512, dr=64d_r=64):

2⋅128⋅(512+64+512)576⋅2=278,5281,152≈242 FLOPs/byte.\frac{2\cdot128\cdot(512+64+512)}{576\cdot 2} = \frac{278{,}528}{1{,}152} \approx 242 \ \text{FLOPs/byte}.

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를 둔다. 토큰·층당 2nhdh2n_hd_h개다. MQA(Shazeer 2019)는 모든 query head가 K/V head 하나를 공유하고, GQA(Ainslie et al. 2023)는 query head g=nh/nkvg=n_h/n_{kv}개로 된 그룹마다 K/V head 하나를 공유한다.

ot,i=∑s≤tsoftmax⁡s ⁣(qt,i⊤ks,⌈i/g⌉dh) vs,⌈i/g⌉,토큰⋅층당 KV=2nkvdh.\mathbf o_{t,i} = \sum_{s\le t}\operatorname{softmax}_s\!\Big(\tfrac{\mathbf q_{t,i}^\top\mathbf k_{s,\lceil i/g\rceil}}{\sqrt{d_h}}\Big)\,\mathbf v_{s,\lceil i/g\rceil},\qquad \text{토큰·층당 KV} = 2n_{kv}d_h .

수학적으로 GQA는 K/V head를 gg번 반복한 MHA다(아래 코드가 확인한다). 그래서 MHA checkpoint의 K/V head를 평균 내 GQA로 “uptrain”할 수 있고, GQA 논문은 원래 사전학습 계산의 5%로 그렇게 한다. Qwen3-235B는 query head 64개에 KV head 4개(g=16g=16), gpt-oss는 64 대 8, MAI-Base-2의 전역 층은 96 대 2다.

덜 뻔한 결과는 속도에 있다. decode에서 캐시된 K/V 바이트는 step마다 한 번 읽히고 그 그룹의 query head gg개가 쓴다. 캐시된 토큰·층당 attention core는 4nhdh4n_hd_h FLOPs(QK와 AV)를 하고 BF16으로 2nkvdh⋅22n_{kv}d_h\cdot 2바이트를 읽으므로

산술 강도=4nhdh4nkvdh=gFLOPs/바이트.\text{산술 강도} = \frac{4n_hd_h}{4n_{kv}d_h} = g \quad \text{FLOPs/바이트}.

gg가 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 ct=WDKVht∈Rdc\mathbf c_t = W^{DKV}\mathbf h_t\in\mathbb R^{d_c} 하나를 캐시하고 head별 key와 value를 복원한다. kt,iC=WiUKct\mathbf k^C_{t,i} = W^{UK}_i\mathbf c_t, vt,i=WiUVct\mathbf v_{t,i}=W^{UV}_i\mathbf c_t. GQA와 달리 모든 head가 자기 K와 V를 가진다. 제약은 공유가 아니라 rank다. 중요한 식은 decode의 식이다. 대입하면

qt,iC⊤ks,iC=(WiUK⊤qt,iC)⊤cs,ot=∑iWiO∑sat,s,i WiUVcs=∑i(WiOWiUV)∑sat,s,i cs.\mathbf q_{t,i}^{C\top}\mathbf k^C_{s,i} = \big(W^{UK\top}_i\mathbf q^C_{t,i}\big)^\top\mathbf c_s,\qquad \mathbf o_t = \sum_i W^O_i \sum_s a_{t,s,i}\,W^{UV}_i\mathbf c_s = \sum_i \big(W^O_iW^{UV}_i\big)\sum_s a_{t,s,i}\,\mathbf c_s .

WiUKW^{UK}_i를 query에, WiUVW^{UV}_i를 출력 projection에 흡수하면 decode는 latent 자체 위의 multi-query attention이 된다. 폭 dcd_c인 공유 “head” 하나(아래의 RoPE key 포함)를 query head nhn_h개가 모두 읽는다. DeepSeek-V3.1/V3.2 추론 코드의 “MQA 모드”가 이것이고 decode에 쓰며, 학습과 prefill은 “MHA 모드”로 토큰마다 한 번 latent를 head별 K, V로 펼친다(V3.2 레슨).

이제 강도를 다시 세자. 캐시된 토큰당 (dc+dr)⋅2(d_c+d_r)\cdot 2바이트, FLOPs는 QK에 2nh(dc+dr)2n_h(d_c+d_r), AV에 2nhdc2n_hd_c. DeepSeek-V3(nh=128n_h=128, dc=512d_c=512, dr=64d_r=64)이면

2⋅128⋅(512+64+512)576⋅2=278,5281,152≈242 FLOPs/바이트.\frac{2\cdot128\cdot(512+64+512)}{576\cdot 2} = \frac{278{,}528}{1{,}152} \approx 242 \ \text{FLOPs/바이트}.

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과 추론 지표에서 차근차근 쌓는다.

GQA: KV –, 강도intensity – MLA: KV –, 강도intensity –
Each point is one attention design: x = bytes of KV cache per token per layer (BF16), y = FLOPs the decode attention core performs per KV byte it reads. Grey points are released configs; the two coloured points follow the sliders (GQA with your KV-head count, MLA with your latent width dc and a 64-wide RoPE key). Reduce the GQA KV heads: the point slides left and up along a line (intensity = group size). MLA jumps: its latent is shared by every head, so intensity ≈ nh·(2dc+64)/(dc+64) — close to the ridge for DeepSeek-V3's 128 heads, which is why decode attention stops being memory-bound there. 점 하나가 attention 설계 하나다. x = 층·토큰당 KV cache 바이트(BF16), y = decode attention core가 읽는 KV 1바이트당 하는 FLOPs. 회색 점은 공개 config이고, 색 점 둘은 슬라이더를 따른다(KV head 수를 고른 GQA, latent 폭 dc와 폭 64인 RoPE key를 가진 MLA). GQA KV head를 줄이면 점이 직선을 따라 왼쪽 위로 간다(강도 = 그룹 크기). MLA는 도약한다. latent를 모든 head가 공유하므로 강도 ≈ nh·(2dc+64)/(dc+64)이고, DeepSeek-V3의 head 128개면 ridge에 가깝다. 그래서 거기서는 decode attention이 더 이상 memory-bound가 아니다.

Things to see: the GQA points lie on one line of slope −1 in log–log (halving nkvn_{kv} 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 dcd_c from 512 to 2048: the cache quadruples but the intensity barely moves (it saturates at about 2nh2n_h). 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 nkvn_{kv} loses quality, which is why nobody ships g=64g=64.

RoPE and the latent

Absorption needs WiUKW^{UK}_i to sit directly between q\mathbf q and cs\mathbf c_s. RoPE rotates keys by an angle that depends on their position ss: q⊤Rt⊤RsWiUKcs=q⊤Rs−tWiUKcs\mathbf q^\top R_t^\top R_s W^{UK}_i\mathbf c_s = \mathbf q^\top R_{s-t} W^{UK}_i\mathbf c_s. 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:

  1. Decoupled RoPE key (DeepSeek-V2/V3, Kimi K2). Put position in a separate small key ksR=RoPE⁡(WKRhs)∈R64\mathbf k^R_s=\operatorname{RoPE}(W^{KR}\mathbf h_s)\in\mathbb R^{64} shared by all heads, and concatenate: logit =qC⊤WUKcs+qR⊤ksR= \mathbf q^{C\top}W^{UK}\mathbf c_s + \mathbf q^{R\top}\mathbf k^R_s. The cache becomes dc+dr=576d_c+d_r=576 numbers.
  2. 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).
  3. 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 −t-t so that only relative position survives (V4 lesson).

Fields of view: sliding windows, sinks and interleaving

A sliding-window layer attends to the last WW tokens only; its cache is WW entries regardless of TT and its attention cost is O(W)O(W) per token. Alone it cannot retrieve anything older than WW, so windows are always interleaved with full layers. Released ratios:

Modellocal : globalwindowsink
Gemma 2 → Gemma 31:1 → 5:14096 → 1024–
gpt-oss1:1128learned per-head scalar
MiMo-V2-Flash5:1128learned sink bias
MAI-Base-1/25:1512 (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 bhb_h per head to the denominator, i.e. a virtual key with value 0:

ats=eztsebh+∑s′∈N(t)ezts′,∑sats=1−ptsink<1.a_{ts} = \frac{e^{z_{ts}}}{e^{b_h}+\sum_{s'\in\mathcal N(t)}e^{z_{ts'}}},\qquad \sum_s a_{ts} = 1-p^{\text{sink}}_t < 1 .

With all logits near 0 in a 128-token window, the sink takes half the mass at b=ln⁡128≈4.85b=\ln128\approx4.85 (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 nn distractors, which the NumPy block checks against real random keys.

볼 것. GQA 점들은 log–log에서 기울기 −1인 한 직선 위에 있다(nkvn_{kv}를 절반으로 하면 바이트는 절반, 강도는 두 배). head가 256개 이상인 MQA로 무너지지 않는 한 어떤 GQA 설정도 ridge에 닿지 않는다. MLA는 그 직선을 벗어난다. dcd_c를 512에서 2048로 끌면 cache는 네 배가 되지만 강도는 거의 그대로다(약 2nh2n_h에서 포화). 그림이 보여 주지 않는 것은 품질 쪽이다. V2 보고서는 MLA를 MHA, GQA와 직접 비교해 훨씬 작은 cache로 MHA 이상이라고 보고했다(V3 레슨). nkvn_{kv}가 아주 작은 GQA는 품질을 잃고, 그래서 아무도 g=64g=64를 내놓지 않는다.

RoPE와 latent

흡수가 되려면 WiUKW^{UK}_i가 q\mathbf q와 cs\mathbf c_s 사이에 바로 있어야 한다. RoPE는 key를 위치 ss에 따라 회전한다. q⊤Rt⊤RsWiUKcs=q⊤Rs−tWiUKcs\mathbf q^\top R_t^\top R_s W^{UK}_i\mathbf c_s = \mathbf q^\top R_{s-t} W^{UK}_i\mathbf c_s. query와 latent 사이의 행렬이 캐시된 위치마다 달라지니 query에 미리 곱해 둘 수 없다. 쓰이는 답은 세 가지다.

  1. 분리된 RoPE key(DeepSeek-V2/V3, Kimi K2). 위치를 모든 head가 공유하는 작은 별도 key ksR=RoPE⁡(WKRhs)∈R64\mathbf k^R_s=\operatorname{RoPE}(W^{KR}\mathbf h_s)\in\mathbb R^{64}에 싣고 이어 붙인다. logit =qC⊤WUKcs+qR⊤ksR= \mathbf q^{C\top}W^{UK}\mathbf c_s + \mathbf q^{R\top}\mathbf k^R_s. cache는 dc+dr=576d_c+d_r=576개가 된다.
  2. 전역 층에 위치 인코딩 없음(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 레슨).
  3. 공유 head 하나에 partial RoPE(DeepSeek-V4). 압축 항목은 key와 value를 겸하는 폭 512짜리 MQA head 하나이고, RoPE는 마지막 64차원에만 걸며, 출력의 마지막 64차원을 −t-t만큼 되돌려 상대 위치만 남긴다(V4 레슨).

시야: sliding window, sink, 섞어 쌓기

sliding window 층은 최근 WW개 토큰만 본다. cache는 TT와 무관하게 WW개이고 attention 비용은 토큰당 O(W)O(W)다. 혼자서는 WW보다 오래된 것을 꺼낼 수 없으니 window는 늘 full 층과 섞어 쌓는다. 공개된 비율:

모델local : globalwindowsink
Gemma 2 → Gemma 31:1 → 5:14096 → 1024–
gpt-oss1:1128head마다 학습되는 스칼라
MiMo-V2-Flash5:1128학습되는 sink bias
MAI-Base-1/25:1512 (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 bhb_h를 분모에 더한다. 값이 0인 가상 key다.

ats=eztsebh+∑s′∈N(t)ezts′,∑sats=1−ptsink<1.a_{ts} = \frac{e^{z_{ts}}}{e^{b_h}+\sum_{s'\in\mathcal N(t)}e^{z_{ts'}}},\qquad \sum_s a_{ts} = 1-p^{\text{sink}}_t < 1 .

128 토큰 window에서 logit이 모두 0 근처이면 b=ln⁡128≈4.85b=\ln128\approx4.85에서 sink가 질량의 절반을 가져간다(아래에서 확인한다).

섞어 쌓기의 대가. 메모리는 local 층 비율에 거의 비례해 준다. 전역 층이 하나라도 있으면 단일 검색은 영향을 받지 않는다. 깨질 수 있는 것은 합성이다. 앞의 결과에 의존하는 먼 거리 조회의 사슬은 hop마다 전역 층 하나가 필요하다. 한 층은 다음 층이 결과를 쓰기 전에 최대 한 번 꺼내기 때문이다. 그림은 이 논증을 장난감으로 정량화한다(가정은 캡션에 있다). hop 성공 확률은 방해 key nn개 사이 needle의 softmax 질량을 쓰고, NumPy 블록이 그것을 실제 무작위 key로 확인한다.

전역 층global layers – / 48 KV @T (전부 전역 대비)KV @T (vs all-global) – hop 성공률 (전역 층)per-hop success (global layer) –
A 48-layer stack, GQA 8 KV heads × 128, BF16. The strip shows the layout (global, local); left: KV memory per sequence vs context for this layout (solid) and all-global (dashed); right: the chance of completing an h-hop pointer chase whose targets are spread uniformly over the context. The toy's assumptions: an attention layer can complete at most one hop, a local layer only if the target lies in its window, and a hop succeeds with the needle's softmax mass es/(es + (n−1)e1/2) over the n keys it sees. Raise the local:global ratio: memory falls almost in proportion, 1-hop recall is unchanged, and recall collapses once the hops outnumber the global layers. 48층 스택, GQA KV head 8 × 128, BF16. 띠는 배치(global, local), 왼쪽은 이 배치(실선)와 전부 전역(점선)의 시퀀스당 KV 메모리, 오른쪽은 표적이 문맥 전체에 고르게 퍼진 h-hop 포인터 추적을 끝낼 확률이다. 장난감의 가정: attention 층 하나는 최대 한 hop을 하고, local 층은 표적이 window 안에 있을 때만 할 수 있으며, hop은 보이는 key n개에 대한 needle의 softmax 질량 es/(es + (n−1)e1/2)의 확률로 성공한다. local:global 비율을 올리면 메모리는 거의 비례해 줄고 1-hop recall은 그대로이며, hop 수가 전역 층 수를 넘는 순간 recall이 무너진다.

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 ss or raise TT and every curve sinks: dilution makes each hop less certain, and a chain multiplies those uncertainties. Raising WW helps only when WW is a sizeable fraction of TT. 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

NumPy GQA = repeated MHA; MLA's two modes; RoPE vs absorption; sinks; dilution
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 (b=ln⁡128b=\ln 128 → half the mass), and part 5 confirms the dilution formula used in the figure.

PyTorch PyTorch: MLA with an absorbed decode path 로컬에서 실행run locally (pip install torch)
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))
 
확인 문제Check yourself

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 =2⋅128⋅(512+64+512)=278,528=2\cdot128\cdot(512+64+512)=278{,}528; bytes =576⋅2=1,152=576\cdot2=1{,}152; ratio ≈ 242. GQA’s intensity equals its group size gg (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: 2nkvdh2n_{kv}d_h (GQA), dc+drd_c+d_r (MLA). GQA = MHA with repeated K/V; MLA keeps per-head K/V at rank dcd_c.
  • Decode intensity of the attention core: g=nh/nkvg=n_h/n_{kv} for GQA (memory-bound), nh(2dc+dr)/(dc+dr)≈242n_h(2d_c+d_r)/(d_c+d_r)\approx242 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 강도 ss를 낮추거나 TT를 올리면 모든 곡선이 가라앉는다. 희석 때문에 hop 하나하나가 덜 확실해지고 사슬은 그 불확실성을 곱한다. WW를 키우는 것은 WW가 TT의 상당한 비율일 때만 도움이 된다. 실제 모델은 이렇게 칼같지 않다(residual stream 안에서 합성할 수도 있고 가까운 hop에는 local 층을 쓸 수 있다). 그래도 이 장난감은 설계자들이 전역 층 수에 하한을 두는 이유, 그리고 공격적인 비율의 대가가 다중 hop 긴 문맥 벤치마크에서 드러나는 이유를 설명한다.

직접 만들기

NumPy GQA = 반복한 MHA, MLA의 두 모드, RoPE와 흡수, sink, 희석
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 산수(b=ln⁡128b=\ln 128 → 질량 절반)를, 5번은 그림에 쓴 희석 식을 확인한다.

PyTorch PyTorch: 흡수된 decode 경로를 가진 MLA 로컬에서 실행run locally (pip install torch)
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))
 
확인 문제Check yourself

DeepSeek-V3는 흡수된 MLA로 decode한다. head 128개가 캐시된 토큰마다 공유 576개 항목(BF16으로 1,152바이트)을 읽는다. attention core는 바이트당 대략 몇 FLOPs를 하고, H100에서 그것은 무엇을 뜻하는가?

캐시된 토큰당 FLOPs =2⋅128⋅(512+64+512)=278,528=2\cdot128\cdot(512+64+512)=278{,}528, 바이트 =576⋅2=1,152=576\cdot2=1{,}152, 비는 약 242다. GQA의 강도는 그룹 크기 gg(1–16)라 memory-bound이고, MLA는 ridge 근처에 있다. 그래서 MLA decode를 빠르게 하는 것은 cache를 더 줄이는 것이 아니라 head를 절반으로 줄이거나(Kimi K2) 읽는 항목 수를 줄이는 것(DSA)이다.

정리

  • 토큰·층당 KV: GQA 2nkvdh2n_{kv}d_h, MLA dc+drd_c+d_r. GQA = K/V를 반복한 MHA, MLA는 rank dcd_c에서 head별 K/V를 유지한다.
  • attention core의 decode 강도: GQA는 g=nh/nkvg=n_h/n_{kv}(memory-bound), V3의 MLA는 nh(2dc+dr)/(dc+dr)≈242n_h(2d_c+d_r)/(d_c+d_r)\approx242(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