4.1.3 · D2Transformer Architecture

Visual walkthrough — Query, key, value matrices

3,206 words15 min readBack to topic

Before we touch attention, we must earn every symbol. Let's begin from the very first thing a transformer sees.


Step 1 — A token is a row of numbers

WHAT. After the tokenizer splits the text, an embedding layer turns each token (say the token "cat") into a fixed list of numbers, e.g. four of them:

Here is called an embedding vector. The little "vector" just means an ordered list of numbers. Each number is one coordinate — think of it as one dial the model can read. Four numbers means four dials, so we say this vector lives in a 4-dimensional space, written . The general size is ("model dimension"); here .

WHY. Computers cannot multiply the letters c-a-t. They can only multiply numbers. So the first job is to represent meaning as numbers. Everything downstream is arithmetic on this row.

PICTURE. Below, the four numbers of are drawn as four colored bars. Tall bar = big number, bar below the line = negative number. This bar-strip is our mental image of "one token."

Figure — Query, key, value matrices

Step 2 — Multiplying a vector by a matrix = mixing the dials

WHAT. A matrix is just a rectangular grid of numbers. When we write , we take our row and a grid , and produce a new, shorter row . Each output number is a weighted sum of the input numbers:

Read this term by term: to make output column , walk down column of the grid, multiply each grid entry by the matching input dial , and add them all up.

WHY this tool and not another? We need a way to re-mix the dials — to build brand-new features like "is this a verb?" out of the raw meaning dials. A linear transformation (matrix multiply) is the simplest such re-mixer: it can amplify, suppress, flip the sign of, and blend any dials. It is exactly what a linear layer does. We choose it because it is (a) flexible enough to build any weighted combination and (b) simple enough to train with backpropagation.

PICTURE. Each output cell is fed by arrows from every input bar; the arrow's number is the grid entry it passes through. One output cell = one full column of the grid consumed.

Figure — Query, key, value matrices

Step 3 — The Query: "what am I looking for?"

WHAT. Multiply the token by a special grid (shape ) to get a query vector:

The output has only 2 numbers because we chose . So lives in a smaller 2-dimensional "search space" — small enough to draw as a real arrow on a page.

Term by term:

WHY. The raw dials of are a hopeless mush of meaning, position, and grammar all together. The query grid is a learned lens that pulls out only "what kind of context this token wants." We give the search its own space so it can be optimized just for matching, independent of meaning.

PICTURE. The 4-bar strip on the left funnels through the grid and lands as one 2D arrow on a plane. That arrow is the token's search intent.

Figure — Query, key, value matrices

Step 4 — The Key: "what do I advertise?"

WHAT. Take the same token but a different grid to get the key vector : With the numbers from the parent note:

WHY a different grid from the query? Because searching and being-found are different jobs. My query says "I want a verb." My key says "I am a noun, subject-ish." If we forced , every token could only ever match tokens like itself — attention could never be asymmetric (cat→sat ≠ sat→cat). Two grids buy us direction.

PICTURE. The same 4-bar strip now flows through a second, different grid and lands as a different arrow on the same plane. One token → two arrows.

Figure — Query, key, value matrices

Step 5 — The dot product turns two arrows into one relevance number

WHAT. To score "how relevant is token to token " we compute the dot product of the query of with the key of : For our single token attending to itself:

WHY the dot product and not something else? We need a single number saying "how aligned are these two arrows." The dot product is exactly that: it is large-positive when the arrows point the same way, zero when they are perpendicular, and negative when they point opposite.

First, the length symbol . For any arrow , its length (how far its tip reaches from the origin) is written and computed by the Pythagorean rule: The two vertical bars just mean "size of this arrow, ignoring its direction" — always a non-negative number. So and below are simply the reaches of the two arrows.

What is ? Draw both arrows starting from the same point (the origin). The ==angle == is simply the opening between them, measured from to if they lie on top of each other, if they form a right angle, if they point dead opposite. The dot product packages the two lengths together with this angle into one formula: Here (cosine) is the "agreement dial": (full agreement), (none), (full disagreement). So the more two search-and-offer arrows agree in direction, the higher the relevance. No other simple operation reads "agreement of direction" so cleanly. This is the core of Scaled Dot-Product Attention and drives Self-Attention.

PICTURE. and drawn tail-to-tail from the origin; the angle between them is shaded in mint, and the resulting score sits on a little "relevance meter" that swings positive/zero/negative.

Figure — Query, key, value matrices

Step 6 — Why we divide by before softmax

WHAT. We don't feed the raw score into the next stage. We scale it:

WHY. A dot product adds up product-terms. If we double the number of dimensions, the sum tends to grow (roughly like ). Huge scores make the next step — softmax — saturate: it puts almost all weight on one token and nearly zero gradient everywhere else, so learning stalls. Dividing by cancels that growth and keeps scores in a gentle range where gradients still flow.

PICTURE. Two bar charts of scores — "unscaled" (tall, spiky) vs "scaled" (calm) — with a softmax curve behind showing the flat, dead zones the tall bars fall into.

Figure — Query, key, value matrices

Step 7 — Softmax: turning scores into listening-percentages

WHAT. For a query, we now have one scaled score against every token in the sentence: a row . The softmax function turns this row of raw numbers into a row of weights that are all positive and sum to 1 — a set of percentages saying "how much of my attention goes to each token":

