3 Model Architecture 6 / 9
  1. In this chapter
  2. From RNNs to Attention
  3. Attention Basics
  4. Positional Encoding Explained
  5. Transformer Block Explained
  6. Modern LLM Architecture
  7. Efficient Attention
  8. Mixture of Experts (MoE)
  9. Long Context
  10. State Space Models and Hybrids
All chapters →

Chapter 3 · Model Architecture 3.6

Efficient Attention: MQA, GQA, MLA and FlashAttention

Attention has two bottlenecks: the KV cache that decoding rereads at every step, and the N×N score matrix of training and prefill. MQA, GQA and MLA shrink the KV cache; FlashAttention cuts memory traffic with tiling and online softmax, and its output is identical to standard attention.

Intermediate 27 min read Updated Companion code ↓

After this page you will be able to

  • Tell the two bottlenecks of attention apart: the KV cache read again and again during decoding, and the N×N score matrix in training and prefill.
  • Work out how many K/V entries MHA, MQA, GQA and MLA cache per token, and where each one saves.
  • Explain how FlashAttention cuts memory traffic with tiling and online softmax while returning exactly the same result as standard attention.
  • Verify online softmax and MLA's matrix absorption in code.
  • Choose an attention variant for a given scenario and avoid the common traps.
On this page
  1. Two bottlenecks, two kinds of fix
  2. What determines the KV cache size
  3. MQA and GQA: share K/V across query heads
  4. What shrinking the K/V heads costs
  5. MLA: don’t keep fewer heads, compress K and V together
  6. Try it: the KV cache of attention variants
  7. FlashAttention: same result, less memory traffic
  8. Other ideas: look at only part of the sequence
  9. Hands-on code: check the online softmax and the matrix absorption
  10. What to choose, and common pitfalls
  11. Summary and exercises
  12. Quick check
  13. Further reading
  14. FAQ

Attention costs come from two different places. During training and prefill, the model computes an N×NN\times N score matrix over the whole sequence, and the bottleneck is reading and writing it in GPU memory. During token-by-token decoding, every step rereads the keys and values of the entire history, and the bottleneck is the size of the KV cache. MQA, GQA and MLA attack the second problem by shrinking what each token must cache; FlashAttention attacks the first by computing attention in blocks with an online softmax, and its result is identical to standard attention.

Two bottlenecks, two kinds of fix

PhaseBottleneckDepends onRemedy
Training, long-sequence prefillAn N×NN\times N score matrix that is written to and read from GPU memory repeatedlyThe square of the sequence length NNFlashAttention
Token-by-token decodingEvery step reads all historical K and VKV cache size: layers, K/V heads, head dimension, sequence lengthMQA, GQA, MLA, cache quantization, PagedAttention

How large is the score matrix of one head? In FP16 (2 bytes) it is 32 MiB at N=4096N=4096, 2 GiB at N=32768N=32768 and 32 GiB at N=131072N=131072. A standard implementation writes the scores SS to GPU memory, reads them back for the softmax, writes the result PP, and reads it back to multiply by VV, so both N×NN\times N matrices are written and read once. QQ, KK, VV and the output, by contrast, hold only N×dN\times d numbers each, and dd is typically 64 to 128, far smaller than NN.

Because the problems differ, the fixes stack: FlashAttention does not change the size of the KV cache, and GQA and MLA do not change how one attention computation moves data.

What determines the KV cache size

During decoding the keys and values of past tokens never change, so they are cached. Each head has dhd_h numbers for K and dhd_h for V, so one layer and one token need 2 H dh2\,H\,d_h numbers (HH is the number of query heads). There are three structural ways to shrink it: fewer K/V heads, compress each K/V, or cache fewer tokens. MQA and GQA take the first, MLA the second and sliding windows the third; on top of that you can lower the precision of each number, which is cache quantization.

