4.1.3Transformer Architecture

Query, key, value matrices

2,898 words13 min readdifficulty · medium2 backlinks

What Are Q, K, V Matrices?

  • Query matrix Q=XWQQ = XW^Q where WQRdmodel×dkW^Q \in \mathbb{R}^{d_{model} \times d_k}
  • Key matrix K=XWKK = XW^K where WKRdmodel×dkW^K \in \mathbb{R}^{d_{model} \times d_k}
  • Value matrix V=XWVV = XW^V where WVRdmodel×dvW^V \in \mathbb{R}^{d_{model} \times d_v}

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?

  1. 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?"
  2. 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.

  3. 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).

Figure — Query, key, value matrices

Derivation from First Principles

Starting Point: What Problem Are We Solving?

We want each token to attend to relevant context. Raw embedings xiRdmodelx_i \in \mathbb{R}^{d_{model}} contain all semantic information mixed together. We need to:

Step 1: Define "relevance" as a similarity score

For token ii to determine relevance of token jj, we compute: relevancei,j=similarity(xi,xj)\text{relevance}_{i,j} = \text{similarity}(x_i, x_j)

But raw dot product xixjx_i \cdot x_j 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 xix_i into a query vector qiq_i that represents "what I'm looking for": qi=WQxiq_i = W^Q x_i

where WQRdk×dmodelW^Q \in \mathbb{R}^{d_k \times d_{model}} is learned to extract "search intent."

WHY: Now qiq_i lives in a dkd_k-dimensional space specifically optimized for computing relevance (typically dk<dmodeld_k < d_{model} for efficiency and preventing overfitting).

Step 3: Project comparison targets into a "key space"

Transform xjx_j into a key vector kjk_j that represents "what I offer": kj=WKxjk_j = W^K x_j

Now relevance is computed as: relevancei,j=qikj=(WQxi)T(WKxj)\text{relevance}_{i,j} = q_i \cdot k_j = (W^Q x_i)^T (W^K x_j)

WHY separate WQW^Q and WKW^K: 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 jj might be different from what made it relevant!

Transform xjx_j into a value vector vjv_j: vj=WVxjv_j = W^V x_j

where WVRdv×dmodelW^V \in \mathbb{R}^{d_v \times d_{model}} 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 X=[x1,x2,,xn]TRn×dmodelX = [x_1, x_2, \ldots, x_n]^T \in \mathbb{R}^{n \times d_{model}}:

Where:

  • Each row of QQ is a query vector for one token
  • Each row of KK is a key vector for one token
  • Each row of VV is a value vector for one token
  • WQ,WK,WVW^Q, W^K, W^V are learned parameters updated via backpropagation

HOW they're used in attention: Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

Worked Examples

Suppose dk=2d_k = 2, and we have learned: WQ=[0.10.40.20.10.30.50.60.2],WK=[0.20.30.50.10.40.20.10.6]W^Q = \begin{bmatrix} 0.1 & 0.4 \\ 0.2 & -0.1 \\ -0.3 & 0.5 \\0.6 & 0.2 \end{bmatrix}, \quad W^K = \begin{bmatrix} -0.2 & 0.3 \\ 0.5 & 0.1 \\ 0.4 & -0.2 \\ -0.1 & 0.6 \end{bmatrix}

Compute query: q1=x1WQ=[0.5,0.3,0.8,0.2][0.10.40.20.10.30.50.60.2]q_1 = x_1 W^Q = [0.5, -0.3, 0.8, 0.2] \begin{bmatrix} 0.1 & 0.4 \\ 0.2 & -0.1 \\ -0.3 & 0.5 \\ 0.6 & 0.2 \end{bmatrix}

WHY this step? Projecting from 4D semantic space into 2D "search" space.

Step-by-step multiplication:

  • First dimension: 0.5(0.1)+(0.3)(0.2)+0.8(0.3)+0.2(0.6)=0.050.060.24+0.12=0.130.5(0.1) + (-0.3)(0.2) + 0.8(-0.3) + 0.2(0.6) = 0.05 - 0.06 - 0.24 + 0.12 = -0.13
  • Second dimension: 0.5(0.4)+(0.3)(0.1)+0.8(0.5)+0.2(0.2)=0.20+0.03+0.40+0.04=0.670.5(0.4) + (-0.3)(-0.1) + 0.8(0.5) + 0.2(0.2) = 0.20 + 0.03 + 0.40 + 0.04 = 0.67

q1=[0.13,0.67]q_1 = [-0.13, 0.67]