Term by term: ( raised to the score) makes every entry positive and blows up big scores more than small ones; the denominator adds up all those positives so that dividing by it forces the whole row to sum to 1. Bigger score in → bigger slice out.

WHY this tool? We need to convert "raw relevance" into a proper weighting — non-negative and totalling 100% — so we can take a weighted average of information. Softmax is the smooth, differentiable way to do that (differentiable matters for backprop).

PICTURE. Three scaled scores enter; softmax bends them into three slices of a pie that sum to 1.

Figure — Query, key, value matrices

Step 8 — The Value: "what information do I actually hand over?"

WHAT. A third grid (shape , so ) turns the token into a value vector — the payload:

WHY a third grid, and why size 3? What made a token relevant (its key) is not the same as what it should contribute (its value). "sat" is relevant to "cat" because of a subject–verb link (a key/query fact), but the information passed on is "cat = animal, subject" (a value fact). Separating them lets the model match on one thing and deliver another. The value space may need a different width, so need not equal .

PICTURE. The same 4-bar strip forks a third time through into a 3-bar payload , drawn as a little parcel labelled "info to send."

Figure — Query, key, value matrices

Step 9 — Stacking into matrices (the full sequence)

WHAT. A sentence is many rows stacked: , one row per token ( = sentence length). The same three grids act on the whole stack at once: Row of is token 's query; row of is token 's key; row of is its value.

The transpose symbol . Writing (read "K transpose") means flip the grid across its diagonal: every row becomes a column and every column becomes a row. So if has shape (tokens down, key-features across), then has shape (key-features down, tokens across). Why do this? To multiply two grids, the across-count of the left grid must equal the down-count of the right grid. is ; to pair its queries against the keys we need something on the right — exactly . The product is then , and its entry in row , column is precisely the dot product of query with key — every query-meets-key score computed in one shot:

Which axis does softmax run along? The subscript "row" is essential: softmax is applied across each row of the score grid — i.e. for a fixed query , over all keys . That way each query's weights sum to 1 independently. Running it down columns instead would be a classic implementation bug (in code: softmax(dim=-1)).

WHY matrices? Doing every token's projection and every pair's score as one big multiply is exactly what GPUs are fast at. Same recipe, applied to a whole page instead of one token. This packing is what Multi-Head Attention then repeats in parallel, and the identical machinery serves Cross-Attention (queries from one sequence, keys/values from another).

PICTURE. Input grid ( rows) fanning into three output grids , , , each row color-matched back to its source token.

Figure — Query, key, value matrices

The one-picture summary

Here is the whole derivation compressed into a single diagram. Read it left to right:

  • Far left, the butter circle labelled is one token's embedding — the four dials of Steps 1–2.
  • Three colored arrows fan out from , one per learned grid. The lavender arrow carries through into the query ("what I want", Step 3); the coral arrow through into the key ("what I offer", Step 4); the mint arrow through into the value ("info I'll hand over", Step 8). One token, three roles — the central lesson.
  • Top middle, "dot → relevance": the and circles both feed the dot-product node, producing one relevance number (Step 5), scaled by (Step 6).
  • Right of that, "softmax → weights (sum 1)": relevance numbers become attention percentages that add to 1 (Step 7).
  • Bottom right, "weighted = OUTPUT": those weights multiply the value and sum up into the token's new, context-aware vector (the of Step 8).

Trace any path and you have re-derived attention: want and offer meet to make relevance, relevance becomes weights, weights pull in values.

Figure — Query, key, value matrices
Recall Feynman retelling — say it back in plain words

Imagine every token in a sentence is a person in a room (a "token" is a small chunk of text — sometimes a whole word like cat, sometimes just a word-piece like un or ness). Each person makes three cards from their own single ID:

  • a want-card (query): "I'm looking for a verb."
  • an offer-card (key): "I'm a noun, I'm the subject."
  • an info-card (value): the actual gossip they'll share.

To decide who listens to whom, everyone holds up their want-card next to everyone else's offer-card and checks how well the arrows line up — that lining-up is the dot product, and a bigger overlap means "more relevant." We shrink those overlap numbers a bit (divide by ) so nobody shouts over everyone else and the learning doesn't freeze. Then softmax turns each person's overlaps into listening percentages that add up to 100%. Finally each person collects everyone's info-cards, weighted by those percentages, and blends them into a new, context-aware understanding of themselves. Three cards from one ID — because what you want, how you're found, and what you say are three different jobs.

Recall Quick checks

What is the difference between a "word" and a "token"? ::: A tokenizer chops text into tokens, which are often sub-word pieces; a common word may be one token, a rare word several. The model embeds and attends over tokens, not raw words. Why three separate matrices and not one? ::: Wanting, being-matched, and contributing information are different jobs; separate learned grids let attention be asymmetric and let the model match on one feature while delivering another. What does mean? ::: The length (magnitude) of the arrow , computed as — a non-negative number ignoring direction. What does the dot product of and measure? ::: Directional agreement of the two arrows via — big positive when aligned, zero when perpendicular, negative when opposed. What does the transpose do and why is it needed? ::: It flips so rows become columns (), making the shapes line up so gives every query-key dot product at once. Why divide by ? ::: Dot products grow with dimension; scaling keeps them in a range where softmax doesn't saturate and gradients keep flowing. Along which axis is softmax applied in ? ::: Along each row (over all keys for a fixed query), so every query's weights sum to 1. If , what is the score against any key? ::: Zero — a token with no search intent matches nothing.