DesignNumbers cached per layer and tokenMeaning
MHA2 H dh2\,H\,d_hEvery query head has its own K and V
GQA2 g dh2\,g\,d_hHH query heads split into gg groups, one K/V per group
MQA2 dh2\,d_hOne K/V shared by all query heads, GQA with g=1g=1
MLAdc+dRd_c+d_RA latent vector (dcd_c numbers) plus a RoPE key (dRd_R numbers)
KV cache of MHA, GQA, MQA and MLA With eight query heads as an example: MHA caches one K and one V per head, 8 units; GQA splits the heads into 2 groups and caches 2 units; MQA shares one K and V across all heads, 1 unit; MLA caches only a compressed latent vector plus a small RoPE key, about 2.25 units. MHA multi-head One K/V per query head 8 query heads KV KV KV KV KV KV KV KV Cache: 8 units Per token/layer: 2·H·d_h H = 8, the baseline GQA grouped-query One K/V per group of heads 8 query heads KV KV Cache: 2 units Per token/layer: 2·g·d_h g = 2, 1/4 of MHA MQA multi-query One K/V shared by all heads 8 query heads KV Cache: 1 unit Per token/layer: 2·d_h 1/8 of MHA MLA latent KV Cache a compressed latent 8 query heads c Cache: 2.25 units Per token/layer: d_c + d_R green c, violet RoPE key
Eight query heads as an example. One unit is one head's K and V (2·d_h numbers). MLA uses d_c = 4·d_h and d_R = d_h/2, DeepSeek-V2's setting, which is 2.25 units. The number of boxes shows relative cache size, not an exact scale.

For the same shape the designs differ enormously. The table uses BF16 (2 bytes per number); layers, heads and head dimension come from each model’s paper or public configuration, and every row follows from the formulas above:

ModelAttention designPer tokenCache at 128K tokens
Llama 2 7BMHA (32 K/V heads)512 KiB64 GiB (extrapolated with the same shape)
Llama 3 8BGQA (8 K/V heads)128 KiB16 GiB
Llama 3 70BGQA (8 K/V heads)320 KiB40 GiB
Llama 3 405BGQA (8 K/V heads)504 KiB63 GiB
DeepSeek-V2MLA (dc=512d_c=512, dR=64d_R=64)67.5 KiB8.44 GiB
DeepSeek-V3MLA (dc=512d_c=512, dR=64d_R=64)68.6 KiB8.58 GiB

All three Llama 3 sizes use 8 K/V heads (Table 3 of the Llama 3 paper), so the per-token cache varies with depth and head dimension, not with the number of query heads. DeepSeek-V3 has 128 query heads; with MHA each token would need about 3.81 MiB, while MLA needs 68.6 KiB, 1/56.9 of that.

MQA and GQA: share K/V across query heads

Multi-query attention (MQA), proposed by Shazeer in 2019, makes all query heads share a single K and V. The motivation is that incremental decoding is limited by memory bandwidth: smaller K/V tensors mean less data to read per step, and the paper reports much faster decoding with only minor quality degradation.

Grouped-query attention (GQA), proposed by Ainslie et al. in 2023, sits between MHA and MQA: the HH query heads are split into gg groups and each group shares one K/V pair. g=1g=1 is MQA and g=Hg=H is MHA. The GQA paper also gives a recipe for converting an existing MHA checkpoint: mean-pool the K and V heads within each group, then continue pretraining with the original recipe for 5% of the original steps.

Most open models today chose GQA: Llama 2’s 34B and 70B use it, all three Llama 3 sizes have 8 K/V heads, and so does Mistral 7B. The Llama 2 paper also names an engineering reason to prefer GQA over MQA: with tensor parallelism over 8 GPUs, MQA has fewer K/V heads than GPUs and can no longer be sharded by head, so the single K/V head must be duplicated on every GPU, which makes the cache as large as GQA’s anyway.

What shrinking the K/V heads costs

Three papers ran controlled comparisons, and their conclusions do not fully agree:

SourceSetupResult
GQA paper (Table 1)T5-XXL (encoder-decoder), MHA checkpoint uptrained for 5%Average score MHA 47.2, GQA-8 47.1, MQA 46.6; inference time per sample per TPUv4 chip 1.51 s, 0.28 s, 0.24 s
Llama 2 paper (Appendix A.2.1, Table 18)30B scale, 150B tokens each, FFN widened to match parameter countsGQA comparable to MHA on most tasks and better than MQA on average
DeepSeek-V2 paper (Table 8)7B dense models, 1.33T tokens each, layers adjusted to align parameter countsMMLU (5-shot) MHA 45.2, GQA-8 41.2, MQA 37.9; BBH (3-shot) 37.0, 35.6, 33.2

