Search

Search papers and lessons

Fast Transformer Decoding: One Write-Head is All You Need

Noam Shazeer · 2019

Shazeer (2019) showed that sharing one set of keys and values across all attention heads makes Transformer decoding several times faster, with only a small loss in quality.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Neural network basics
  • Linear algebra
  • Probability
  • Architectures
  • ReadReady to readNot yet

TL;DR

Generating text with a Transformer is slow not because of arithmetic but because of memory traffic: at every new token the model reloads the keys and values of all earlier tokens. Shazeer's paper proposes multi-query attention, in which all query heads share one set of keys and one set of values. The cached data shrinks by the number of heads, and on a translation benchmark the decoder ran several times faster with a small loss in quality.

Builds on: Multi-Head Attention, KV Cache, GPU Memory Hierarchy · Leads to: Multi-Query Attention (the technique as used in later models)

Why it mattered

Almost every large language model that generates text runs an autoregressive decoder, so decoding speed is a direct cost of serving it. The paper's idea became a standard design choice. Google's PaLM model, released in 2022, used multi-query attention in its decoder, and the 2023 grouped-query attention work, which the Llama 2 models use in their larger sizes, generalises the idea from one shared key-value head to a few groups of them. Both trade a little modelling capacity for a much smaller key-value cache. The paper is short, and its contribution is a diagnosis: once training is parallel, the bottleneck at inference is how many bytes must be moved, not how many multiplications must be done.

The problem

A Transformer decoder produces one token at a time. To compute attention for the new token, it needs the keys and values of every earlier position in the same layer. Those are stored in the KV Cache and reloaded at every step. During training the whole target sentence is known in advance, so all positions are processed together as large matrix products. That is efficient, and the paper's analysis says the ratio of memory traffic to arithmetic is small in that setting.

Incremental decoding breaks this. The paper writes the number of arithmetic operations for n decoding steps as Θ(bnd²), where b is the batch size and d the model width, which is the same order as training. The memory accessed across the n steps is Θ(bn²d + nd²). The first term comes from reloading the keys and values, and the second from reloading the projection matrices. Dividing memory by arithmetic gives a ratio of Θ(n/d + 1/b). When the sequence length n is close to the width d, that ratio is close to 1. Modern accelerators can do roughly two orders of magnitude more arithmetic per second than they can move bytes, so a ratio near 1 leaves the processor waiting on memory. Two terms need to be pushed well below 1. The 1/b term is easy, because a larger batch fixes it if memory allows. The n/d term is the hard one, because it is set by the size of the keys and values.

Earlier fixes shorten the context, or restrict each position to a local window, or compress the memory. The paper says its approach is orthogonal: it leaves the number of attended positions alone and removes the head dimension from the keys and values only.

How it works

Multi-head attention runs h attention heads in parallel. Each head has its own learned projections for queries, keys and values, and the head outputs are combined by a final projection. Multi-query attention keeps the h query projections and collapses the key and value projections to one each. Every head then reads the same keys and values.

The walkthrough below uses a tiny layer with d = 4 model width, h = 2 heads, and key and value size k = v = 2, which is the paper's assumption k = v = d/h.

  1. Count what the cache holds for one position in multi-head attention. Each head stores its own key of size k = 2 and value of size v = 2. Two heads store 2 × (2 + 2) = 8 numbers per position.

  2. Change to multi-query attention. Keep two query projections, one per head, so each head still asks a different question of the sequence. Replace the two key projections and the two value projections with one key projection and one value projection. Each produces a single vector of size 2 for each position.

  3. Count again. The cache now stores one key and one value per position, which is 2 + 2 = 4 numbers. Check: 8 numbers became 4, a factor of 2. That factor equals h.

  4. Run one decoding step. A new token produces two queries, q₁ and q₂. Both are compared against the same cached keys K. Each head gets its own weights from its own query, and both weighted sums use the same cached values V. The two outputs are then projected and summed, as in the original layer.

  5. Interpret the result. The heads still differ in their queries, so they can still look at different things. They share only the record of what is in the context. The cost of reloading that record drops by the factor h, and the extra query projections cost little.