Compute key: k1=x1WK=[0.5,0.3,0.8,0.2][0.20.30.50.10.40.2 0.10.6]k_1 = x_1 W^K = [0.5, -0.3, 0.8, 0.2] \begin{bmatrix} -0.2 & 0.3 \\ 0.5 & 0.1 \\ 0.4 & -0.2 \ -0.1 & 0.6 \end{bmatrix}

  • First dimension: 0.5(0.2)+(0.3)(0.5)+0.8(0.4)+0.2(0.1)=0.100.15+0.320.02=0.050.5(-0.2) + (-0.3)(0.5) + 0.8(0.4) + 0.2(-0.1) = -0.10 - 0.15 + 0.32 - 0.02 = 0.05
  • Second dimension: 0.5(0.3)+(0.3)(0.1)+0.8(0.2)+0.2(0.6)=0.150.030.16+0.12=0.080.5(0.3) + (-0.3)(0.1) + 0.8(-0.2) + 0.2(0.6) = 0.15 - 0.03 - 0.16 + 0.12 = 0.08

k1=[0.05,0.08]k_1 = [0.05, 0.08]

WHY different from query? Same token has different roles: "what I search for" vs. "what I offer when searched."

score1,1=q1k1=[0.13,0.67][0.05,0.08]\text{score}_{1,1} = q_1 \cdot k_1 = [-0.13, 0.67] \cdot [0.05, 0.08]

WHY dot product? Measures alignment in the attention space. High dot product = high relevance.

=(0.13)(0.05)+(0.67)(0.08)=0.0065+0.0536=0.047= (-0.13)(0.05) + (0.67)(0.08) = -0.0065 + 0.0536 = 0.047

Interpretation: Token 1 has slight positive relevance to itself. In practice, this would be scaled by 1dk=120.707\frac{1}{\sqrt{d_k}} = \frac{1}{\sqrt{2}} \approx 0.707 and combined with scores to other tokens before softmax.

WHY scaling? As dkd_k grows, dot products grow in magnitude, pushing softmax into saturation regions. Scaling maintains gradient flow.