The benchmarks, model scales, training budgets and ways of matching parameter counts all differ, so the numbers are not directly comparable. The safe reading is that fewer K/V heads buy a proportional cache reduction, and the quality cost has no universal value: the DeepSeek team saw a clear gap on harder benchmarks. Whether to use GQA, and with how many groups, should be tested at your own scale and on your own evaluations.

MLA: don’t keep fewer heads, compress K and V together

Multi-head latent attention (MLA) comes from DeepSeek-V2. Instead of reducing the number of heads, it jointly compresses K and V into one low-dimensional latent vector and caches only that:

ctKV=WDKVht,ktC=WUKctKV,vtC=WUVctKV\mathbf c_t^{KV}=W^{DKV}\mathbf h_t,\qquad \mathbf k_t^{C}=W^{UK}\mathbf c_t^{KV},\qquad \mathbf v_t^{C}=W^{UV}\mathbf c_t^{KV}

Here ht∈Rd\mathbf h_t\in\mathbb R^{d} is the layer input of token tt, ctKV∈Rdc\mathbf c_t^{KV}\in\mathbb R^{d_c} is the latent vector, WDKVW^{DKV} is the down-projection, WUKW^{UK} and WUVW^{UV} are the up-projections that restore the keys and values of all heads, and dcd_c is much smaller than dhHd_h H. At inference only ctKV\mathbf c_t^{KV} is cached.

Better still, restoring the full K and V is not necessary. Let WiUKW^{UK}_i and WiUVW^{UV}_i (of shape dh×dcd_h\times d_c) be the slices of the up-projections for head ii, and pt,j,ip_{t,j,i} the attention weight of head ii from position tt to position jj. Then the score and the output can be written as

qt,i⊤kj,iC=((WiUK)⊤qt,i)⊤cjKV,ot,i=WiUV∑jpt,j,i cjKV\mathbf q_{t,i}^{\top}\mathbf k_{j,i}^{C}=\big((W^{UK}_i)^{\top}\mathbf q_{t,i}\big)^{\top}\mathbf c_j^{KV},\qquad \mathbf o_{t,i}=W^{UV}_i\sum_{j}p_{t,j,i}\,\mathbf c_j^{KV}

The first identity moves WUKW^{UK} to the query side, so scores are computed directly in the latent space. The second sums the latent vectors first and multiplies by WUVW^{UV} afterwards, and WUVW^{UV} can be merged with the output projection WOW^{O} ahead of time. The paper calls this absorbing the matrices; it means inference never has to reconstruct K and V for the prefix. The code below checks both identities numerically.

Why a separate RoPE key. RoPE acts on queries and keys and depends on position. Applying it directly to ktC\mathbf k_t^{C} would place a position-dependent rotation between WQW^{Q} and WUKW^{UK}; matrix multiplication does not commute, so the absorption above no longer works and the keys of the whole prefix would have to be recomputed. DeepSeek-V2’s fix is decoupled RoPE: a small dRd_R-dimensional query per head and one key shared by all heads, ktR=RoPE(WKRht)\mathbf k_t^{R}=\mathrm{RoPE}(W^{KR}\mathbf h_t), carry the position. The key of head ii is [kt,iC;ktR][\mathbf k_{t,i}^{C};\mathbf k_t^{R}] and the scores are scaled by 1/dh+dR1/\sqrt{d_h+d_R}. That key is cached too, so MLA stores dc+dRd_c+d_R numbers per layer and token.

DeepSeek-V2 sets dc=4 dhd_c=4\,d_h and dR=dh/2d_R=d_h/2, so its cache equals that of GQA with 2.25 groups ((4dh+dh/2)/(2dh)=2.25(4d_h+d_h/2)/(2d_h)=2.25). Both DeepSeek-V2 and V3 use dh=128d_h=128, dc=512d_c=512 and dR=64d_R=64, which is 576 numbers per layer and token, 1/56.9 of an MHA with 128 query heads (32768 numbers). The DeepSeek-V2 abstract reports a 93.3% smaller KV cache than DeepSeek 67B.

The appendix also compares MLA with MHA in the same MoE architecture (Table 9, only the attention differs):

ScaleCache per token (MHA → MLA)MMLU (5-shot)BBH (3-shot)
Small MoE (about 16B parameters, 1.33T tokens)110.6K → 15.6K numbers (14%)48.7 → 50.037.9 → 39.0
Large MoE (about 250B parameters, 420B tokens)860.2K → 34.6K numbers (4%)57.5 → 59.046.6 → 50.7