flowchart LR
  subgraph MHA[Multi-head: one K and V per head]
    q1[q1] --> a1[head 1 attention]
    q2[q2] --> a2[head 2 attention]
    K1[K1, V1] --> a1
    K2[K2, V2] --> a2
  end
  subgraph MQA[Multi-query: one K and V for all heads]
    r1[q1] --> b1[head 1 attention]
    r2[q2] --> b2[head 2 attention]
    KS[K, V shared] --> b1
    KS --> b2
  end

The math

The paper's notation follows the code in its Section 2. Here b is batch size, n is the number of query positions in a step, m is the number of key-value positions, d is model width, h is the number of heads, and k and v are the key and value sizes. The paper assumes m = n, k = v = d/h, and n ≤ d.

Step 2 in symbols: the projections

For one query x in multi-head attention, head i computes

qi=xPq(i),Ki=MPk(i),Vi=MPv(i)q_i = x P_q^{(i)}, \qquad K_i = M P_k^{(i)}, \qquad V_i = M P_v^{(i)}

where M stacks the m positions whose keys and values are cached. Each head has its own K_i and V_i.

In multi-query attention the key and value projections lose the head index:

K=MPk,V=MPvK = M P_k, \qquad V = M P_v

Every head uses the same K and V, and only q_i still depends on i. The output of head i is

oi=softmax⁡ ⁣(qiK⊤k)Vo_i = \operatorname{softmax}\!\left(\frac{q_i K^{\top}}{\sqrt{k}}\right) V

The paper's code omits the constant scaling factor on the logits, which it says can be folded into a projection. The softmax turns each row of scores into weights that sum to 1, as in the Softmax lesson.

Step 3 in symbols: cache size per position

Let c_MHA and c_MQA be the number of numbers stored per cached position in one layer. Each head stores a key of size k and a value of size v, so

cMHA=h(k+v),cMQA=k+vc_{\text{MHA}} = h(k + v), \qquad c_{\text{MQA}} = k + v

With k = v = d/h,

cMHA=2d,cMQA=2dhc_{\text{MHA}} = 2d, \qquad c_{\text{MQA}} = \frac{2d}{h}

The ratio is h. For the paper's baseline, h = 8, so the cache is eight times smaller per position. The derivation uses only the head count, so it holds whatever the other sizes are.

Step 4 in symbols: memory per arithmetic operation

For n incremental steps the paper gives

memory accessedarithmetic=Θ ⁣(nd+1b)(multi-head)\frac{\text{memory accessed}}{\text{arithmetic}} = \Theta\!\left(\frac{n}{d} + \frac{1}{b}\right) \quad \text{(multi-head)} memory accessedarithmetic=Θ ⁣(1d+ndh+1b)(multi-query)\frac{\text{memory accessed}}{\text{arithmetic}} = \Theta\!\left(\frac{1}{d} + \frac{n}{dh} + \frac{1}{b}\right) \quad \text{(multi-query)}

The n/d term is divided by h. A 1/d term from the projections also appears, but it is small next to n/d for any n of at least 1. Here Θ hides constant factors. The paper summarises this as reducing the offending term "by a factor of h".

Step 5 in symbols: what the claim does and does not say

The ratio is an asymptotic statement about the cost of loading the cache relative to the arithmetic. It says that decoding should become faster when the cache term dominates. It does not give a wall-clock speedup directly, because real speed also depends on how the hardware overlaps loading and computing, and on the padding the experiments used. The measured numbers in the next section are what test the claim.

Results

The paper trains one baseline Transformer and several variants on WMT 2014 English to German translation, and a decoder-only language model on the Billion-Word benchmark. The baseline is 6 layers, width d_model = 1024, h = 8, k = v = 128, feed-forward size 4096, and 211 million parameters. The multi-query model widens the feed-forward layer to 5440 so that its total parameter count matches the baseline. Training used 100,000 steps on a 32-core TPUv3 cluster.

Quality, from the paper's Table 1 (WMT14 EN-DE):

AttentionFeed-forward sizeDev log-perplexityDev BLEUTest BLEU, beam 1 / beam 4
multi-head40961.42426.727.7 / 28.4
multi-query54401.43926.527.5 / 28.5
multi-head, h = 167841.51825.8not reported

