Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Everything looks at everything
Recurrent networks read a sentence word by word. The Transformer looks at all words at once:
- every word asks “which other words matter to me?” (attention) and gathers information from them;
- a small network then processes each word on its own;
- stacking a few such layers builds rich understanding;
- since no step waits for the previous one, it trains fast on parallel hardware.
The demo shows the core calculation, scaled dot-product attention, and why its scaling matters.
Transformers now power language models, translation, speech, vision and robot policies. Understanding the original design explains most of their behaviour and cost.
- 1. The Transformer replaces recurrence with…
- 2. It trains fast because…
- 3. Any two positions are connected in…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
Encoder layer:
- x ← LayerNorm(x + MultiHeadSelfAttention(x));
- x ← LayerNorm(x + FFN(x)), with FFN(x) = max(0, xW₁ + b₁)W₂ + b₂.
Decoder layer:
- masked self-attention (no looking ahead);
- cross-attention to the encoder output;
- the FFN, each with a residual connection and LayerNorm.
Base model: N = 6 layers each side, d = 512, d_ff = 2048, h = 8 heads, dropout 0.1.
Parameters:
- an encoder layer has 4(d² + d) + (2·d·d_ff + d_ff + d) + 4d = 3,152,384;
- a decoder layer has 4,204,032;
- with a shared 37,000-token embedding, the total is 63.1 M by this count (the paper reports 65 M);
- the big model has d = 1024, d_ff = 4096, h = 16 (213 M).
Training recipe:
- Adam with β₂ = 0.98, and lr = d⁻⁰·⁵ · min(step⁻⁰·⁵, step·warmup⁻¹·⁵) with warmup = 4000, which peaks at 7.0 × 10⁻⁴;
- label smoothing ε = 0.1: the correct class gets 0.925 of 4 classes’ mass, the others 0.025 each.
Cost per layer:
- self-attention takes about 2n²d multiply–adds against n·d² for a recurrent layer, so attention is cheaper when n < d;
- the maximum path length is 1 (attention), n − 1 (recurrent), or ⌈log_k n⌉ (dilated convolutions).
- 1. Base model width d:
- 2. Peak learning rate of the schedule (warmup 4000):
- 3. Self-attention is cheaper than recurrence when…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.The Transformer in code
Exercise 1.
- The layer counts gave 3,152,384 (encoder) and 4,204,032 (decoder), 63,082,496 in total with the shared embedding.
- The learning rate rose linearly to 6.99 × 10⁻⁴ at step 4000, then decayed as step⁻⁰·⁵.
Practice.
- PyTorch’s
nn.Transformer(d_model=512, nhead=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=2048)implements the architecture. Usenorm_first=Truefor pre-LN, which trains more stably for deep stacks. - Masks:
- a causal mask on decoder self-attention;
- key-padding masks for padded tokens.
- Embeddings are multiplied by √d and shared between input and output in the paper.
- The original used post-LN (normalise after adding the residual) and needed warmup. Most later models use pre-LN.
model = nn.Transformer(d_model=512, nhead=8, num_encoder_layers=6, num_decoder_layers=6,
dim_feedforward=2048, dropout=0.1, batch_first=True)
tgt_mask = model.generate_square_subsequent_mask(T)
out = model(src_emb, tgt_emb, tgt_mask=tgt_mask, src_key_padding_mask=src_pad)- 1. PyTorch option for pre-LN layers:
- 2. Decoder self-attention uses…
- 3. The original Transformer normalised…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
What the pieces do.
- Attention mixes information across positions; the FFN transforms each position independently (most of the parameters).
- Residual connections keep a direct path for gradients and information.
- LayerNorm keeps activations at a stable scale.
- Positional encodings give the otherwise order-blind attention a sense of position (E12-3).
Parallelism and path length.
- Within a layer, all n positions are computed at once in training, against n sequential steps for an RNN.
- Every pair of positions interacts directly, so long-range dependencies do not have to survive many steps. This was the paper’s central argument (its Table 1).
- The price is n² memory and compute per layer, which limits context length and motivated E12-15 onward.
Training stability.
- Post-LN Transformers have large gradients near the output at initialisation, so they need learning-rate warmup.
- Pre-LN puts normalisation inside the residual branch, keeping gradients well scaled, and often trains without warmup (Xiong et al., 2020).
- 1. Most Transformer parameters are in…
- 2. Attention's cost grows with length as…
- 3. Post-LN Transformers need…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.How quickly does attention learn to reverse?
History.
- A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. Gomez, Ł. Kaiser and I. Polosukhin published “Attention is all you need” (NeurIPS 2017).
- The big model reached 28.4 BLEU on WMT’14 English→German and 41.8 on English→French, training in 3.5 days on 8 GPUs.
- Its encoder became BERT (E12-4), its decoder GPT (E12-10) and its encoder on image patches ViT (E12-22).
Exercise 2.
- Model: one pre-LN Transformer layer (1 head, d = 32, FFN 64) written in NumPy with hand-derived gradients (checked numerically).
- Task: read a random sequence over 6 symbols and output it reversed at the same positions.
- Training: 300 Adam steps, 2 seeds, with learned or sinusoidal positional encodings.
| positions | length 12 | length 24 |
|---|---|---|
| learned | 1.000, 1.000 | 0.512, 0.729 |
| sinusoidal | 1.000, 1.000 | 1.000, 1.000 |
| The code runs seed 0 only, to stay fast in the browser; the second value in each cell is seed 1 from a native run. |
- One attention layer reverses 12 tokens perfectly in 300 steps. In E11-9 an RNN encoder–decoder without attention reached 0.229 at length 12. The setups differ (encoder-only here), but the point stands: each output reads its source directly.
- At length 24, the positional encoding decides the speed. Learned position vectors must each be learned from scratch, and reached only 0.51–0.73 in 300 steps; they reached 1.0 on both seeds in 1000 steps. Fixed sinusoids give structured positions from the start and solve it in 300.
- Without any positional encoding the layer cannot reverse at all: about 0.33 at length 12 (chance 0.17). Attention alone cannot tell positions apart (E12-3).
Transformers in AI, robotics and aerospace
- Foundation models: language and vision–language models used for planning and operator assistance are Transformers.
- Robot policies: decision transformers and vision–language–action models output robot actions from tokenised observations.
- Time series and telemetry: Transformer forecasters handle long sensor histories, with efficient attention for long windows.
References
- A. Vaswani et al. (2017). “Attention is all you need.” Proc. NeurIPS.
- R. Xiong et al. (2020). “On layer normalization in the Transformer architecture.” Proc. ICML.
- D. Bahdanau, K. Cho, Y. Bengio (2015). “Neural machine translation by jointly learning to align and translate.” Proc. ICLR.