Transformer

A small decoder-only Transformer trained in your browser on copy, reverse, sort and addition: every block, the residual stream, attention maps, and sampling with temperature and top-k/p.

Updated

  • Tokens, embeddings and position encodings
  • Pre-LN blocks: LayerNorm, attention, feed-forward, residuals
  • Next-token prediction and the causal mask
  • Training on algorithmic tasks
  • Sampling: temperature, top-k, top-p
LayerNormMulti-head attentionLayerNormFeed-forward · GELU++residual× L3718>3718>83718>83718>813718>813718>8173718>8173718>81733718>8173P(next | prefix)
Preparing the lab…

Intuition

One token at a time

Show the model "3718>" and let it continue. It first predicts the most likely character after ">", writes "8"; then looks at "3718>8" and writes "1"… until it is done. Every step is the same question: given what came before, what is the next token? Large language models do exactly this, with much larger vocabularies, data and models.

The three small labs below really train this model on "reverse" in your browser. Each row is an evaluation sample: the prompt in black, followed by the model's answer (green right, red wrong). For speed, each answer position here takes the most likely token given the correct prefix; getting them all right is equivalent to greedy generation from the prompt being entirely right.

Random weightsPreparing…
25 training stepsPreparing…
50 training stepsPreparing…

With random weights 5.6% of the answer tokens are right. At 25 steps 68.2% of the answer tokens are right, but only 14.8% of the 4-token answers are entirely right — one wrong token spoils the whole answer. After 50 steps all 256 evaluation samples are answered correctly.

Math

What happens inside a block

The TT input tokens become a T×DT\times D matrix xx (token embedding + position encoding), which then passes through LL blocks (Pre-LN):

x←x+Attn(LN1(x)),x←x+W2 GELU(W1 LN2(x)+b1)+b2x \leftarrow x + \mathrm{Attn}(\mathrm{LN}_1(x)),\qquad x \leftarrow x + W_2\,\mathrm{GELU}(W_1\,\mathrm{LN}_2(x) + b_1) + b_2
  • attention moves information between positions (multi-head with a causal mask — see self-attention);
  • the feed-forward network applies a non-linear transformation at each position separately, with a hidden layer of width 4D4D;
  • residual connections let each block learn only "how much to change", and let gradients flow straight back;
  • layer normalisation rescales each position's vector to mean 0 and variance 1 before scaling, keeping training stable.

After the final LNf\mathrm{LN}_f an output matrix gives each position's logits, and softmax gives the next-token probabilities. This page computes cross-entropy only on the "answer": the prompt is random, so there is nothing to learn there.

Reverse: the 4 heads of layer 2Preparing…
Copy: the 4 heads of layer 2Preparing…
Sort, 100 stepsPreparing…

The first two show the attention matrix of each head in layer 2 (rows are positions, columns the positions looked at, the upper-right triangle hidden by the causal mask). After the same 50 steps, both fully correct, copying and reversing need the answer positions to fetch different prompt positions, and the attention patterns learned differ. The third is sorting: 81.6% of answers entirely right at 100 steps, 98.8% at 500.

Where position comes from

Attention by itself has no sense of order. There are three common ways to add position:

Position encodingHowReverse 4 digits: whole-answer accuracy at 50 steps
Learned (default)A trainable vector per position, added to the embedding100%
SinusoidalFixed sin⁡\sin and cos⁡\cos waves of different frequencies per dimension96.9%
RoPENot added to the embedding: rotates qq and kk by position, so dot products depend only on relative distance8.2% (95.3% at 250 steps)

RoPE is what most large models use today, yet on this small task it starts much more slowly. One possible explanation: reversing requires knowing "which answer position am I", an absolute position, while RoPE directly gives only relative distances, so the model must first learn to infer it using ">" as a reference. (That is an explanation, not a conclusion this page has verified.)

Task difficulty

TaskExampleWhole answer right
Copy3718>3718100% at 50 steps
Reverse3718>8173100% at 50 steps
Sort3718>137881.6% at 100 steps, 98.8% at 500
Addition1234+5678=219600 at 500 steps, 31.6% at 750, 100% at 1000

The sum is written backwards (units digit first) so that carries can flow from front to back: 1234 + 5678 = 6912, written as 5 reversed digits, is 21960. Its training curve is interesting: at 250 and 500 steps only about 30% of answer tokens are right (28.75%, 31.6%), as if stuck; then within a few hundred steps it suddenly learns.

