Let’s build on our “whiteboard + highlighter” picture and introduce Q, K, V—and then see how “KV-caching” speeds things up.
1. What are Queries, Keys, and Values (Q, K, V)?
Every word (or token) in a transformer is converted into three vectors—think of them as three different “views” or “roles” for that word:
-
Query (Q)
– “What am I looking for?”
– If we’re trying to understand the next word, our Query vector asks, “Which past words are most relevant to help me here?”
-
Key (K)
– “What do I offer?”
– Every previous word shows up on the whiteboard with a Key vector that labels its content—like a little keyword index saying, “Here’s what I can tell you about.”
-
Value (V)
– “Here’s my info.”
– Attached to each Key is a Value vector, which is the actual content or embedding of that word that we can mix into our final answer.
How they work together
- For the current position (the word you want to process), you generate a Query.
- You compare that Query against every Key from all positions (including itself).
- The comparison scores tell you “how much attention” to pay to each position.
- You use those scores to take a weighted sum of all the Value vectors—this sum becomes your context-enhanced representation for the current word.
2. Why do we need Q, K, V?
If we only had one vector per word, we couldn’t cleanly separate
- “What I’m looking for” (Query)
- “What I have to offer” (Key)
- “What I’ll actually contribute” (Value)
Splitting into Q/K/V lets the model flexibly match any target (Query) against any source (Key) and then pull in exactly the right information (Value).
3. What is KV-Caching?
When you generate text step by step (inference), you repeatedly do attention over all tokens seen so far. Naïvely, at each new token you’d recompute Key and Value for every previous token. That’s wasteful.
KV-Caching means:
• After you process a token once, store its Key & Value in a cache.
• For the next token, you only:
1. Compute the new token’s Query, Key, Value.
2. Reuse (cache lookup) all prior Keys/Values—no need to recompute them.
3. Do the Query vs. all Keys dot-products, weight the Values, and move on.
Benefits of KV-Caching
• Speed: You avoid repeating work for previous tokens.
• Memory efficiency: You keep a rolling buffer of K/V instead of rebuilding everything.
• Real-time generation: Makes language models snappier when writing long passages.
Quick Recap
- Q, K, V let the model ask “What do I need?” (Q), match that against “What’s on offer?” (K), and then pull in the actual details (V).
- KV-Caching just means “save the K’s and V’s from tokens you’ve already processed, so you don’t recompute them every time you add a new token.”
Together, Q/K/V + KV-caching are the backbone of fast, context-aware transformers that power modern LLMs! 🚀