4.1.3 · D4Transformer Architecture

Exercises — Query, key, value matrices

3,096 words14 min readBack to topic

This page is a self-test ladder for Query, key, value matrices. Every problem states the goal cleanly, then hides a complete worked solution inside a collapsible callout. Reveal only after you try.

Before we begin, one promise: every symbol used below is defined here or in the parent note. We reuse only these:

Figure — Query, key, value matrices

Level 1 — Recognition

Exercise 1.1 — Shape reading

Given and , what is the shape of ? How many query vectors are there, and how long is each?

Recall Solution

Matrix multiply rule: . The inner s must match — and they do. So . There are 5 query vectors (one per token, one per row), each of length 3 (). What it looks like: 5 rows stacked, each row a short 3-number "search request."

Exercise 1.2 — Naming roles

In the library analogy, match each object to its job: (a) , (b) , (c) .

Recall Solution
  • (a) = your search request — "what token is looking for."
  • (b) = the book spine label of token — used only to decide whether is relevant.
  • (c) = the book's actual content of token — the information handed over once is judged relevant. Key point: and come from the same token but do different jobs, so they use different matrices ( vs ).

Exercise 1.3 — True/False

" are fixed by the architecture and never change during training." True or false?

Recall Solution

False. They are learned parameters, initialised randomly and updated by Backpropagation via gradient descent. The architecture fixes only their shapes ( etc.), not their values.


Level 2 — Application

Exercise 2.1 — Compute one query vector

Let (so ) and Compute .

Recall Solution

Walk down each column of , dot it with — exactly the column rule pictured in figure s01.

  • Column 1 = : .
  • Column 2 = : . What it looks like: the 3D token got squeezed to a 2D arrow pointing right-and-down in "search space" (figure s02).

Exercise 2.2 — Two tokens at once

Using the same , add token . Stack and compute .

Recall Solution

Row 1 is from before. Row 2:

  • Col 1 with : .
  • Col 2 with : . Each row is one token's query. The whole matrix is just Exercise 2.1 done in parallel for every token — that's why we batch as instead of looping.

Exercise 2.3 — Key for a token

With and compute .

Recall Solution
  • Col 1 .
  • Col 2 .

Exercise 2.4 — When : value projection to a different size

Same token . Now suppose keys live in but values live in (a genuinely different-sized "information space"). With compute and state its length.

Recall Solution

Column rule again (figure s01), :

  • Col 1 : .
  • Col 2 : .
  • Col 3 : . The edge case that matters: have length but has length . That is legal — keys are only used inside the dot product (both length , so it works), while values are summed separately to build the output. The output vector then has length , not . Matching space and information space are decoupled.
Figure — Query, key, value matrices

Level 3 — Analysis

Exercise 3.1 — A relevance score

Take (Ex 2.1) and (Ex 2.3). Compute the raw relevance score , then the scaled score with .

Recall Solution

Raw: . Scaled: . Interpretation: negative score → token 1's query points against token 2's key. After softmax this will get a low attention weight. The shrink keeps scores from blowing up as grows (which would push softmax into flat, gradient-starved regions).

Exercise 3.2 — Directionality of attention

Is (token 1 querying token 2) necessarily equal to ? Compute to test it. Use (Ex 2.2) and with .

Recall Solution

First get , :

  • Col 1 .
  • Col 2 . Now . Compare: but . They are different. Why: attention is directional. Because , "1 looking at 2" and "2 looking at 1" use different projections — exactly the asymmetry the parent note stressed ("cat querying sat" ≠ "sat querying cat"). Figure s03 draws all four arrows () so you can see that points away from (negative) while leans toward (positive).
Figure — Query, key, value matrices

Exercise 3.3 — Why not one shared matrix?

Suppose an engineer sets . Show that self-scores then equal , and explain what capacity is lost.

Recall Solution

If then . So A token can now never assign itself a negative raw score and the score matrix becomes symmetric (). Lost capacity: the model can no longer express asymmetric relations ("A should attend to B strongly but not vice-versa"). Two separate matrices restore that freedom.


Level 4 — Synthesis

