Okay, let's break down the KV Cache mechanism in detail.
The Transformer Architecture & Self-Attention (Brief Refresher)
Transformer models, the backbone of most modern LLMs, rely heavily on the self-attention mechanism. In a nutshell, self-attention allows the model to weigh the importance of different words (or tokens) in the input sequence when processing a specific word.
For each token in the sequence, the model computes three vectors:
- Query (Q): Represents the current token's "question" or focus.
- Key (K): Represents what information a token "holds" or signifies.
- Value (V): Represents the actual content or meaning of a token.
The attention score between two tokens (say, token i and token j) is calculated based on the compatibility between token i's Query (Qi) and token j's Key (Kj). This is often done using a dot product: scoreij=Qi⋅Kj. These scores are then scaled and passed through a softmax function to get attention weights (aij).
Finally, the output for token i is a weighted sum of the Value vectors (V) of all tokens in the sequence, using the calculated attention weights: Outputi=∑.
Crucially, the Key (K) and Value (V) vectors are derived from the input embeddings of the tokens themselves. The Query (Q) vector is also derived from the input embedding, but it represents the perspective of the current token.
The Problem: Autoregressive Generation & Recomputation
LLMs typically generate text autoregressively. This means they predict one token at a time, and each new token is added to the sequence, becoming part of the input for predicting the next token.
Consider generating a sentence: "The quick brown fox".
- Input: "The" -> Predict "quick"
- Input: "The quick" -> Predict "brown"
- Input: "The quick brown" -> Predict "fox"
- Input: "The quick brown fox" -> Predict "."
Now, let's think about the self-attention calculation when predicting the third token ("brown"). The model needs to compute attention scores between "brown" (as the Query) and all previous tokens ("The", "quick") (as Keys and Values).
When predicting the fourth token ("fox"), the model again needs to compute attention scores between "fox" (Query) and all previous tokens ("The", "quick", "brown").
If we do this naively, for every single token we generate, we would recompute the Key (K) and Value (V) vectors for all the preceding tokens in the sequence. If the sequence gets long (e.g., hundreds or thousands of tokens), this becomes incredibly inefficient and computationally expensive.
The Solution: The KV Cache
The KV Cache addresses this inefficiency during the inference (generation) phase.
How it works:
- Prompt Processing: When the initial prompt is fed into the model, the Key (K) and Value (V) vectors are computed for each token in the prompt.
- Caching: These computed K and V vectors (often grouped by layer and attention head) are stored in a cache (a dedicated memory space).
- Generating the Next Token:
- The model computes the Query (Q) vector for the current token (the one being generated).
- It then performs the attention calculation using this new vector against the vectors stored in the cache (from previous tokens).
In essence, the KV cache stores the Keys and Values computed for previous tokens, so they don't need to be recomputed at each generation step. Only the K and V for the newly generated token need to be computed and added.
This significantly speeds up the generation process because the most computationally intensive part (computing K and V for the entire history) is largely avoided after the initial prompt processing.
Simple Showcase
Let's imagine a tiny Transformer processing sequence generation. We'll simplify vectors to just numbers and focus on one attention head in one layer.
Sequence Goal: Generate text following "Hello ". Target: "Hello world!"
Step 1: Process Prompt ("Hello ")
- Input Embeddings:
- EHello (Embedding for "Hello")
- E (Embedding for " ")
- Compute K, V for prompt tokens:
- , = ComputeKV()
Step 2: Generate Token 3 ("world")
- Input Embedding: Eworld (This embedding conceptually represents the state after "Hello ")
- Compute Q, K, V for the new token:
- Qworld, , = ComputeQKV()
Step 3: Generate Token 4 ("!")
- Input Embedding: E! (Represents state after "Hello world")
- Compute Q, K, V for the new token:
- Q!, , = ComputeQKV()
And so on...
Why Not a Query Cache?
The idea of caching seems appealing, so why don't we typically use a "Query Cache" in the same way?
-
Purpose of Q vs K/V:
- K and V: These vectors represent the content and context of the tokens already processed (the history). This information is static for a given token and is useful for any subsequent token that needs to attend to it. Caching them avoids redundant computation of the sequence's history.
- Q: The Query vector represents the current token's perspective and what information it is seeking from the history (K/V). In autoregressive generation, the "current" token is always the newly generated one. Its Q vector is fundamentally tied to its position and the specific context at that moment.
-
Dynamic Nature: The Q vector changes entirely with each new token being generated. Caching a Q vector from a previous step wouldn't be useful for the next step because the context has changed (a new token has been added), and the new token needs to formulate a new query based on this updated context.
-
Calculation vs. Storage: The KV cache optimizes by storing pre-computed values (K and V) that are needed repeatedly. The vector is computed based on the state. While you could technically store the vector for the token you just generated, it's not helpful for generating the token. The next token needs its unique . Re-using a previous would mean asking the same question as a previous token, which isn't how autoregressive generation works.
Think of it like reading a book:
- KV Cache: Like remembering the key points and details (K and V) of the chapters you've already read. You don't need to re-read the chapters every time you want to understand the context for the next sentence.
- Query (Q): Like the question forming in your mind right now as you read the current sentence. This question is specific to your current understanding and what you want to know next. It's based on everything you've read so far, but it's a new question for the current moment. You wouldn't reuse the question you had two paragraphs ago because your focus might have shifted.
Therefore, the KV cache focuses on storing the parts of the attention calculation (K and V) that represent the static history and are needed by dynamically changing Queries, making the generation process much faster.