1def attend(q, K, V):2 d_k = len(q)3 s = [dot(q, k) for k in K]4 s = [x / sqrt(d_k) for x in s]5 e = [exp(x) for x in s]6 w = [x / sum(e) for x in e]7 return mix(w, V)× 6 blocksfeed-forwardnext?the1 0cat0 1sat1 1W_QW_KW_Vthecatsatthecatsatpositionquery of satthecatsatnew sat
Rows of cells: embeddings, keys, scores, values (one column per token)Left: weights W_Q, W_K, W_V · right: the query of sat and its new vectorSmall tiles: vectors on the moveOne column per token of "the cat sat". Each embedding goes through three learned weight matrices and becomes a key, a value and (for "sat") a query. The query is compared with every key (a dot product), the scores are scaled by √d_k and turned into weights by softmax, and the values are mixed by those weights into a new vector for "sat". At the back, the tower is one transformer block: attention heads side by side, then a feed-forward network; the original model stacks six. 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).

Query, key, value

  1. 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.

Attention weights

The transformer

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.