Generation: temperature, top-k, top-p

Once the model gives next-token probabilities, how to choose:

  • temperature 0: take the most likely (greedy) — deterministic;
  • temperature τ\tau: use softmax(z/τ)\mathrm{softmax}(z/\tau); larger τ\tau is more random;
  • top-k: sample only among the kk most likely;
  • top-p: sample only among the fewest tokens whose cumulative probability reaches pp.

What is cut is renormalised and then sampled with the seed, so the same settings and seed always write exactly the same thing. The lab's "Generate" tab lets you adjust each of these.

How it is computed, with real numbers

Once the lab above has loaded, this panel works through the same formulas with its current numbers.

Experiment

Follow the lesson

Course

Lesson 1: a small model that writes

5 steps · each one: set up and run → look → answer

  1. 1. Tokens and whole answers

    The default reverse task, 25 training steps. Look at the two accuracies on the right.

    68.2% of answer tokens are right, but only 14.8% of whole answers. Why the big gap?
  2. 2. Look at the attention

    Train to 50 steps, open "Attention maps" and hover a row of the answer.

    Why is the upper-right triangle empty?
  3. 3. Another position encoding

    Set the position encoding to RoPE and train 250 steps.

    Learned positions are fully right at 50 steps; RoPE gets 95.3% of whole answers at 250. What can you conclude?
  4. 4. Sorting

    Switch the task to sorting and train 500 steps.

    What makes sorting harder than reversing?
  5. 5. Addition

    Switch to addition and train 1000 steps (it takes a while). Watch the curve on the right.

    For the first 500 steps accuracy sits around 30%, then after 750 it jumps to 100%. What does that tell you?

Try these settings

The lab has three more tabs: "Generate" lets you type your own prompt and adjust temperature and top-k / top-p; "Tokenization" trains a BPE tokenizer live on this site's own articles; "Pretrained: Tang poems" loads a character-level Transformer trained offline with PyTorch on the Complete Tang Poems and writes poetry in your browser.

Exercises

Exercises

Exercise 1: switch back to a suitable position encoding

With RoPE only 8.2% of whole answers are right after 50 steps on the reverse task. Change the settings to get at least 99% within 50 steps.

Hint

Set the position encoding to "Learned": 100% at 50 steps. Sinusoidal gives 96.9%, just short.

  • Whole answer ≥ 99.0%
  • at most 50 steps

Exercise 2: learn addition

4-digit addition. Train until at least 99% of whole answers are right.

Hint

The defaults reach 100% at 1000 steps. There is a plateau along the way; be patient.

  • Whole answer ≥ 99.0%

Quiz

What is the training objective of GPT-style models?
What is the residual connection x ← x + f(x) for?
With temperature 0, generation…

Further reading

Frequently asked questions

What is a Transformer?

A neural network architecture built around self-attention (Vaswani et al., 2017). It stacks identical blocks, each with multi-head self-attention and a feed-forward network, wrapped in residual connections and layer normalisation. GPT, BERT and most modern large language models are built on it.

What is the difference between an encoder and a decoder?

An encoder's attention can see the whole sentence (bidirectional) and suits understanding tasks (BERT, for example); a decoder uses a causal mask and sees only what came before, which suits generation (GPT, for example). The original Transformer had both, for translation. This page has a decoder-only model.

Why are position encodings needed?

Attention looks only at content and has no sense of order; shuffle the input and the results simply move with it. Position encodings add "which position": learned vectors, fixed sine waves, or rotating queries and keys as RoPE does.

What are temperature, top-k and top-p?

Ways of choosing the next word during generation. Temperature scales the logits, with higher meaning more random; top-k picks only among the k most likely; top-p picks only among the fewest tokens whose cumulative probability reaches p. Temperature 0 always takes the most likely (greedy).

How do large language models differ from the model on this page?

The architecture is essentially the same; the difference is scale. This page has 2 layers, width 32, about 27 thousand parameters and 13 tokens; large models have tens to over a hundred layers, widths in the thousands, billions to trillions of parameters and vocabularies of tens of thousands, trained on vast amounts of text and then instruction-tuned and aligned.

Further reading