These are the DeepSeek team’s own ablations at modest training budgets, and the conclusion is that MLA is better than MHA with a much smaller cache. Keep the source in mind, and remember that, like the GQA comparison above (Table 8), it describes their setup.

Try it: the KV cache of attention variants

Pick a model shape, change the GQA group count, the MLA latent size, the context length, the cache precision and the KV budget, and watch how the cache of each design changes and how many sequences a given memory budget can hold at once.

  1. With the defaults (Llama 3 8B shape, 32K context, BF16, 40 GiB budget), MHA needs 16 GiB per sequence and fits 2; GQA (g=8g=8) needs 4 GiB and fits 10; MQA needs 512 MiB and fits 80; MLA needs 1.13 GiB and fits 35.
  2. Switch to Llama 3 70B at 128K: MHA needs 320 GiB, GQA (g=8g=8) 40 GiB, MQA 5 GiB and MLA 11.25 GiB. A 40 GiB budget holds exactly one GQA sequence and not even one MHA sequence.
  3. Switch to DeepSeek-V3 at 128K: the hypothetical MHA is 488 GiB, MLA is 8.58 GiB, about 1.8% of MHA (1/56.9), and the “Equivalent GQA groups” column reads 2.25.
  4. Drag dcd_c to 256 and dRd_R to 0: the MLA row’s equivalent group count becomes 1.00 and its cache equals MQA’s. The MLA cache depends only on dc+dRd_c+d_R, not on HH.
  5. Set the cache precision to FP8 / INT8 and every number halves: the GQA cache of Llama 3 70B at 128K drops from 40 GiB to 20 GiB. Cache quantization stacks with the attention design.

FlashAttention: same result, less memory traffic

A GPU has two levels of memory: large but slow GPU memory (HBM), and a small but much faster on-chip SRAM. Standard attention writes the two N×NN\times N intermediates S=QK⊤S=QK^{\top} and P=softmax(S)P=\mathrm{softmax}(S) to HBM and reads them back, and element-wise operations such as softmax have low arithmetic intensity, so the time is dominated by data movement (arithmetic intensity and the roofline are explained in GPUs and the Roofline Model). FlashAttention (Dao et al., 2022) makes the algorithm IO-aware: it splits QQ, KK and VV into blocks, loads one small block at a time into SRAM, performs the matrix multiplications and the softmax there, and writes only the final output back to HBM, all fused into a single GPU kernel.

The difficulty is that a softmax needs the maximum and the sum of a whole row. FlashAttention uses an online softmax: as the blocks of a row arrive it keeps only three quantities, the running maximum mm, the normalizer ℓ\ell and the unnormalized output a\mathbf a, and updates them with each new block:

