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
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.
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 input tokens become a matrix (token embedding + position encoding), which then passes through blocks (Pre-LN):
- 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 ;
- 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 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.
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 encoding | How | Reverse 4 digits: whole-answer accuracy at 50 steps |
|---|---|---|
| Learned (default) | A trainable vector per position, added to the embedding | 100% |
| Sinusoidal | Fixed and waves of different frequencies per dimension | 96.9% |
| RoPE | Not added to the embedding: rotates and by position, so dot products depend only on relative distance | 8.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
| Task | Example | Whole answer right |
|---|---|---|
| Copy | 3718>3718 | 100% at 50 steps |
| Reverse | 3718>8173 | 100% at 50 steps |
| Sort | 3718>1378 | 81.6% at 100 steps, 98.8% at 500 |
| Addition | 1234+5678=21960 | 0 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 : use ; larger is more random;
- top-k: sample only among the most likely;
- top-p: sample only among the fewest tokens whose cumulative probability reaches .
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. Tokens and whole answers
The default reverse task, 25 training steps. Look at the two accuracies on the right.
2. Look at the attention
Train to 50 steps, open "Attention maps" and hover a row of the answer.
3. Another position encoding
Set the position encoding to RoPE and train 250 steps.
4. Sorting
Switch the task to sorting and train 500 steps.
5. Addition
Switch to addition and train 1000 steps (it takes a while). Watch the curve on the right.
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
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
- Vaswani et al., Attention Is All You Need, 2017: the original Transformer paper.
- Radford et al., Improving Language Understanding by Generative Pre-Training, 2018: GPT.
- Xiong et al., On Layer Normalization in the Transformer Architecture, 2020: the Pre-LN structure.
- Su et al., RoFormer: Enhanced Transformer with Rotary Position Embedding, 2021: RoPE.
- Hendrycks, Gimpel, Gaussian Error Linear Units (GELUs), 2016.
- Holtzman et al., The Curious Case of Neural Text Degeneration, 2019: top-p sampling.
- Sennrich, Haddow, Birch, Neural Machine Translation of Rare Words with Subword Units, 2016: BPE tokenization.