Study · Model anatomy
Attention-head anatomy: one cache, four wirings Attention head 해부: 하나의 cache, 네 가지 배선
MHA, MQA, GQA and MLA are one design decision seen from four points: how many query heads share each cached K/V. Turn the dial from 32 private K/V pairs down to a single shared latent, put real model configs through the bytes calculator, then open DeepSeek's Multi-head Latent Attention matrix by matrix. MHA·MQA·GQA·MLA는 별개의 네 설계가 아니라 하나의 결정 — cache된 K/V 하나를 몇 개의 query head가 공유하는가 — 를 네 지점에서 본 것이다. 32개의 전용 K/V pair에서 하나의 shared latent까지 다이얼을 돌려 보고, 실제 모델 config를 byte 계산기에 넣어 본 뒤, DeepSeek의 Multi-head Latent Attention을 matrix 단위로 열어 본다.
§1 Why the cache hurts — the problem before any mechanism cache가 왜 문제인가 — 메커니즘 이전의 문제
An autoregressive LLM generates one token at a time, and each new token must attend to every token that came before it. To avoid recomputing the past at every step, the model stores per-token state — the KV cache — and re-reads it on every single generated token. The weights are a fixed cost; the cache grows with context length, and again with every sequence served in parallel. autoregressive LLM은 token을 하나씩 생성하고, 새 token은 앞선 모든 token을 attend해야 한다. 매 step마다 과거를 다시 계산하지 않으려고 모델은 token별 상태 — KV cache — 를 저장해 두고, token 하나를 생성할 때마다 전부 다시 읽는다. weight는 고정 비용이지만 cache는 context 길이에 비례해 자라고, 동시에 서빙하는 sequence 수만큼 다시 배로 자란다.
Put numbers on it. Llama-2-7B in FP16 has about 13.5 GB of weights — fixed. Its KV cache costs 512 KB per token, so one 8K-context sequence adds 4 GB. Serve a batch of 16 and the cache alone is 64 GB — nearly five times the weights — and an 80 GB GPU is full before its compute units are ever the bottleneck. That is the itch: the cache, not the weights, caps how many sequences a GPU can serve at long context. 숫자로 보자. FP16의 Llama-2-7B는 weight가 약 13.5 GB — 고정이다. KV cache는 token당 512 KB이므로 8K context sequence 하나가 4 GB를 더한다. batch 16을 서빙하면 cache만 64 GB — weight의 거의 5배 — 이고, 80 GB GPU는 연산 유닛이 병목이 되기도 전에 메모리부터 가득 찬다. 이것이 가려운 지점이다: 긴 context에서 GPU가 서빙할 수 있는 sequence 수를 막는 것은 weight가 아니라 cache다.
Where do those 512 KB per token actually come from — what exactly does the cache store? token당 512 KB는 정확히 어디서 나오는가 — cache에는 무엇이 저장되나?
§2 What the cache stores — heads, K/V, and one formula cache에 담기는 것 — head, K/V, 그리고 공식 하나
Inside every layer, every token is projected into three vectors: a query, a key and a value. Multi-head attention runs this several times in parallel — Llama-2-7B uses 32 heads of dimension 128 — so each head can attend to a different aspect of the context. When token t is generated, its query must be scored against the keys of all previous tokens, and the resulting weights average their values. Those past keys and values never change, so recomputing them every step would be pure waste: the model computes them once and caches them. That is the KV cache — one K and one V vector per head, per layer, for every token seen so far. 모든 layer에서 모든 token은 세 vector로 projection된다: query, key, value. multi-head attention은 이것을 병렬로 여러 번 돌린다 — Llama-2-7B는 dimension 128짜리 head 32개 — 각 head가 context의 다른 측면을 보게 하기 위해서다. token t를 생성할 때 그 query는 앞선 모든 token의 key와 score를 내고, 그 가중치로 value들을 평균한다. 과거의 key·value는 변하지 않으므로 매 step 다시 계산하는 것은 순수한 낭비다: 한 번 계산해서 cache한다. 이것이 KV cache다 — 지금까지 본 모든 token에 대해 head당·layer당 K 하나와 V 하나.
That one formula prices everything on this page. Per token, the cache costs 2 · layers · kv_heads · head_dim · bytes — and each factor is an attack surface. Bytes-per-element is quantization's territory; sequence length is eviction's and hybrid attention's. This page is about the kv_heads factor: for Llama-2-7B the product is 2 · 32 · 32 · 128 · 2 B = 512 KB per token, and 32 of those factors are head count. 이 공식 하나가 이 페이지의 모든 것을 값 매긴다. token당 cache 비용은 2 · layers · kv_heads · head_dim · bytes — 그리고 인자 하나하나가 공략 지점이다. bytes-per-element는 quantization의 영역, sequence 길이는 eviction과 hybrid attention의 영역이다. 이 페이지는 kv_heads 인자를 다룬다: Llama-2-7B에서 곱은 2 · 32 · 32 · 128 · 2 B = 512 KB/token이고, 그중 32 하나가 head 수다.
32 query heads each carrying a private K/V pair — do they really all need their own? query head 32개가 각자 전용 K/V pair를 가진다 — 정말 전부 자기 것이 필요할까?
§3 Head wiring — one dial from MHA to MQA Head 배선 — MHA에서 MQA까지 하나의 다이얼
We now have the price formula, and kv_heads is its most exposed factor. The insight behind ten years of attention variants is that this factor is a free dial: MHA, GQA and MQA are not three designs but three positions of it. This section makes that dial literal. 이제 가격 공식이 있고, 그중 가장 공략하기 쉬운 인자가 kv_heads다. 지난 attention 변형들의 통찰은 이 인자가 자유롭게 돌릴 수 있는 다이얼이라는 것이다: MHA·GQA·MQA는 세 가지 설계가 아니라 다이얼의 세 위치다. 이 섹션은 그 다이얼을 문자 그대로 보여준다.
Hover a query head to see exactly which cached K/V it reads. Drag the KV-heads dial: 32 is MHA, 1 is MQA, everything between is GQA. MLA replaces the K/V row with a shared latent. query head 위에 hover하면 그 head가 읽는 cache된 K/V가 표시된다. KV-heads 다이얼을 움직여 보자: 32면 MHA, 1이면 MQA, 그 사이는 전부 GQA다. MLA는 K/V 행 자체를 shared latent로 바꾼다.
MHA — every query head owns a private K/V pair. Nothing is shared: 32 K and 32 V vectors are cached per token per layer, 8,192 elements (16 KB in FP16). This is the quality reference all sharing schemes are measured against. MHA — 모든 query head가 전용 K/V pair를 가진다. 아무것도 공유되지 않으므로 token·layer당 K 32개와 V 32개, 8,192개 원소(FP16 기준 16 KB)가 cache된다. 모든 sharing 방식의 품질 기준점이다.
The wiring view makes the family relationship literal: fix 32 query heads and slide the number of K/V heads. At 32 every query head has a private K/V pair (MHA); at 1 a single K/V head serves all of them (MQA); every stop between is GQA with group size 32/kv. Nothing else about attention changes — same scores, same softmax, same output projection. The only thing the dial moves is how many K and V vectors must be written to, stored in, and read back from the KV cache. 배선 뷰는 이 가족 관계를 문자 그대로 보여준다: query head 32개를 고정하고 K/V head 수만 움직여 보자. 32면 head마다 전용 K/V pair(MHA), 1이면 하나의 K/V head가 전부를 담당(MQA), 그 사이 모든 지점이 group 크기 32/kv의 GQA다. attention의 다른 부분은 아무것도 변하지 않는다 — score도, softmax도, output projection도 같다. 다이얼이 움직이는 것은 오직 KV cache에 쓰고, 저장하고, 다시 읽어야 하는 K·V vector의 개수뿐이다.
A 4× or 32× smaller cache sounds abstract — what does it buy in gigabytes on real model configs? cache가 4×, 32× 작아진다는 말은 추상적이다 — 실제 모델 config에서 몇 GB를 아끼는 걸까?
§4 KV-bytes calculator KV-byte 계산기
We have the dial and we have the formula. What is still missing is scale: whether sharing heads saves megabytes or tens of gigabytes depends on the other factors — layers, context, dtype. This calculator puts shipped configs through the formula so you can watch each term move. 다이얼도 공식도 손에 있다. 아직 없는 것은 규모 감각이다: head 공유가 몇 MB를 아끼는지 수십 GB를 아끼는지는 나머지 인자 — layers, context, dtype — 에 달려 있다. 이 계산기는 실제 출시된 config를 공식에 넣어 각 항이 움직이는 것을 보여준다.
Pick a real model or move the sliders; the bars compare what the four variants would cache for the same backbone shape. 실제 모델 preset을 고르거나 slider를 움직여 보자. 막대는 같은 backbone 형상에서 네 방식이 각각 cache하게 될 양을 비교한다.
Llama-3-8B: GQA with 32 Q / 8 KV heads — a 4× cache cut vs the same backbone with MHA, straight from the official config. Llama-3-8B: 32 Q / 8 KV head의 GQA — 공식 config 그대로, 같은 backbone을 MHA로 둘 때보다 cache가 4× 작다.
MLA row always uses DeepSeek's published dims (d_c 512 + d_R 64) regardless of the head sliders; the dtype is applied uniformly, so low-bit MLA rows are hypothetical what-ifs, shown for comparison only. 1 KB = 1,024 B. MLA 행은 head slider와 무관하게 DeepSeek이 공개한 차원 (d_c 512 + d_R 64)을 사용한다. dtype은 일괄 적용되므로 저비트 MLA 행은 비교용 가상 수치일 뿐이다. 1 KB = 1,024 B.
Every architecture choice on this page attacks exactly one factor of the formula: MQA/GQA shrink kv_heads (Llama-2-7B's 512 KB/token becomes Llama-3-8B's 128 KB/token), quantization shrinks bytes (the orthogonal axis — see the KIVI review), and MLA replaces the whole 2 · kv_heads · head_dim block with a fixed 576 elements per layer. That is why a 236B-parameter DeepSeek-V2 caches 67.5 KB/token while a 7B GQA model caches 128 KB. 이 페이지의 모든 아키텍처 선택은 공식의 인자를 정확히 하나씩 공략한다: MQA/GQA는 kv_heads를 줄이고(Llama-2-7B의 512 KB/token이 Llama-3-8B에서는 128 KB/token), quantization은 bytes를 줄이며(직교 축 — KIVI 리뷰 참고), MLA는 2 · kv_heads · head_dim 항 전체를 layer당 고정 576개 원소로 바꿔 버린다. 236B parameter의 DeepSeek-V2가 7B GQA 모델(128 KB)보다 작은 67.5 KB/token만 cache하는 이유가 이것이다.
How can 128 heads attend out of just 576 cached numbers per layer — without collapsing into one head? layer당 cache된 숫자 576개만으로 어떻게 head 128개가 — 하나의 head로 뭉개지지 않고 — attention을 할 수 있을까?
§5 MLA deep-dive — the low-rank trick, matrix by matrix MLA 딥다이브 — low-rank 트릭을 matrix 단위로
This is the hardest section of the page — take it slowly. Everything so far shrank the cache by storing fewer keys and values. MLA stores neither: it caches a compressed latent and rebuilds per-head K/V on the fly, which only pays off because of two tricks — weight absorption and decoupled RoPE — that the stepper below walks through one matrix at a time. 이 페이지에서 가장 어려운 섹션이다 — 천천히 가자. 지금까지는 key·value를 더 적게 저장해서 cache를 줄였다. MLA는 둘 다 저장하지 않는다: 압축된 latent를 cache해 두고 head별 K/V를 그때그때 복원하는데, 이것이 이득이 되는 이유는 두 가지 트릭 — weight absorption과 decoupled RoPE — 때문이다. 아래 stepper가 matrix 하나씩 짚어 간다.
DeepSeek-V2 shapes: hidden 5,120, 128 heads × 128, latent d_c = 512, decoupled RoPE key d_R = 64, 60 layers. Step through the pipeline. DeepSeek-V2 형상: hidden 5,120, 128 heads × 128, latent d_c = 512, decoupled RoPE key d_R = 64, 60 layers. 파이프라인을 단계별로 넘겨 보자.
Multi-head Latent Attention in one picture: instead of caching per-head K and V, DeepSeek-V2 caches one 512-dim latent c^KV plus one 64-dim RoPE key per token — everything else is rebuilt, or folded into other weight matrices, at compute time. Step through to see how. Multi-head Latent Attention 한눈에 보기: head별 K·V를 cache하는 대신 DeepSeek-V2는 token마다 512-dim latent c^KV와 64-dim RoPE key 하나만 cache한다 — 나머지는 계산 시점에 복원되거나 다른 weight matrix에 흡수된다. Step을 넘기며 확인해 보자.
MQA and GQA still cache keys and values — just fewer of them. MLA caches a different object: a 512-dim low-rank latent from which per-head K and V are linearly reconstructed. Because the reconstruction is linear, WUK folds into the query path and WUV into WO offline, so per-head K/V never materialize at decode time. The one obstacle is RoPE: a position-dependent rotation between WUK and the latent would make the folded product change every step. DeepSeek's fix is to carry position in a separate 64-dim key, shared across heads, and add the two dot products — the "decoupled RoPE" that costs 64 extra cached elements and saves the whole trick. MQA와 GQA는 여전히 key·value를 cache한다 — 개수만 줄일 뿐이다. MLA는 cache하는 대상 자체가 다르다: head별 K·V를 선형으로 복원할 수 있는 512-dim low-rank latent다. 복원이 선형이기 때문에 WUK는 query 경로에, WUV는 WO에 offline으로 흡수(absorption)되어 decode 시점에는 head별 K/V가 아예 실체화되지 않는다. 유일한 걸림돌이 RoPE다: position에 의존하는 회전이 WUK와 latent 사이에 끼면 흡수된 곱이 step마다 달라진다. DeepSeek의 해법은 position 정보를 모든 head가 공유하는 별도의 64-dim key에 실어 두 dot product를 더하는 것 — cache 원소 64개를 더 내고 트릭 전체를 살리는 "decoupled RoPE"다.
That is the mechanism. But does all this sharing cost quality — what do the papers actually measure? 메커니즘은 여기까지다. 그런데 이런 공유가 품질을 깎지는 않을까 — 논문들은 실제로 무엇을 측정했나?
§6 What the papers actually claim 논문이 실제로 주장하는 것
The mechanism is settled; the remaining question is evidence. Sharing K/V is only a good trade if quality survives it — here is what each paper claims, in its own words, with the arithmetic behind each headline number. 메커니즘은 정리됐다. 남은 질문은 근거다. K/V 공유는 품질이 살아남을 때에만 좋은 거래다 — 각 논문이 자기 표현으로 주장하는 내용과, 헤드라인 수치 뒤의 산수를 모았다.
Published quality-vs-memory evidence only — qualitative where numbers aren't independently verified. 공개된 quality-vs-memory 근거만 담았다 — 독립 검증되지 않은 수치는 정성적으로만 서술한다.
MHA 2017
The reference point. Every head keeps a private K/V pair, so cache traffic scales with the full head count: at Llama-2-7B shape that is 512 KB per token — 4 GB of cache at 8K context before batching. 기준점. 모든 head가 전용 K/V pair를 가지므로 cache가 전체 head 수에 비례한다. Llama-2-7B 형상에서는 token당 512 KB — batching 이전에 8K context만으로 4 GB다.
2 · 32 L · 32 kv · 128 · 2 B = 512 KB/tokenMQA Shazeer 2019
One K/V head serves every query head. The paper's claim: decoding is much faster because the K/V tensors shrink by the head count, with “only minor quality degradation” — the aggressive endpoint of the dial. 하나의 K/V head가 모든 query head를 담당한다. 논문의 주장: K/V tensor가 head 수만큼 줄어 decoding이 크게 빨라지고 품질 저하는 “only minor quality degradation” 수준 — 다이얼의 가장 공격적인 끝점이다.
arXiv 1911.02150 · 32× smaller cache vs MHA-32GQA Ainslie et al. 2023
Groups of query heads share K/V heads. Uptraining T5-XXL with 8 KV groups for just 5% of pre-training compute gave “quality close to multi-head attention with comparable speed to MQA” — the result that made 8-group GQA the open-model default (Llama-3, Mistral). query head들이 그룹 단위로 K/V head를 공유한다. T5-XXL을 8개 KV group으로 pre-training compute의 5%만 들여 uptraining하자 “quality close to multi-head attention with comparable speed to MQA” — 이 결과가 8-group GQA를 open 모델의 기본값(Llama-3, Mistral)으로 만들었다.
arXiv 2305.13245 · GQA-8, α = 0.05 uptrainingMLA DeepSeek-V2 2024
All heads share one low-rank latent. The paper reports a 93.3% KV-cache reduction versus DeepSeek 67B, a cache “equal to GQA with only 2.25 groups”, and — in its own ablations — quality above MHA. That last claim is paper-reported; treat it as the authors' measurement, not settled fact. 모든 head가 하나의 low-rank latent를 공유한다. 논문은 DeepSeek 67B 대비 93.3%의 KV cache 절감, “GQA 2.25 group과 동일한” cache, 그리고 자체 ablation에서 MHA보다 높은 품질을 보고한다. 마지막 주장은 저자 측정치이므로 확정된 사실이 아니라 논문 보고 수치로 받아들이자.
arXiv 2405.04434 · 576 elts/layer/tokenIf the head factor is this compressible, what is left — and which factor does the field attack next? head 인자가 이렇게까지 압축된다면 남은 것은 무엇이고, 이제 field는 어느 인자를 공략하고 있을까?
§7 Where this goes — the other two levers 어디로 가는가 — 남은 두 개의 레버
The head factor is one lever of three, and the field's frontier is less about pushing any single lever further than about composing them — and about porting MLA-style caches beyond the models they were born in. head 인자는 세 레버 중 하나일 뿐이고, field의 최전선은 어느 한 레버를 더 미는 것보다 레버들을 합성하는 쪽 — 그리고 MLA류 cache를 태생 모델 바깥으로 이식하는 쪽 — 에 있다.
Why the KV cache is the axis that matters 왜 KV cache가 핵심 축인가
Decoding is memory-bound: each generated token must read the weights plus the entire KV cache of every preceding token, and the cache — not compute — is what caps batch size on a fixed-memory GPU. Head sharing is one of three orthogonal levers on the same bytes: this page's axis shrinks the head factor (MHA → MQA/GQA → MLA), quantization shrinks the bytes-per-element factor, and hybrid/linear attention attacks the sequence-length factor. Because they multiply, they compose: a GQA model with a quantized cache, or an MLA model inside a hybrid stack, pays the product of the discounts. decoding은 memory-bound다: token 하나를 생성할 때마다 weight 전체에 더해 앞선 모든 token의 KV cache를 읽어야 하고, 고정 메모리 GPU에서 batch 크기를 막는 것은 연산이 아니라 cache다. head sharing은 같은 byte에 걸린 세 개의 직교 레버 중 하나다: 이 페이지의 축은 head 인자를 줄이고(MHA → MQA/GQA → MLA), quantization은 bytes-per-element 인자를, hybrid/linear attention은 sequence length 인자를 공략한다. 곱으로 작용하므로 서로 합성된다: cache를 quantize한 GQA 모델, hybrid stack 안의 MLA 모델은 할인율의 곱을 그대로 가져간다.
Each lever is an active research front. On the bytes axis, KV-cache quantization pushes stored precision down to 4 and even 2 bits — see the reviews of KIVI, KVQuant and TurboQuant. On the length axis, eviction and hybrid designs keep only the tokens or heads that matter — H2O, DuoAttention, and hybrid stacks like MiniMax-01 or linear-attention lines such as Gated DeltaNet. Questions the papers themselves leave hanging: how the levers behave when composed — a latent is a different object from a key, so per-axis results don't automatically stack — and whether pretrained MHA/GQA models can be converted to MLA-style caches cheaply instead of training from scratch. 레버 하나하나가 살아 있는 연구 전선이다. bytes 축에서는 KV-cache quantization이 저장 정밀도를 4-bit, 심지어 2-bit까지 내린다 — KIVI, KVQuant, TurboQuant 리뷰 참고. length 축에서는 eviction과 hybrid 설계가 중요한 token·head만 남긴다 — H2O, DuoAttention, 그리고 MiniMax-01 같은 hybrid stack이나 Gated DeltaNet 같은 linear-attention 계열. 논문들이 스스로 남겨 둔 질문들: 레버들을 합성하면 어떻게 되는가 — latent는 key와 다른 대상이므로 축별 결과가 자동으로 곱해지지 않는다 — 그리고 pretrained MHA/GQA 모델을 처음부터 다시 학습하지 않고 MLA류 cache로 싸게 변환할 수 있는가.
Going deeper 더 깊이 가기
- Fast Transformer Decoding: One Write-Head is All You Need — MQA (Shazeer, 2019)
- GQA: Training Generalized Multi-Query Models from Multi-Head Checkpoints (Ainslie et al., 2023)
- DeepSeek-V2 — Multi-head Latent Attention (2024)
- Hybrid attention — removing the sequence-length axis
- KIVI review — quantization, the orthogonal bytes-per-element axis
- KV-cache quantization, byte by byte
Configs verified against official sources (July 2026): Llama-2-7B (32 layers, 32Q/32KV, hidden 4,096), Llama-3-8B and Mistral-7B-v0.1 (32 layers, 32Q/8KV), DeepSeek-V2 (60 layers, 128 heads, kv_lora_rank 512, qk_rope_head_dim 64), DeepSeek-V3 (61 layers, otherwise same MLA dims). Mistral v0.1's sliding-window attention is not modeled by the calculator. Quality claims are quoted from the respective papers. config는 공식 소스로 검증했다(2026년 7월): Llama-2-7B (32 layers, 32Q/32KV, hidden 4,096), Llama-3-8B·Mistral-7B-v0.1 (32 layers, 32Q/8KV), DeepSeek-V2 (60 layers, 128 heads, kv_lora_rank 512, qk_rope_head_dim 64), DeepSeek-V3 (61 layers, 나머지 MLA 차원 동일). Mistral v0.1의 sliding-window attention은 계산기에 반영하지 않았다. 품질 주장은 각 논문에서 인용했다.