m′=max⁡ ⁣(m,max⁡i∈blocksi),ℓ′=em−m′ ℓ+∑i∈blockesi−m′,a′=em−m′ a+∑i∈blockesi−m′ vim'=\max\!\big(m,\max_{i\in\text{block}}s_i\big),\quad \ell'=e^{m-m'}\,\ell+\sum_{i\in\text{block}}e^{s_i-m'},\quad \mathbf a'=e^{m-m'}\,\mathbf a+\sum_{i\in\text{block}}e^{s_i-m'}\,\mathbf v_i

After the last block the output is a/ℓ\mathbf a/\ell. The old accumulators only need to be multiplied by the scalar em−m′e^{m-m'} to move them to the new maximum, so a whole row of scores is never stored. In the backward pass FlashAttention does not save SS and PP; it saves the output and the per-row statistics (m,ℓ)(m,\ell) and recomputes the blocks of SS and PP from QQ, KK and VV when needed, a form of selective gradient checkpointing.

The paper analyzes the IO complexity (Theorem 2). With sequence length NN, head dimension dd and SRAM size MM (d≤M≤Ndd\le M\le Nd), standard attention needs Θ(Nd+N2)\Theta(Nd+N^2) HBM accesses and FlashAttention needs Θ(N2d2M−1)\Theta(N^2d^2M^{-1}); it also proves that no exact attention algorithm can asymptotically do better for all SRAM sizes. A measured example (Figure 2 of the paper: GPT-2 medium, sequence length 1024, head dimension 64, 16 heads, batch size 64, A100, forward plus backward):

MetricStandard attentionFlashAttentionChange
Compute66.6 GFLOPs75.2 GFLOPs13% more
HBM traffic40.3 GB4.4 GBdown to about 1/9.2
Runtime41.7 ms7.3 ms5.7× faster

The FLOPs went up because the backward pass recomputes the scores, but attention on a GPU is limited by memory traffic, so when the traffic falls the time falls with it. The end-to-end numbers in the abstract are 15% faster than the MLPerf 1.1 record on BERT-large (sequence length 512) and 3× faster on GPT-2 (sequence length 1K). Memory use also drops from quadratic to linear in the sequence length.

The next two generations apply the same idea to the hardware more completely:

VersionImprovementReported result
FlashAttention-2 (2023)Fewer non-matmul FLOPs, parallelism over the sequence length, better work split between thread blocks and warpsAbout 2× faster than FlashAttention, 50% to 73% of the theoretical peak FLOPs/s on an A100; up to 225 TFLOPs/s (72% model FLOPs utilization) when training GPT-style models end to end
FlashAttention-3 (2024)For the H100: overlaps computation and data movement through the asynchrony of Tensor Cores and TMA, adds FP8On an H100 SXM5, FP16 forward is 1.5 to 2.0× faster than FlashAttention-2 (backward 1.5 to 1.75×), reaching up to 740 TFLOPs/s (75% utilization); FP8 reaches close to 1.2 PFLOPs/s; the paper says FlashAttention-2 reaches only 35% utilization on an H100

In PyTorch you do not need to call these kernels yourself: torch.nn.functional.scaled_dot_product_attention can use FlashAttention-2 and other optimized kernels on CUDA (see the function’s documentation).

Other ideas: look at only part of the sequence

Several other approaches change different things:

MethodWhat it changesExact?Example
FlashAttentionBlock order of the computation and GPU memory trafficExactBuilt into mainstream training and inference frameworks
Sliding-window attentionEach position sees only the previous WW tokensChanges the modelMistral 7B, W=4096W=4096
GQA, MQANumber of K/V headsChanges the model, needs trainingLlama 2 70B, Llama 3
MLAThe representation of K/V, a low-rank latentChanges the model, needs trainingDeepSeek-V2, V3
Linear attention, SSMsDrops the softmax and compresses the history into a fixed-size stateLossy, changes the model, needs trainingMamba, Qwen3-Next, see State Space Models and Hybrid Architectures
KV cache quantizationNumeric precision of the cacheLossySee the quantization page
PagedAttentionHow cache memory is managedExactvLLM, see the KV cache page

In sliding-window attention every position in every layer attends only to the previous WW tokens, yet stacking layers still lets information travel further: after kk layers it can move up to k×Wk\times W tokens. Mistral 7B has 32 layers and W=4096W=4096, so the theoretical attention span at the last layer is about 131K tokens (32×4096=13107232\times4096=131072). Because each position only needs the K/V of the last WW tokens, the cache can be a rolling buffer of fixed size WW; the paper says this cuts cache memory by 8× on a 32K-token sequence (32768/4096=832768/4096=8). A span that information can theoretically reach is not the same as a length the model uses well, a point that comes back with long contexts.

Hands-on code: check the online softmax and the matrix absorption

The first snippet implements blocked, online-softmax attention in NumPy and compares it with the full N×NN\times N version. It is a teaching version; the real FlashAttention fuses the whole loop into one GPU kernel and runs it in SRAM:

import numpy as np

def naive_attention(Q, K, V):
    S = Q @ K.T / np.sqrt(Q.shape[1])              # the full N×N score matrix, all stored
    P = np.exp(S - S.max(axis=1, keepdims=True))
    P /= P.sum(axis=1, keepdims=True)
    return P @ V

def tiled_attention(Q, K, V, block=128):
    N, d = Q.shape
    O = np.empty_like(Q)
    for i in range(0, N, block):                    # outer loop: one block of Q at a time
        q = Q[i:i + block]
        m = np.full(len(q), -np.inf)                # running max score per row
        l = np.zeros(len(q))                        # running softmax denominator (relative to m)
        acc = np.zeros((len(q), d))                 # running unnormalized output per row
        for j in range(0, N, block):                # inner loop: sweep over the blocks of K and V
            s = q @ K[j:j + block].T / np.sqrt(d)   # only a small block×block score tile
            m_new = np.maximum(m, s.max(axis=1))
            scale = np.exp(m - m_new)               # rescale old accumulators to the new max
            p = np.exp(s - m_new[:, None])
            l = l * scale + p.sum(axis=1)
            acc = acc * scale[:, None] + p @ V[j:j + block]
            m = m_new
        O[i:i + block] = acc / l[:, None]
    return O

rng = np.random.default_rng(0)
N, d = 1000, 64
Q, K, V = (rng.normal(size=(N, d)) * 3 for _ in range(3))   # scaled up to make the softmax sharper
out_naive = naive_attention(Q, K, V)
out_tiled = tiled_attention(Q, K, V, block=128)
print(f"max abs error: {np.abs(out_naive - out_tiled).max():.1e}")
print(f"full score matrix {N * N * 8 / 2**20:.1f} MiB, the tiled version holds {128 * 128 * 8 / 2**10:.0f} KiB at a time")

Output:

max abs error: 3.0e-14
full score matrix 7.6 MiB, the tiled version holds 128 KiB at a time

The widget below shrinks that comparison to one query and 8 keys, and you can walk it block by block: only three quantities are ever kept (the running maximum m, the denominator l and the unnormalised output a), each new block first multiplies the two old accumulators by the conversion factor e^(m−m’) and then adds its own contribution. After the last block a / l matches the whole-row result digit for digit; tick the common-bug box to see how far the output drifts when the factor is skipped. The two numbers the page prints (7.6 MiB and 128 KiB) can be recomputed for other sequence lengths.

The two implementations agree to floating-point error: tiling changes where the intermediate data lives, not the result.

The second snippet checks MLA’s matrix absorption. With random matrices it computes the output once by “restore K and V, then run attention” and once by “absorb and work in the latent space”, and compares the two (the RoPE part is left out, so it only tests the two identities above):

import numpy as np

rng = np.random.default_rng(0)
d, n_h, d_h, d_c, T = 256, 8, 32, 48, 10        # toy sizes: hidden dim, heads, head dim, KV latent dim, length
H = rng.normal(size=(T, d))                      # hidden state of every token
W_DKV = rng.normal(size=(d_c, d)) / np.sqrt(d)               # down-projection d -> d_c
W_UK = rng.normal(size=(n_h, d_h, d_c)) / np.sqrt(d_c)       # per-head K up-projection
W_UV = rng.normal(size=(n_h, d_h, d_c)) / np.sqrt(d_c)       # per-head V up-projection
W_Q = rng.normal(size=(n_h, d_h, d)) / np.sqrt(d)
W_O = rng.normal(size=(d, n_h * d_h)) / np.sqrt(n_h * d_h)

C = H @ W_DKV.T                                  # the cached latents: T × d_c, the only thing stored
t = T - 1                                        # the position being generated; causal attention sees 0..t

def softmax(s):
    e = np.exp(s - s.max())
    return e / e.sum()

# Way 1: restore K and V first, then run standard multi-head attention
heads = []
for h in range(n_h):
    q = W_Q[h] @ H[t]
    K, V = C @ W_UK[h].T, C @ W_UV[h].T          # T × d_h
    heads.append(softmax(K @ q / np.sqrt(d_h)) @ V)
u_explicit = W_O @ np.concatenate(heads)

# Way 2: absorb. W_UK goes into the query, W_UV into the output projection; K and V are never restored
u_absorbed = np.zeros(d)
for h in range(n_h):
    q_abs = W_UK[h].T @ (W_Q[h] @ H[t])          # d_c-dimensional: the query lives in the latent space
    p = softmax(C @ q_abs / np.sqrt(d_h))        # score = c_j · q_abs
    u_absorbed += (W_O[:, h * d_h:(h + 1) * d_h] @ W_UV[h]) @ (p @ C)

print(f"max abs error between the two ways: {np.abs(u_explicit - u_absorbed).max():.1e}")
print(f"numbers cached per token and layer: MHA {2 * n_h * d_h}, MLA {d_c} (without the RoPE part)")

Output:

max abs error between the two ways: 6.1e-16
numbers cached per token and layer: MHA 512, MLA 48 (without the RoPE part)

The results match before and after absorption, so at inference MLA can store only ctKV\mathbf c_t^{KV} and never has to restore the K and V of each prefix token.

What to choose, and common pitfalls

GoalCommon choiceNotes
Training, long-sequence prefillFlashAttention or a framework’s fused kernelExact, no quality cost
Training from scratch with deployment in mindGQA, typically 8 K/V headsThe choice of Llama 2 70B, Llama 3 and Mistral 7B
An existing MHA checkpoint whose cache you want to shrinkMean-pool the K/V heads into GQA, then continue training brieflyThe GQA paper’s recipe, 5% of the original pretraining steps on T5-XXL
The cache is still the bottleneck (very long contexts, high concurrency)MLA, cache quantization, sliding windowsMLA needs matching inference kernels (absorbed matrices, decoupled RoPE) and framework support varies, so check before committing

Common mistakes:

  1. Counting only the K/V heads, forgetting depth and head dimension. The cache is proportional to 2 g dh L2\,g\,d_h\,L: with 8 K/V heads each, Llama 3 405B needs 504 KiB per token and the 8B model only 128 KiB.
  2. Expecting FlashAttention to save KV cache. It saves intermediates like the score matrix and memory traffic; the cache size does not change at all.
  3. Assuming GQA is always nearly free. The three experiments above give different answers; the result depends on scale, training budget and evaluation.
  4. Fewer K/V heads than GPUs under tensor parallelism. The K/V must then be duplicated across GPUs, which eats into the savings.
  5. Leaving the RoPE key out of the MLA cache. Counting only dcd_c underestimates it: dR/dc=64/512=12.5%d_R/d_c=64/512=12.5\%.
  6. Reading “equivalent GQA groups” as equal quality. It only says the caches have the same size, not that the models are equally capable.

Summary and exercises

Key points:

  1. Attention has two bottlenecks: training and prefill are limited by the memory traffic of the N×NN\times N score matrix, decoding by the size of the KV cache.
  2. Per layer and token, MHA caches 2Hdh2Hd_h numbers, GQA 2gdh2gd_h, MQA 2dh2d_h and MLA dc+dRd_c+d_R; the DeepSeek-V2 and V3 setting equals GQA with 2.25 groups.
  3. The quality cost of fewer K/V heads depends on the setup: nearly lossless on T5-XXL, a clear gap in DeepSeek’s 7B ablation; in DeepSeek’s own ablation MLA shrank the cache and raised the scores at the same time.
  4. FlashAttention is exact: tiling and online softmax cut HBM traffic to Θ(N2d2M−1)\Theta(N^2d^2M^{-1}), and it does not reduce the KV cache.

Quick check

1. A model has L layers, H query heads and head dimension d_h and uses MHA. How many numbers does the KV cache hold per token?

  • H·d_h
  • 2·H·d_h·L
  • 2·H·d_h
  • H·L

K and V each have H·d_h numbers, so one layer needs 2·H·d_h, multiplied by the number of layers L. For GQA, replace H with the number of groups g.

2. What is the main reason FlashAttention is faster than standard attention?

  • It reduces the data moved between HBM and the on-chip SRAM
  • It uses a low-rank approximation to cut the computation
  • It only computes the most important tokens
  • It shrinks the KV cache

In the paper’s example it even does 13% more computation, yet HBM traffic falls to about 1/9.2 and the time is 5.7× shorter. It is an exact algorithm and does not change the KV cache size.

3. Which statements are correct? (multiple choice)

  • GQA with one group is MQA, and with H groups it is MHA
  • Besides the latent vector, the MLA cache also holds a small key that carries RoPE
  • MLA caches the full K and V at lower precision
  • An MHA checkpoint can be turned into GQA by mean-pooling its K/V heads and training a little longer

MLA caches a d_c-dimensional latent vector and a d_R-dimensional RoPE key, not low-precision K and V. The other three come from the definition of GQA and the GQA paper’s conversion recipe.

4. DeepSeek-V3 has d_h = 128, d_c = 512 and d_R = 64. How many numbers does MLA cache per layer and token, and how many GQA groups is that equivalent to?

  • 512 numbers, 2 groups
  • 576 numbers, 2.25 groups
  • 1024 numbers, 4 groups
  • 64 numbers, 0.25 groups

The cache holds d_c + d_R = 576 numbers; one GQA group caches 2·d_h = 256 numbers, and 576 ÷ 256 = 2.25.

Exercises:

  1. A model has 32 layers, 32 query heads and head dimension 128, and caches in BF16. How many KiB per token does MHA need, and how many does GQA with g=4g=4 need? How many GiB does one 16K-token sequence take in each case?
  2. In the widget choose Llama 3 70B, 128K context, BF16 and a 40 GiB budget. How many GiB does each of the four designs take, and how many sequences does each fit?
  3. Why is FlashAttention faster even though it does more FLOPs than the standard implementation?
  4. What goes wrong if MLA applies RoPE directly to the reconstructed key WUKcjW^{UK}\mathbf c_j?
Reference answers
  1. MHA: 2×32×128×32×22\times32\times128\times32\times2 bytes =524288=524288 bytes =512=512 KiB, and a 16K sequence takes 512 KiB×16384=8512\ \text{KiB}\times16384=8 GiB. GQA with g=4g=4: 2×4×128×32×2=655362\times4\times128\times32\times2=65536 bytes =64=64 KiB, so a 16K sequence takes 1 GiB, 1/8 of MHA (g/H=4/32g/H=4/32).
  2. MHA 320 GiB (does not fit, 0 sequences), GQA (g=8g=8) 40 GiB (1 sequence), MQA 5 GiB (8 sequences), MLA 11.25 GiB (3 sequences).
  3. The backward pass does not store SS and PP and recomputes them from blocks, so the FLOPs increase; but attention on a GPU is limited by memory traffic, HBM traffic falls to about 1/9.2, and the total time drops to about 1/5.7.
  4. The rotation depends on position and would sit between the query projection and WUKW^{UK}. Matrix multiplication does not commute, so WUKW^{UK} can no longer be absorbed into the query side and inference would have to recompute the keys of every prefix token. That is why MLA puts position into a small separate decoupled RoPE key and caches it next to the latent vector.

Further reading

FAQ

What is the difference between MQA, GQA and MLA?
In standard multi-head attention (MHA) every query head has its own K and V. MQA lets all query heads share one K/V pair, GQA lets each group of query heads share one, and MLA does not cache K/V at all but a low-dimensional latent vector plus a small RoPE key. The numbers cached per layer and token are 2·H·d_h, 2·g·d_h, 2·d_h and d_c + d_R respectively (H is the number of query heads, g the number of groups, d_h the head dimension).
How much quality does GQA lose?
It depends on the setup, and there is no single number. The GQA paper converted a T5-XXL MHA checkpoint to GQA-8 with 5% extra training and got an average score of 47.1 against 47.2. In Llama 2's ablation (30B scale, 150B tokens) GQA matched MHA on most tasks. In DeepSeek-V2's 7B dense ablation (1.33T tokens) MHA scored 45.2 on MMLU against 41.2 for GQA-8, a clear gap. So GQA is not free; scale, training budget and how hard the benchmark is all change the gap, and you should test it in your own setting.
Is FlashAttention an approximation?
No. FlashAttention computes the same result as standard attention. It only splits the computation into blocks and accumulates them with an online softmax in the GPU's on-chip SRAM, so the N×N score matrix is never written back to GPU memory. What it saves is memory traffic and footprint, not FLOPs. In the paper's GPT-2 medium example the FLOPs rise slightly from 66.6 to 75.2 GFLOPs (the backward pass recomputes scores) while HBM traffic drops from 40.3 GB to 4.4 GB.
Does FlashAttention reduce the KV cache?
No. FlashAttention optimizes the intermediate results and memory traffic of one attention computation. The KV cache size is set by the number of layers, K/V heads, head dimension and sequence length, and is shrunk by GQA, MLA, sliding windows or cache quantization. The two kinds of optimization address different problems and can be combined.
Why does MLA cache a separate RoPE key?
Applying RoPE directly to the keys MLA reconstructs would put a position-dependent rotation between the query projection and the key up-projection. Matrix multiplication does not commute, so the trick of absorbing the key up-projection into the query no longer works, and inference would have to recompute the keys of every prefix token. DeepSeek-V2 carries position in a small separate part of the key instead (d_R is 64 in DeepSeek-V2 and V3) and caches it next to the latent vector.