v1=x1WV=[0.5,0.3,0.8,0.2][0.30.20.50.10.40.20.60.10.30.20.50.4]v_1 = x_1 W^V = [0.5, -0.3, 0.8, 0.2] \begin{bmatrix} 0.3 & -0.2 & 0.5 \\ -0.1 & 0.4 & 0.2 \\ 0.6 & 0.1 & -0.3 \\ 0.2 & -0.5 & 0.4 \end{bmatrix}

  • First: 0.5(0.3)+(0.3(0.1)+0.8(0.6)+0.2(0.2)=0.15+0.03+0.48+0.04=0.700.5(0.3) + (-0.3(-0.1) + 0.8(0.6) + 0.2(0.2) = 0.15 + 0.03 + 0.48 + 0.04 = 0.70
  • Second: 0.5(0.2)+(0.3)(0.4)+0.8(0.1)+0.2(0.5)=0.100.12+0.080.10=0.240.5(-0.2) + (-0.3)(0.4) + 0.8(0.1) + 0.2(-0.5) = -0.10 - 0.12 + 0.08 - 0.10 = -0.24
  • Third: 0.5(0.5)+(0.3)(0.2)+0.8(0.3)+0.2(0.4)=0.250.060.24+0.08=0.030.5(0.5) + (-0.3)(0.2) + 0.8(-0.3) + 0.2(0.4) = 0.25 - 0.06 - 0.24 + 0.08 = 0.03

v1=[0.70,0.24,0.03]v_1 = [0.70, -0.24, 0.03]

WHY different dimension dvd_v? Values encode information content, which may need different dimensionality than the matching space. Often dv=dkd_v = d_k for simplicity, but not required.

HOW used: After computing attention weights αi,j\alpha_{i,j} via softmax of relevance scores, the output for token ii is: outputi=j=1nαi,jvj\text{output}_i = \sum_{j=1}^n \alpha_{i,j} v_j

Common Mistakes

Why it feels right: We define their dimensions and roles architecturally.

Why it's wrong: WQ,WK,WVW^Q, W^K, W^V 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 XX. They're not slicing XX into parts; they're transforming all of XX three different ways.

The fix:

  • Not: [QKV]=X[Q | K | V] = X (wrong: this is concatenation)
  • Instead: Q=XWQQ = XW^Q, K=XWKK = XW^K, V=XWVV = XW^V (correct: three separate transformations)

Sometimes implementations optimize by computing WQKV=[WQWKWV]W^{QKV} = [W^Q | W^K | W^V] 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:

  1. Computational cost: Attention is O(n2dk)O(n^2 d_k). Reducing dkd_k saves compute.
  2. Regularization: Lower-dimensional projections force the model to learn compressed, essential features for attention.
  3. Multi-head attention: With hh heads each of dimension dkd_k, total dimension is hdk=dmodelh \cdot d_k = d_{model}, maintaining expressiveness across heads.

The fix: Think of dkd_k as the dimension of the "attention query language"—a compressed, task-optimized space. Typical: dk=dmodel/hd_k = d_{model} / h where hh is number of heads.

How Q, K, V Enable Multi-Head Attention

In multi-head attention, we create hh sets of (WiQ,WiK,WiV)(W^Q_i, W^K_i, W^V_i) for i=1,,hi = 1, \ldots, h. Each head:

  1. Computes Qi=XWiQQ_i = XW^Q_i, Ki=XWiKK_i = XW^K_i, Vi=XWiVV_i = XW^V_i
  2. Runs attention: headi=Attention(Qi,Ki,Vi)\text{head}_i = \text{Attention}(Q_i, K_i, V_i)
  3. Heads are concatenated and projected: MultiHead(Q,K,V)=Concat(head1,,headh)WO\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h)W^O

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 QKTQK^T 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 XX comes from embedding layer
  • Positional Encoding: Added to XX 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 WQ,WK,WVW^Q, W^K, W^V 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 XRn×dmodelX \in \mathbb{R}^{n \times d_{model}}, write the formulas for Q, K, V matrices :: Q=XWQQ = XW^Q, K=XWKK = XW^K, V=XWVV = XW^V where WQ,WKRdmodel×dkW^Q, W^K \in \mathbb{R}^{d_{model} \times d_k} and WVRdmodel×dvW^V \in \mathbb{R}^{d_{model} \times d_v} are learned weight matrices.

Why do we use three separate weight matrices (WQ,WK,WVW^Q, W^K, W^V) instead of one?
Decouples three roles: searching (Q), being searched (K), and providing information (V). Allows asymetric relationships—attention from A to B differs from B to A. Enables different optimization for matching vs. information content.
What is the typical relationship between dkd_k and dmodeld_{model}, and why?
dk<dmodeld_k < d_{model}, typically dk=dmodel/hd_k = d_{model}/h where hh is the number of attention heads. Reasons: computational efficiency (O(n2dk)O(n^2 d_k)), regularization through dimensionality reduction, and enabling multiple specialized heads.
How is the attention score between token ii and token jj computed from Q and K?
scorei,j=qikj=(qi)Tkj\text{score}_{i,j} = q_i \cdot k_j = (q_i)^T k_j, often scaled by 1dk\frac{1}{\sqrt{d_k}} to prevent gradient saturation as: qikjdk\frac{q_i \cdot k_j}{\sqrt{d_k}}.
Are WQW^Q, WKW^K, WVW^V fixed or learned parameters?
Learned parameters. They start random and are optimized via backpropagation to learn task-specific patterns for attention.
What's the difference between Q, K, V in self-attention vs. cross-attention?
Self-attention: Q, K, V all come from the same sequence (Q=K=V=XQ = K = V = X). Cross-attention: Q from one sequence (e.g., decoder), K and V from another (e.g., encoder).
Why can't we just use the raw embedings XX directly for computing attention scores?
Raw embeddings mix all semantic information (meaning, syntax, position). We need specialized subspaces: one optimized for "what to search for" (Q-K space for matching) and another for "what to retrieve" (V space for information).
In multi-head attention, how many sets of WQ,WK,WVW^Q, W^K, W^V matrices are there?
hh sets (one per head), where hh is the number of attention heads. Each head learns to focus on different patterns or relationships.
What's the dimension of each row in the Q, K, V matrices?
Each row in Q and K has dimension dkd_k. Each row in V has dimension dvd_v. Each row corresponds to one token in the sequence.

Concept Map

WQ projection

WK projection

WV projection

search intent

matching geometry

relevance scores

weight contribution

information geometry

motivates

motivates

motivates

prevents overfitting

Input X n x d_model

Query matrix Q

Key matrix K

Value matrix V

Query-Key matching

Attention weights

Output context

Decoupled roles

Specialized subspace d_k

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 (dk<dmodeld_k < d_{model}) efficiency aur regularization ke liye. Yeh architecture transformers ko itna powerful banata hai ki wo complex language patterns samajh sake.

===VERIFY

Go deeper — visual, from zero

Test yourself — Transformer Architecture

Connections