Query, key, value matrices
What Are Q, K, V Matrices?
- Query matrix where
- Key matrix where
- Value matrix where
These are learned linear transformations that project each token into three different subspaces optimized for different purposes in the attention mechanism.
Why Three Separate Matrices?
WHY separate transformations?
-
Decoupling roles: The same token embedding serves different purposes. When token A attends to token B, we need:
- A's query: "What am I looking for?"
- B's key: "What do I represent for matching?"
- B's value: "What information should I contribute?"
-
Asymetric relationships: The similarity between "cat" and "sat" should be computed differently than the information "cat" provides. Keys handle matching geometry, values handle information geometry.
-
Optimization flexibility: Different weight matrices allow the network to learn that "cat" might query for verbs (high similarity with "sat" in Q-K space) but provide noun information (in V space).

Derivation from First Principles
Starting Point: What Problem Are We Solving?
We want each token to attend to relevant context. Raw embedings contain all semantic information mixed together. We need to:
Step 1: Define "relevance" as a similarity score
For token to determine relevance of token , we compute:
But raw dot product is too rigid—it uses the same dimensions for similarity that encode position, syntax, semantics, etc.
WHY this fails: The dimensions optimized for "word meaning" aren't necessarily optimized for "should attend to this."
Step 2: Project into a specialized "matching space"
Instead, transform into a query vector that represents "what I'm looking for":
where is learned to extract "search intent."
WHY: Now lives in a -dimensional space specifically optimized for computing relevance (typically for efficiency and preventing overfitting).
Step 3: Project comparison targets into a "key space"
Transform into a key vector that represents "what I offer":
Now relevance is computed as:
WHY separate and : Attention is directional. "The cat sat" → "cat" querying "sat" is different from "sat" querying "cat." Asymetric matrices encode asymetric relationships.
Step 4: Separate the information retrieval
Once we know relevance, we need to extract information. But the information we want from token might be different from what made it relevant!
Transform into a value vector :
where is optimized for "information content" not "matching."
WHY: In "The cat sat on the mat," when "sat" attends to "cat," the key helps decide that "cat" is relevant (subject-verb relationship), but the value determines what information "cat" provides (semantic features: animal, subject, etc.).
Full Matrix Form
For a sequence :
Where:
- Each row of is a query vector for one token
- Each row of is a key vector for one token
- Each row of is a value vector for one token
- are learned parameters updated via backpropagation
HOW they're used in attention:
Worked Examples
Suppose , and we have learned:
Compute query:
WHY this step? Projecting from 4D semantic space into 2D "search" space.
Step-by-step multiplication:
- First dimension:
- Second dimension:
Compute key:
- First dimension:
- Second dimension:
WHY different from query? Same token has different roles: "what I search for" vs. "what I offer when searched."
WHY dot product? Measures alignment in the attention space. High dot product = high relevance.
Interpretation: Token 1 has slight positive relevance to itself. In practice, this would be scaled by and combined with scores to other tokens before softmax.
WHY scaling? As grows, dot products grow in magnitude, pushing softmax into saturation regions. Scaling maintains gradient flow.
- First:
- Second:
- Third:
WHY different dimension ? Values encode information content, which may need different dimensionality than the matching space. Often for simplicity, but not required.
HOW used: After computing attention weights via softmax of relevance scores, the output for token is:
Common Mistakes
Why it feels right: We define their dimensions and roles architecturally.
Why it's wrong: are learned parameters. They start random and are optimized via gradient descent to learn what features matter for attention in this specific task.
The fix: Think of them as "learnable lenses" that the model tunes to focus on task-relevant patterns. In a translation model, they learn different patterns than in a summarization model.
Why it feels right: Sometimes you see "QKV" as a single matrix in implementation code.
Why it's wrong: Q, K, V are three different linear projections of the same input . They're not slicing into parts; they're transforming all of three different ways.
The fix:
- Not: (wrong: this is concatenation)
- Instead: , , (correct: three separate transformations)
Sometimes implementations optimize by computing and doing one matrix multiply, then splitting the result, but conceptually they're separate transformations.
Why it feels right: More dimensions = more information preserved.
Why it's wrong:
- Computational cost: Attention is . Reducing saves compute.
- Regularization: Lower-dimensional projections force the model to learn compressed, essential features for attention.
- Multi-head attention: With heads each of dimension , total dimension is , maintaining expressiveness across heads.
The fix: Think of as the dimension of the "attention query language"—a compressed, task-optimized space. Typical: where is number of heads.
How Q, K, V Enable Multi-Head Attention
In multi-head attention, we create sets of for . Each head:
- Computes , ,
- Runs attention:
- Heads are concatenated and projected:
WHY multiple heads? Different heads can learn different attention patterns:
- Head 1: syntactic relationships (subject-verb)
- Head 2: semantic similarity (synonyms)
- Head 3: positional patterns (nearby words)
Each head's Q, K, V matrices specialize in different aspects.
Recall Explain to a 12-Year-Old
Imagine you're in a class, and the teacher asks a question.
Query (Q): This is like your hand raised with your specific question written on a card—"I need help with fractions!"
Key (K): This is like everyone else in class holding up cards saying what they're good at—"I know fractions!" or "I'm great at spelling!" or "I know science!"
Value (V): This is the actual helpful information people can give you. Sarah's KEY says "I know fractions," but her VALUE is the actual explanation she can provide about how to add1/2 and 1/3.
The teacher (attention mechanism) looks at your QUERY card, compares it to everyone's KEY cards to find the best matches, then collects the VALUE information from those people and gives you a combined answer.
The magical part? The transformer learns how to write these cards! At first, it writes random stuff on the Q, K, V cards, but after seeing thousands of examples, it learns:
- How to write QUERY cards that ask the right questions
- How to write KEY cards that advertise relevant help
- How to write VALUE cards with the most useful information
And here's the coolest part: The same student (word token) has all three types of cards. When YOU ask a question, you use your QUERY card. But when SOMEONE ELSE asks, they look at your KEY card to see if you can help, and take information from your VALUE card.
Or: "Query the library, match the Keys on the spines, read the Values inside."
Connections
- Attention Mechanism: Q, K, V matrices are inputs to the attention function
- Scaled Dot-Product Attention: Uses to compute attention scores
- Multi-Head Attention: Creates multiple sets of Q, K, V projections
- Linear Layers: Q, K, V transformations are linear layers (matrix multiplications)
- Embedding Layer: Input comes from embedding layer
- Positional Encoding: Added to before Q, K, V projection
- Self-Attention: Q, K, V all derived from same sequence
- Cross-Attention: Q from one sequence, K and V from another (encoder-decoder)
- Backpropagation: How are learned
- Gradient Descent: Optimization algorithm updating weight matrices
#flashcards/ai-ml
What are the three matrices in attention and what does each represent conceptually? :: Query (Q) = "what I'm searching for", Key (K) = "what I offer for matching", Value (V) = "information I provide". They're learned linear projections of input embedings.
Given input , write the formulas for Q, K, V matrices :: , , where and are learned weight matrices.
Why do we use three separate weight matrices () instead of one?
What is the typical relationship between and , and why?
How is the attention score between token and token computed from Q and K?
Are , , fixed or learned parameters?
What's the difference between Q, K, V in self-attention vs. cross-attention?
Why can't we just use the raw embedings directly for computing attention scores?
In multi-head attention, how many sets of matrices are there?
What's the dimension of each row in the Q, K, V matrices?
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Query, Key, Value matrices attention mechanism ka core hai. Socho ki tumhare pas ek library hai aur tum koi specific book dhundh rahe ho. Tumara query (Q) wo search term hai jo tum type karte ho—"I need books about machine learning." Library ki har book kaek key (K) hai jo uska title ya description hai, jo tumhe bata hai ki ye book tumhare query se match karti hai ya nahi. Jab tum match mil jati hai, tum us book ka value (V) padhte ho, yani actual content.
Transformer mein yahi concept hai. Har token (word) ko teen different matrices se transform kiya jata hai: W^Q, W^K, aur W^V. Ye matrices learned parameters hain—model training ke dauran seekhta hai ki kaise queries likhni hai, kaise keys bani hai, aur kaise values encode karni hai. Jab "cat" token "sat" token ko attend karta hai, wo apne query se "sat" ki key ko match karta hai (kitna relevant hai?) aur phir "sat" ki value se information extract karta hai.
Yeh teen alag matrices isliye zaroori hain kyunki ek hi word ke teen roles ho sakte hain: searching, being searched, aur providing information. Multi-head attention mein ye aur powerful ban jata hai—har head apna alag QKV set use karke different patterns seekhta hai (syntax, semantics, position). Dimension typically chhota rakha jata hai () efficiency aur regularization ke liye. Yeh architecture transformers ko itna powerful banata hai ki wo complex language patterns samajh sake.
===VERIFY