Query, key, value
A transformer reads text as tokens, here "the cat sat". Each token starts as an embedding: a list of numbers for its meaning. Ours have 2 numbers. Alone, each vector ignores its neighbours: "sat" does not know who sat.
Three learned weight matrices turn every embedding into three new vectors: a query (what am I looking for?), a key (what do I offer?) and a value (what do I pass on?). The query of "sat" is [−1, 1].
Attention weights
Attention compares the query of "sat" with every key using a dot product: multiply matching numbers, then add. For "cat": [−1, 1] · [0, 2] = 2. The scores are the −1, cat 2, sat 1. Bigger means a better match.
Each score is divided by √d_k, the square root of the key length. Here d_k = 2, so we divide by 1.41: −0.71, 1.41, 0.71. With long vectors, unscaled scores grow huge and learning slows down.
Softmax turns the scores into weights: raise e to the power of each score, then divide each by their sum. The weights are positive and add up to 1: the 0.07, cat 0.62, sat 0.31. So "sat" attends mostly to "cat".
The new vector for "sat" is the weighted sum of the values: 0.07×[0, 1] + 0.62×[1, 0] + 0.31×[1, 1] = [0.93, 0.38]. It now carries information from "cat". That is self-attention.
The transformer
Every token does the same with its own query, all at the same time. Written with matrices it is one formula: softmax(QKᵀ / √d_k) V. No token waits for the one before it, so the work runs in parallel on the hardware.
One attention finds one kind of match. The original transformer runs 8 attention heads side by side, each with its own weights and vectors of 64 numbers instead of 512. Their outputs are joined and mixed back into one vector per token.
A block is attention followed by a small feed-forward network applied to each token. Each part adds its result to its input (a residual connection) and then normalises. The original stacks 6 blocks; GPT-3 stacks 96.
Attention alone ignores word order: shuffle the words and each one gets the same mix as before. So a position signal is added to every embedding first. The original transformer used sine and cosine waves of different lengths.
A language model such as GPT stacks only these blocks, with a mask so each token sees only earlier ones. The last vector becomes a probability for every token in the vocabulary. A likely one, "on", is added, and it repeats.
What happens
;; step 1/11 · tokens token embedding the [1, 0] cat [0, 1] sat [1, 1] each vector was made for the word alone, without looking at the other words
The numbers are a toy: 2 numbers per token and hand-picked weight matrices. Real models learn their weights by gradient descent and use hundreds or thousands of numbers per token (512 in the original transformer). Weights are shown to 2 decimals (0.0743, 0.6200, 0.3057); the new vector is computed with the unrounded weights.