Exercise 4.1 — Full single-head attention output for one token

Given (all computed above or here): Compute the attention output for token 1: (1) raw scores , (2) scale by , (3) softmax into weights , (4) output .

Recall Solution

Notation for this problem: we write a plain for a raw score , and a tilde for its scaled version . The tilde is just "same score, after dividing by " — no new maths, only a short label so we don't rewrite the division every line.

Step 1 — raw scores ():

  • .
  • .

Step 2 — scale by (this produces the tilde versions):

Step 3 — softmax, shown from scratch. Softmax of two numbers is by definition Why we can simplify: divide numerator and denominator by (allowed — it is a nonzero common factor): Here we gave the gap between the two scaled scores a short name: (a single number). We introduce it only because it makes the formula show clearly that only the difference of scores matters, not their absolute size — this compact is the logistic (sigmoid) form that any two-way softmax reduces to. Now , so Token 1 attends almost entirely to itself.

Step 4 — output (): What it looks like: because token 1's query aligns strongly with its own key and clashes with token 2's, the output is essentially — it copied its own value. This is one row of from Scaled Dot-Product Attention.

Exercise 4.2 — Same machinery, cross-attention

In Cross-Attention the queries come from a decoder sequence but keys/values from an encoder sequence. If decoder has 4 tokens and encoder has 7 tokens, with , give the shapes of , , , the score matrix , and the final output.

Recall Solution
  • : from 4 decoder tokens → .
  • : from 7 encoder tokens → .
  • : from 7 encoder tokens → .
  • : — one score per (decoder token, encoder token) pair.
  • Output : — one vector per decoder token. The only change from Self-Attention is where the rows of come from; the algebra is identical.

Level 5 — Mastery

Exercise 5.1 — Multi-head parameter count

Multi-Head Attention uses heads, each with its own of shape (and ), with . For , : (a) find , (b) count parameters in one head's three matrices, (c) count across all heads, (d) compare to a single head that uses the full width .

Recall Solution

(a) . (b) One head: three matrices each params → . (c) All heads: params. (d) Single full-width head, : three matrices each . They are equal: . Multi-head doesn't cost more parameters — it splits the same budget into independent subspaces, each learning a different relation pattern.

Exercise 5.2 — Degenerate input: the zero token

Suppose after Embedding Layer + Positional Encoding a token's vector is exactly (the zero vector — all entries ). Compute its for any . Then, in a 2-token sequence where token 2 is this zero token, what is its raw score against any query, and does it still receive attention weight?

Recall Solution

, and likewise , . A zero row in maps to a zero row out (linear maps send ). Raw score of any query against this key: . A score of is not , so after softmax the zero token still gets nonzero weight ( in the numerator). But its value is , so it contributes nothing to the weighted sum — it dilutes but does not corrupt. (True masking uses scores, not zero inputs — a different mechanism.)

Exercise 5.3 — Limiting behaviour of the scale factor

Assume the entries of and are independent random numbers, each with mean and variance (a standard initialisation assumption), and that 's entries are independent of 's. The raw dot product is . Show its variance is , so typical magnitude , and explain why dividing by keeps the scaled score's magnitude roughly constant — and what softmax does without it.

Recall Solution

Why each term has mean and variance : since and are independent with mean , And for independent zero-mean variables, So each product term has mean , variance . Sum of independent such terms: variances of independent variables add, so giving standard deviation . Dividing by : So the scaled score has spread regardless of . Without the scale, scores grow like ; feeding huge values into softmax makes one weight and the rest — a near one-hot, almost flat gradient. Scaling keeps softmax in a responsive, learnable regime.


Recall Self-check summary

What makes attention directional (asymmetric)? ::: Separate and , so in general. Why divide scores by ? ::: To keep scaled-score variance so softmax stays responsive and gradients don't vanish. Can differ from ? ::: Yes — keys are used only inside (both length ), while values build the output separately, so the output has length , which may differ. Does multi-head cost extra parameters vs one full head? ::: No — same total, split into subspaces each of size . What does a zero input token contribute to attention output? ::: Nothing (), though it still receives nonzero softmax weight.