Lower perplexity is better. BLEU is a score that counts overlapping word sequences between the model output and a human reference translation, and higher is better. Multi-query is slightly worse than the baseline on the dev set, and on the test set with beam search it is slightly higher (28.5 against 28.4). It is clearly better than the variants that reduce the number of heads.

Speed, from the paper's Table 2, measured in TPUv2 microseconds per output token on one TPUv2 with 8 cores:

AttentionTrainingInference, encoder + decoderBeam-4, encoder + decoder
multi-head13.21.7 + 462.0 + 203
multi-query13.01.5 + 3.81.6 + 32

The decoder is about 12 times faster per token under greedy decoding (46 down to 3.8) and about 6 times faster under beam-4 search (203 down to 32). Training cost is unchanged, as the analysis predicted. The encoder runs once per input and changes little (1.7 to 1.5 microseconds per token).

Limits. The results are from one hardware generation and two benchmarks, and the decoder timings used padded tensors of fixed length, so every step took the same time. The paper says a version that grows the tensors would be faster early in the sequence, but it does not measure that. The quality drop is small in these experiments, not zero. The language-model results show the same pattern, with the multi-query model at a dev perplexity of 30.2 against 29.9 for the baseline.

Reading guide

Read the paper in this order. Each section names the lessons it leans on.

  • Abstract and Section 1. The problem in one paragraph. Needs Transformer and Autoregressive Model.
  • Section 2.1 (dot-product attention). A query compared against keys, weights from a Softmax, and a weighted sum of values. Needs Attention Mechanism and Softmax.
  • Section 2.2 and 2.3 (multi-head attention, batched). The projections for each head and the einsum notation, which is a shorthand for Tensor Contraction. Needs Multi-Head Attention and Matrix Multiplication.
  • Section 2.3.1 (performance analysis of training). The arithmetic and memory counts for a batch. Needs Big-O Notation and GPU Memory Hierarchy.
  • Section 2.4 (incremental attention). Why decoding must run one step at a time and what the cache holds. Needs KV Cache.
  • Section 3 (multi-query attention). The one-line change to the code and the cache-size argument. Needs Multi-Query Attention.
  • Section 4 (experiments). Read Tables 1 and 2 against the claims. The BLEU score and perplexity are defined in words above.
  • Section 5 (conclusion). Short; it states the claim the paper is making about adoption.

Check yourself

QuestionRecall: in multi-query attention, what is shared across heads, and what stays separate?Show answer

The keys and values are shared: there is one key projection and one value projection, so every head reads the same cached keys and values. The queries stay separate, one projection per head, so the heads still ask different questions of the same context.

QuestionComputation: a model has d = 512 and h = 8, so k = v = 64. How many numbers does one cached position occupy per layer under multi-head attention, and under multi-query attention?Show answer

Multi-head stores h(k + v) = 8 × (64 + 64) = 1,024 numbers, which equals 2d. Multi-query stores k + v = 128 numbers, which equals 2d / h. The ratio is 8, which is h.

QuestionWhy: why does sharing keys and values reduce decoding time more than it reduces training time?Show answer

Training processes all positions of a known target sentence together, so its arithmetic is large relative to the memory it loads, and the cache-loading cost is a small share. Incremental decoding loads the whole cache at every step for only one new position, so memory traffic dominates. Shrinking the cache by h cuts that dominant cost, while training cost is essentially unchanged, as Table 2 shows (13.2 against 13.0).

QuestionApplied: a team serves a model with a long context and finds that decoding at batch size 1 is slow. Their profiler shows the time is spent loading keys and values. Would switching to multi-query attention help, and what would they give up?Show answer

Yes, it should help, because the bottleneck is the cache-loading term, which is the one multi-query attention divides by h. The cost is a small loss in quality, which the paper measured as a slightly higher perplexity and similar BLEU. At batch size 1 the 1/b term is also large, so the gain will be smaller than the factor h suggests unless the team can also batch requests. They should measure on their own hardware, because the paper's padded-decoding setup is a simplification.

Sources

Read the full paper

Noam Shazeer, 2019. arXiv:1911.02150