← zerosofzeta.com: more pages like this

a transformer, one token at a time

Forget the giant matrices for a minute. Here is a real, tiny transformer that learns while you watch. It reads one token, puts a key and a value into its memory, guesses the next token, and moves on. That's all it does, over and over. The code beside it is the same machine, line for line, so you can check one against the other.

–loss, all 6 sentences
0training steps
–learned numbers
the 6 training sentences
    German sentence to translate
    prompt: the model carries on from here
    1.0low: nearly always the top guess · high: wilder

    embed

    learned, or positiveloss and gradient, or negativehappening nowclick any blue plate to see all its numbers

    encoder

    Runs once per German sentence. Every word attends to every word, later ones too: nothing on this side is being predicted.
    What comes out: a vector e for each German word.

    token tape

    stream xEach station reads x, works on it, and adds what it found back onto x. You're seeing this one token's x.
    wte + wpe

    embed

    +
    x + attention

    self-attention

    q, k and v all come from this sentence
    h = norm(x)
    →q
    →k
    →v
    memory
    a = Σ weight × v→
    →added to x
    x + cross-attention

    cross-attention

    q from this English token; k and v from the encoder's German
    h = norm(x)
    →q
    applied to each e from the encoder, once
    German memory: filled once, never grows
    a = Σ weight × v→
    →added to x
    x + MLP

    MLP

    this token alone: no looking at the others
    norm(x)→
    →ReLU→
    →added to x
    norm(x)

    read out

    a probability for every token in the vocabulary

    Every little square is one number: blue positive, red negative, pale near zero. Hover a strip, press “show numbers”, or click a plate to read them exactly. The tinted plates are the learned weights. Everything else is worked out fresh for each token and thrown away.

    the network being trained

    That's it. That's the whole network. Training changes these numbers and nothing else. Everything else you see in the machine (q, k, v, the memory, x, the attention weights, the probabilities) is worked out fresh for every token and thrown away after the sentence.

    norm and softmax have no learned numbers here. Real models give norm a learned gain and add bias vectors; I left those out so you can see the rest more clearly.

    How do Wq and Wk find out that they should look for the animal? Nobody tells them. In “the dog sits on the ___”, the loss on “rug” goes down whenever the second “the” pays attention to “dog”. So backprop nudges Wq and Wk toward a higher score for that pair, and nudges Wv and Wo toward passing along which animal it was. Do that a few hundred times and the pattern in the grids further down appears all by itself.

    Not every start works out. Some random starts get stuck near a loss of 0.43: attention never finds the animal, so the best the model can do is guess the place. Press “new random start” a few times and you'll meet one.

    attention is a lookup where every entry counts a little

    Think of a dictionary. You look up a word, find the entry whose key matches exactly, and read its value. Attention works the same way, except nothing has to match exactly. Every token has put a key and a value on the shelf. A new token comes along with a query and compares it with every key. The comparison is a dot product, which is big when two vectors point the same way. Softmax turns those scores into weights that add up to 1, and what comes back is a blend of all the values, with the best matches counting most.

    Why a blend and not a straight pick? Because a blend changes smoothly. Change Wq a tiny bit and the output changes a tiny bit, and that is exactly what gradient descent needs. A hard yes-or-no lookup gives it nothing to push on.

    self-attention and cross-attention

    The arithmetic is exactly the same. The only question is whose keys and values are sitting on the shelf.

    memory: k and v from each token so far k v k v k v k v not yet q <s> the dog sits ?
    Self-attention: “sits” scores its query against keys written by its own sentence, its own included. The shelf grows by one row per token, and a token that hasn't arrived yet can't be read.
    der Hund sitzt auf dem Teppich k v k v k v k v k v k v q <s> the dog ?
    Cross-attention: the query comes from the English token being written, but the keys and values come from the encoder's version of the German. That shelf is complete before the first English token, and it never changes.
    self-attentioncross-attention
    Query fromthe current tokenthe current token (decoder)
    Keys and values fromtokens of the same sequence, up to this onea different sequence: the encoder's output
    Memorygrows one row per tokenfilled once, fixed
    Sees later tokens?not in a decoder (they don't exist yet); yes in an encoderthe whole source, always
    Learned matricesWq Wk Wv WoCq Ck Cv Co
    Found inevery transformer; GPT-style models use only thisencoder–decoder models: translation, speech-to-text such as Whisper, image models that read a text prompt

    query, key and value in training and in inference

    traininginference
    Learned numbersused, then nudged after every sentenceused as they are: frozen
    Input tokensa real sentence from the datathe prompt, then the model's own samples
    At each positioncompare the guess with the true next token: that's the lossignore the guess while reading the prompt; after that, sample a token and feed it back
    qmade from x with Wq, used once, thrown awaythe same
    k and vmade with Wk and Wv and kept for the rest of the sentence; gradients flow back through them into Wk and Wvkept in the KV cache, so earlier tokens never need recomputing
    Memory lastsone sentenceone prompt and its continuation
    Backward passevery learned number gets a gradientnone
    Positions in parallel?possible: every next token is known ahead of timeno: each new token needs the one sampled before it

    Here's the thing to notice: the function in the middle, gpt(), is exactly the same in both tabs. Training wraps it in a loop that grades every guess and then adjusts the weights. Inference wraps it in a loop that feeds every guess back in as the next input.

    That's also why there's a key-value cache and no query cache. A token's query only matters at the moment the token is read. Its key and value get read by every token that comes after it.

    And in training, one sentence of 8 tokens is really 7 examples, one at each position. The loss is their average, so the model practises all seven at once.

    the same machine, the way a GPU computes it

    A GPU hates loops; it likes to do everything at once. So real code stacks every token's x into one matrix X and computes Q = X·Wq, K = X·Wk and V = X·Wv in three big multiplications. Then scores = Q·Kᵀ / √d gives the whole grid on the left in one shot. But now there's a problem: row 2 can see column 5, a token from the future. So the code adds a causal mask that sets everything above the diagonal to −∞ before the softmax.

    That's all the mask is: a patch that makes the fast version agree with this loop, where a key that hasn't been written yet simply can't be read. The numbers come out exactly the same. Cross-attention needs no mask at all, because the whole German sentence exists before the first English token.

    what full-size models add

    • Several heads. q, k and v are cut into pieces; GPT-2 small uses 12 heads of 64 numbers each. Each piece does its own attention, and the results are joined before Wo, so different heads can look for different things.
    • Many blocks. The attention and MLP pair repeats, 12 times in GPT-2 small. Each block has its own weights and its own key and value memory.
    • Bigger everything. GPT-2 small has vectors of 768 numbers, 50,257 word-piece tokens and about 124 million learned numbers. Same machine.
    • Batches. Many sentences go through at once, and their gradients are averaged. Same loss.