Hi, I'm Matsuken, a data scientist at a Japanese technology company.
In this article, I'll explain how decoding works in a Transformer that uses a key-value (KV) cache.
This is an English version of my original Japanese article, which I originally wrote and published on Qiita.
Transformer inference consists of two stages:
- Prefill: Process all input tokens—the prompt—in parallel. During this stage, the model computes the keys ( ) and values ( ) and stores them in a cache.
- Decode: Generate text one token at a time. At each step, the model reads and reuses the previously computed keys and values, then appends one new row—the key and value for the latest token—to the cache.
For an explanation of the first stage, prefill, see my previous article. The stored and tensors produced by this process are collectively called the KV cache.
Given an input , an attention layer computes the queries, keys, and values as follows:
It then produces the output :
The process is illustrated below.1
Here, is the number of tokens and is the token representation dimension.
In a decoder-only Transformer, this computation takes place in every Multi-Head Attention block: each block receives and produces .2
Prefill
During the initial pass, the input normally contains multiple tokens, so it is an matrix. This is the prefill stage covered in my previous article.
The next stage—decode—is where the KV cache comes into play.
Decode
Prefill processes the prompt and determines the first generated token. In each subsequent decode step, the model receives the token generated in the previous step and autoregressively predicts the next token.
Conceptually, we could append every generated token to the original input sequence and process the entire sequence again. In practice, this would repeatedly perform the same computations. Instead, the model computes only the new query, key, and value vectors for the latest token. It reuses the keys and values for all previous tokens from the KV cache. This reuse is the purpose of the KV cache.
Suppose the prompt is:
[BOS] two kids are playing in a swimming pool with a green colored crocodile.
and the first generated token is “Then.”
Because tokens have already been processed, the model uses the representation of token to compute three new vectors: , , and .
Next, the model updates and . It reuses the entries through position from the cache and appends and , respectively.
The new query is multiplied by the transpose of the updated key matrix, which consists of the cached keys followed by . This produces the attention-score vector .
The model applies softmax to and multiplies the resulting attention weights by the updated value matrix—the cached values followed by . The result is .
We have now obtained the required by this layer.
Although the explanation above follows the operations step by step, we can also view the computation as part of a conceptual full attention matrix. It has three regions: entries that were computed in previous steps, future positions excluded by the causal mask, and the newly computed row for the current step.
The complete decode-step computation can be summarized as follows:
You might wonder whether alone is enough, or whether the model also needs . Recall that this step required only because the earlier keys and values were already cached. Therefore, computing only is sufficient.
As long as and are cached, each subsequent step needs only the representation of the newest token to produce the next-token output. That is what makes decoding with a KV cache so efficient.
The model maintains a separate KV cache for every Transformer layer. If the model has layers, it therefore has cache pairs:
This efficiency comes with a trade-off: as the number of tokens—the context-window length—increases, the memory required to store the key and value caches also grows. Several techniques address this issue, but I'll save those for another article.










Top comments (0)