rumblr Work in progressWIP

● The AI Primer · Lesson 8 · Part 1: how a language model works

The transformer

The transformer block: the unit every modern LLM stacks

This lesson covers The block every language model stacks, and how to turn a config file into gigabytes

Members · open during launch 34 min12 figures and diagrams8 interactive

What this is

What is a transformer?

A transformer is the kind of neural network behind modern AI language models, built as a stack of identical blocks. In each block, the words of the input first exchange information (attention), then each word is worked on alone (a feed-forward step). Counting the numbers inside the blocks tells you how much memory a language model needs and how much work each word costs. A mixture of experts keeps several feed-forward steps in each block and runs only a few of them for each word, so it grows a language model without growing that work.

Why it matters: A language model's configuration is a handful of numbers: its width, its number of blocks, its vocabulary and its experts. Turning them into gigabytes and operations per word is how you size a GPU for it, or compare a dense 70B language model with an 8x7B mixture of experts.

At a glance

Key takeaways

  1. A block is attention, where tokens exchange information, then a feed-forward network, where each token is worked on alone. Each step reads a layer-normalized copy of the vectors and adds its result back (pre-norm, with a residual connection).
  2. A GPT looks up a vector for each token and its position, runs them through a stack of blocks, normalizes, and scores every vocabulary entry against the same embedding table it started from.
  3. Parameters ≈ 12·L·d² + vocab·d; compute ≈ 2N per generated token and 6ND to train. MoE adds experts to grow parameters without growing per-token compute.

How it works, from scratch

A language model holds one vector per token, a list of numbers, and passes those vectors through a stack of identical transformer blocks before it scores the next token (What happens when you send a prompt). Each block works like a team's meeting followed by desk work. The meeting is attention: each token takes in what the other tokens hold. The desk work is a feed-forward network, which works on each token alone. GPT-2 small stacks 12 blocks; big models stack 80 or more.

Chapter 1

The block: a meeting, then desk work

Neither step replaces a token's vector. Each one adds a correction to it, the residual connection from Training deep neural networks, so whatever the vector held is kept. Take one token whose vector is x = (1, 2). The meeting produces a correction (0.1, −0.3), and adding it gives (1.1, 1.7). Desk work then adds (−0.2, 0.4), giving (0.9, 2.1). The vector has been edited twice and never replaced.

Figure 1 · Diagram

Reading it: follow the main line down the left. The input is first normalized, put on a common scale, and fed to attention. The "Add" circle adds attention's output to the original input, which arrives by the side arrow that skips the step. The feed-forward network repeats the pattern. Those two side arrows are the residual connections, and they give the signal, and in training the gradient, a clear path through a hundred blocks. Putting the norm before each step is called pre-norm; it trains more stably than the 2017 original, which normalized after.

In symbols, the whole block is two lines:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the token vectors, one row per token (the "residual stream") (1, 2) for one token
"replace the left side with the right side", as in code: x = x + ...
layer normalization (section 2)
multi-head attention from Attention: the meeting returns (0.1, −0.3)
the feed-forward network (section 3): desk work returns (−0.2, 0.4)
add the correction to the vector, number by number

In words: "add what the meeting found to each token's notes, then add what each token worked out alone."

With the numbers: (1, 2) + (0.1, −0.3) = (1.1, 1.7); then (1.1, 1.7) + (−0.2, 0.4) = (0.9, 2.1).

In Python
x = [1.0, 2.0]
# what Attn(LN(x)) returned
attn = [0.1, -0.3]
# x ← x + Attn(LN(x))
x = [x_j + a_j for x_j, a_j in zip(x, attn)]
[round(x_j, 1) for x_j in x]  # → [1.1, 1.7]
# what FFN(LN(x)) returned
ffn = [-0.2, 0.4]
# x ← x + FFN(LN(x))
x = [x_j + f_j for x_j, f_j in zip(x, ffn)]
[round(x_j, 1) for x_j in x]  # → [0.9, 2.1]

New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.

In code: TransformerBlock runs these two lines, with one primer.ml.attention.MultiHeadAttention and one FeedForward. View source

A block gives back vectors of the same shape as the ones it was given, so the output of one block is a valid input to the next, and blocks stack. With both steps switched off, a block passes its input through unchanged.

Here is one token going through a block, as a vector of two numbers. Drag the two corrections, the meeting's and then the desk's, and watch where the token ends up.

Chapter 2

Layer normalization

Before each step, the block puts every token's numbers on a common scale. Layer normalization is the grading on a curve from Training deep neural networks, applied to one token at a time: subtract the average of the token's numbers from each of them, then divide by how spread out they are. However far a token's numbers have drifted, attention and the feed-forward network always read them at the same scale, through dozens of blocks.

Take the token (1, 2, 3, 4). Its mean (average) is 2.5. Its variance (the average squared distance from the mean) is (2.25 + 0.25 + 0.25 + 2.25) / 4 = 1.25, so its spread, the standard deviation (the variance's square root), is 1.118. The result is (−1.342, −0.447, 0.447, 1.342). Multiply the input by 100 and the result is identical.

Figure 2 · Diagram

Reading it: two fixed steps, then one learned step. Centring and dividing bring every token's numbers to average 0 and spread 1; the learned gain and bias then let the model give each feature the scale it needs. RMSNorm (used by Llama and most recent models) skips the centring box and divides by the root-mean-square instead, which is cheaper and works as well.
The formula and its symbols

Symbols

Symbol Meaning here In the example
one token's vector (1, 2, 3, 4)
how many numbers it has 4
a counter over those numbers, 1 to
the -th number
"add up the following for = 1, 2, ..., "
(mu) the mean 2.5
(sigma squared) the variance 1.25
square root; is the spread 1.118
(epsilon) a tiny number (1e-5) so we never divide by zero 0.00001
(gamma, beta) learned gain and bias per feature 1 and 0 at the start

In words: "subtract the token's average from each of its numbers, divide by the token's spread, then rescale and shift each feature by learned amounts."

With the numbers: : (1 − 2.5) / √(1.25 + 0.00001) = −1.5 / 1.118 = −1.342, then × 1 + 0 = −1.342.

In Python
import math
x = [1, 2, 3, 4]
d = len(x)
# μ = (1/d) Σ x_j
mu = sum(x) / d
# σ² = (1/d) Σ (x_j − μ)²
sigma2 = sum((x_j - mu) ** 2 for x_j in x) / d
mu, sigma2  # → (2.5, 1.25)
# learned gain and bias start at 1 and 0
eps, gamma, beta = 1e-5, 1.0, 0.0
[round(gamma * (x_j - mu) / math.sqrt(sigma2 + eps) + beta, 3) for x_j in x]  # → [-1.342, -0.447, 0.447, 1.342]

In code: layer_norm and rms_norm are the two variants. View source

Because each token is normalized on its own, not across the batch like the BatchNorm used in image networks, the result is the same for any batch size and any sequence length.

Drag one token's four numbers, or multiply them all by one number, and watch where layer normalization puts them.

Chapter 3

The feed-forward network

After the meeting and a second layer norm, the token goes to its desk. The feed-forward network works on one token's vector at a time, with the same weights for every token, so it never mixes tokens: it works on what attention has already gathered into each one.

It first widens the vector with a matrix multiply: each output number is the dot product of the vector with one column of a weight matrix, so a matrix with 4d columns turns d numbers into 4d. Each of those numbers then passes through GELU, a smooth on/off switch, and a second matrix multiply narrows them back to d. Without the switch, the two matrix multiplies would collapse into one, and stacking them would add nothing. At model width 8, the token goes from 8 numbers to 32 and back to 8, through 8·32 + 32 + 32·8 + 8 = 552 parameters. On single numbers, GELU(1) = 0.841, GELU(10) = 10.0, GELU(−3) = −0.004 and GELU(0) = 0.

Figure 3 · Diagram

Reading it: one token's vector goes in on the left, alone, and its correction comes out on the right. The two weight matrices are where the parameters are: two thirds of each block's (8d² of every 12d²), and, with the embedding table counted too, 45% of GPT-2 small and 63% of GPT-2 XL. Much of a model's factual knowledge is thought to be stored in these weights.
The formula and its symbols

Symbols

Symbol Meaning here In the example
one token's vector 8 numbers
first weight matrix, widens 8 × 32
first bias, added after widening 32 numbers
second weight matrix, narrows 32 × 8
second bias 8 numbers
any single number fed to GELU 1
"hyperbolic tangent": an S-shaped curve from −1 to +1 = 0.664
pi, 3.14159...
"approximately equals": this tanh form is a fast stand-in for exact GELU

In words: "widen the token with a matrix multiply, softly switch off negative numbers, then narrow it back with another matrix multiply."

With the numbers: GELU(1) = ½ · 1 · (1 + tanh(0.798 · 1.045)) = ½ · (1 + tanh(0.834)) = ½ · (1 + 0.683) = 0.841.

In Python
import math
def gelu(z):
    return 0.5 * z * (1 + math.tanh(math.sqrt(2 / math.pi) * (z + 0.044715 * z ** 3)))
[round(gelu(z), 3) for z in (1, 10, -3, 0)]  # → [0.841, 10.0, -0.004, 0.0]
d = 8
# W1 (8 × 32), b1, W2 (32 × 8), b2
d * 4 * d + 4 * d + 4 * d * d + d  # → 552

Figure 4 · Chart

−4 −3 −2 −1 0 1 2 3 4 input to the activation 0 1 2 3 4 output GELU: a smooth ReLU ReLU: max(0, x) GELU

GELU tracks ReLU far from zero but bends smoothly through it and dips slightly below zero for small negatives

Reading it: the x-axis is the number going into the activation and the y-axis is what comes out. ReLU (grey) is a hard hinge: zero for every negative input, the identity for positives. GELU (blue) follows the same shape far from zero but bends smoothly around it and dips slightly below zero for small negatives. The smooth bend means the gradient never jumps, which is part of why transformers train well with it. Many newer models use SwiGLU, a gated variant of the same idea.

In code: FeedForward is the network and gelu the switch. View source

Slide a number along the GELU curve, then change the width and the widening, and watch the parameter count follow.

Chapter 4

A tiny GPT, end to end

That completes the block. A language model wraps a stack of blocks with two more pieces: a table lookup that turns token ids into vectors at the start, and a scoring step that turns the last vectors into a score for every token in the vocabulary at the end. Take a model with a 50-token vocabulary, width 32, 2 blocks and 16 positions. The ids [3, 1, 4, 1, 5] become a 5 × 32 grid, pass through both blocks as 5 × 32, and come out as a 5 × 50 grid of logits (raw scores): row 5 scores every possible 6th token. The model has 27,328 parameters.

Figure 5 · Diagram

Reading it: the top-left path says what each token is, the bottom-left path where it is (see Positional information); their sum enters the blocks. Every block keeps the 5 × 32 shape. At the end, each token's final vector takes a dot product with every row of the token table, which gives one score per vocabulary entry. The dotted line marks weight tying: the table that turned ids into vectors on the way in is reused to score them on the way out, which saves vocab × width parameters.

In symbols, the scoring step is one matrix multiply:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the vectors leaving the last block 5 × 32
after the final layer norm 5 × 32
the token embedding table, one row per vocabulary entry 50 × 32
transposed: rows become columns 32 × 50
logits score of every vocabulary entry at every position 5 × 50

In words: "score each candidate next token by how well its embedding lines up with the model's final vector."

With the numbers: row 5 of the logits holds 50 scores, one per token id; softmax turns them into next-token probabilities (see What happens when you send a prompt). Shrink the model to a width of 2 and a vocabulary of 3 to check by hand: a last position whose normalized vector is LN(h) = (1, −1), against table rows (1, 0), (0, 1) and (−1, 1), scores 1·1 + (−1)·0 = 1, then −1 and −2: token 0 lines up best.

In Python
# LN(h) for the last position
ln_h = [1.0, -1.0]
# one row per vocabulary entry
E = [[1.0, 0.0], [0.0, 1.0], [-1.0, 1.0]]
# LN(h) Eᵀ: a dot product with each row
[sum(h_k * e_k for h_k, e_k in zip(ln_h, row)) for row in E]  # → [1.0, -1.0, -2.0]

In code: TinyGPT runs this pipeline, and TinyGPT.n_params counts the 27,328 weights. View source

GPT-2 runs the same pipeline, with 12 blocks of width 768 in place of 2 blocks of width 32.

Set the model's sizes and watch the shapes follow, then score the last token by hand.

Chapter 5

Three families: encoder, decoder, encoder-decoder

The tiny GPT's blocks let each token look only at itself and the tokens before it, the causal mask from Attention. That makes it a decoder. Take the mask away, so that every token looks at every token, and the same blocks make an encoder. An encoder-decoder uses both: an encoder reads a source text, and a decoder writes the output while looking at the encoder's vectors as well as its own past. With 3 tokens, an encoder's attention may use all 9 (query, key) pairs and a decoder only the 6 on or below the diagonal. In a decoder block, then, changing a later token never changes an earlier token's output. In an encoder block, changing the last of five tokens changes the first token's output too.

Figure 6 · Diagram

Reading it: each box is one family, with models that use it and the jobs it does. Seeing everything suits understanding a text, and seeing only the past is what makes generation possible.
Type Example Attention Best for
Encoder-only BERT Bidirectional Classification, embeddings, NER
Decoder-only GPT, Claude, Llama Causal Generation, chat, agents
Encoder-decoder T5, original transformer Both Translation, summarization

Figure 7 · Chart

0 2 4 key (token looked at) 0 1 2 3 4 5 query (token looking) encoder (bidirectional) 0 2 4 key (token looked at) 0 1 2 3 4 5 query (token looking) decoder (causal) 0.0 0.2 0.4 0.6 0.8 1.0 attention weight

The encoder spreads attention over the whole grid; the decoder's upper-right triangle is empty, and only the last row matches

Reading it: both panels are attention weights from one block on the same 6 input vectors; rows are the token looking, columns the token looked at, darker is more weight. On the left (encoder) weight is spread over the whole grid. On the right (decoder) the upper-right triangle is empty, so nothing reads the future. Only the bottom row is identical in both panels: the last token sees everything either way, so the mask changes nothing for it. Every other decoder row differs, because its weights are shared out over only the tokens it may see: the first token, seeing only itself, puts all of its weight (1.0) there.

In code: one flag makes a TransformerBlock a decoder or an encoder block, and mask_patterns draws the figure. View source

Switch between the three families, and click a token to see which outputs it can reach.

Chapter 6

Counting parameters

Whatever its mask, a block holds the same weights, so a model's size follows from a few numbers in its configuration: the width, the number of blocks and the vocabulary. For width d, one block holds attention's 4·d² (W_q, W_k, W_v, W_o), the feed-forward network's 8·d² (two d × 4d matrices), and small bias and norm terms. With d = 32: 12 · 1,024 = 12,288, plus 160 (biases) plus 128 (norms) = 12,576 per block. Two blocks, plus tables of 50 × 32 and 16 × 32 and a final norm of 64, gives 27,328. The same recipe on GPT-2 small (d = 768, 12 blocks, 50,257 tokens, 1,024 positions) gives 124,402,944. GPT-2 also puts a bias on its attention projections, which the tiny model leaves out: 4·d = 3,072 more per block, 36,864 in all, and that brings it to exactly its published 124,439,808.

Figure 8 · Diagram

Reading it: almost all of a block's weight sits in two places, attention's four square matrices and the feed-forward network's two wide ones. Everything else is small at large width, which is where the 12·L·d² rule comes from. The embeddings are added once, not per block.
The formula and its symbols

Symbols

Symbol Meaning here GPT-2 small
total parameters 124,439,808
number of blocks (layers) 12
model width 768
times : the size of one square matrix 589,824
vocabulary size 50,257
the token embedding table 38,597,376

In words: "about twelve square matrices per layer, plus the embedding table."

With the numbers: 12 · 12 · 589,824 = 84,934,656, plus 38,597,376 = 123,532,032, about 0.7% under the exact 124,439,808 (which also counts positions, biases and norms).

In Python
L, d, V = 12, 768, 50_257
# 12·L·d² and V·d
blocks, table = 12 * L * d ** 2, V * d
print(f"{blocks:,} + {table:,} = {blocks + table:,}")  # → 84,934,656 + 38,597,376 = 123,532,032
# the share it leaves out
round((124_439_808 - (blocks + table)) / 124_439_808, 3)  # → 0.007

Figure 9 · Chart

small medium large XL GPT-2 size 0 200 400 600 800 1000 1200 1400 1600 parameters (millions) Where the parameters live 124M 355M 774M 1,558M embeddings attention feed-forward norms

Feed-forward is always the largest share; embeddings fall from 32% of GPT-2 small to 5% of XL

Reading it: each bar is one GPT-2 size, split by where the parameters live. Feed-forward (red) is always the largest block of the stack. In the small model, embeddings (grey) are almost a third of everything, because a 50k-row table is big next to 12 narrow layers. As models grow, the embeddings stay fixed while layers multiply, so their share shrinks to about 5% in XL, and the 12·L·d² term dominates.

Multiply the count by the bytes each parameter takes and you have the memory a model needs just to load (Inference does the arithmetic).

In code: gpt_param_count gives the exact count, and param_breakdown splits it for the figure. View source

Pick a GPT-2 size or set your own shape, and the bar shows where every parameter lives.

Chapter 7

Mixture of experts

The feed-forward network holds the largest share of every block. A mixture of experts (MoE) replaces it with several feed-forward networks, the experts, and a small router that scores each token against every expert. Only the k best-scoring experts run for that token. Take a router that scores one token against 4 experts as (2.0, 1.0, 0.5, −1.0). Keep the top 2 (experts 0 and 1) and take the softmax of just those two scores: e² / (e² + e¹) = 7.39 / 10.11 = 0.731, and 0.269. The token's output is 0.731 × expert 0's output + 0.269 × expert 1's output, and experts 2 and 3 never run for this token.

Figure 10 · Diagram

Reading it: the router is a tiny linear layer that scores the token against every expert. Only the two best-scoring experts run, and their outputs are blended by the renormalized scores (solid arrows); the others are skipped (dotted). Attention is unchanged; only the feed-forward network is replaced.
The formula and its symbols

Symbols

Symbol Meaning here In the example
one token's vector
the router's weights, width × number of experts
the router scores (2.0, 1.0, 0.5, −1.0)
the positions of the largest scores experts {0, 1} for k = 2
just those scores (2.0, 1.0)
expert 's gate: softmax over the kept scores 0.731, 0.269
expert (a feed-forward network) applied to
add up over the chosen experts only two terms

In words: "score every expert, keep the best k, and blend those experts' outputs by their softmaxed scores."

With the numbers: y = 0.731 · E₀(x) + 0.269 · E₁(x). With 8 experts of width 16, the layer holds 8 × 2,128 + 128 = 17,152 parameters, but one token touches only 2 × 2,128 + 128 = 4,384. Mixtral 8x7B works the same way: about 47B parameters in total, about 13B active per token.

In Python
import math
r, k = [2.0, 1.0, 0.5, -1.0], 2
# TopK(r)
top_k = sorted(range(len(r)), key=lambda i: r[i], reverse=True)[:k]
top_k  # → [0, 1]
exps = [math.exp(r[i]) for i in top_k]
# g: softmax over the kept scores only
[round(e / sum(exps), 3) for e in exps]  # → [0.731, 0.269]
d, n_experts = 16, 8
# one expert is one feed-forward network
expert = d * 4 * d + 4 * d + 4 * d * d + d
# W_r
router = d * n_experts
# one, all held, touched per token
expert, n_experts * expert + router, k * expert + router  # → (2128, 17152, 4384)

A router left alone sends more tokens to some experts than to others. Training therefore adds a small load-balancing loss (from the Switch Transformer) that is lowest when the traffic is even:

The formula and its symbols

Symbols

Symbol Meaning here Balanced example Collapsed example
number of experts 4 4
share of routing slots that went to expert ¼ each (1, 0, 0, 0)
expert 's average router probability ¼ each ≈ (1, 0, 0, 0)
the penalty added to the training loss 1.0 ≈ 4.0

In words: "number of experts times the sum, over experts, of traffic share times average router probability."

With the numbers: balanced: 4 · (4 · ¼ · ¼) = 1.0, the minimum. Collapsed onto one expert: 4 · (1 · 1) = 4.0, the maximum.

In Python
n = 4
def balance(f, P):
    # n Σ f_i P_i
    return n * sum(f_i * P_i for f_i, P_i in zip(f, P))
# every expert gets a quarter
balance([0.25] * n, [0.25] * n)  # → 1.0
# everything goes to expert 0
balance([1.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0])  # → 4.0

Figure 11 · Chart

0 1 2 3 4 5 6 7 expert 0 10 20 30 40 50 60 70 tokens routed to it (of 256, top-2) An untrained router plays favourites perfectly even (64 each)

An untrained router is lopsided: experts 3 and 5 get 75 tokens each, expert 2 only 51, against an even 64

Reading it: each bar counts how many of 256 tokens an untrained router sent to each of 8 experts (top-2, so 512 slots in all); the dashed line is the perfectly even 64. Experts 3 and 5 get 75 tokens each while expert 2 gets only 51: even random routing is lopsided, and in training the imbalance compounds because favoured experts improve and attract more traffic. The balancing loss pushes the bars back towards the line.

So a mixture of experts grows the parameters a model holds without growing the work each token does. The cost is memory: every expert must be loaded, though only k of them run for each token.

In code: MixtureOfExperts with top_k_gates routes the tokens, and load_balancing_loss is the penalty. View source

Drag the router's four scores for one token and watch which two run.

Chapter 8

Compute arithmetic: 2N to generate, 6N to train

That work per token can be counted. Each parameter does one multiply and one add for every token that passes through it, so generating one token with a model of N parameters costs about 2N FLOPs (floating-point operations). Training costs about 6N per token. A 7B-parameter model generating one token costs 2 × 7e9 = 1.4e10 operations (14 GFLOPs). Training a 70B model on a trillion tokens costs 6 × 70e9 × 1e12 = 4.2e23 operations.

Figure 12 · Diagram

Reading it: inference only runs the forward pass, so it pays 2 per parameter per token. Training runs the same forward pass, then a backward pass (Neural networks) that costs about twice as much, because it computes gradients both for the weights and for the activations. 2 + 4 = 6.
The formula and its symbols

Symbols

Symbol Meaning here In the example
number of parameters 7e9 / 70e9 / 175e9
number of training tokens 1e12 / 300e9
compute in FLOPs (floating-point operations: one multiply or one add)
in 7e9 "times 10 to the power": 7e9 = 7,000,000,000

In words: "generating costs two operations per parameter per token; training costs six per parameter per training token."

With the numbers: GPT-3: 6 × 175e9 × 300e9 = 3.15e23 FLOPs, matching the roughly 3.14e23 its paper reports.

In Python
def C_infer(N):
    # per generated token
    return 2 * N
def C_train(N, D):
    # over all D training tokens
    return 6 * N * D
print(f"{C_infer(7e9):.2g}  {C_train(70e9, 1e12):.2g}  {C_train(175e9, 300e9):.3g}")  # → 1.4e+10 4.2e+23 3.15e+23

In code: inference_flops_per_token and training_flops are the two rules. View source

With these two rules and the parameter count, a model's configuration becomes an estimate of what it costs to serve and to train.

Set the parameters and the training tokens, and both costs follow from the two rules.

Test yourself

8 questions

Answer each one out loud or on paper before you open it.

Question 1What do attention and the feed-forward network each contribute?Think it through, then reveal

Attention mixes information across tokens; the feed-forward network transforms each token independently and holds most of the parameters (and, it's thought, much of the factual knowledge).

Question 2Why residual connections?Think it through, then reveal

Each sub-layer adds a correction instead of replacing its input, so signal and gradients have a direct path through very deep stacks.

Question 3Pre-norm vs. post-norm?Think it through, then reveal

Pre-norm normalizes before each sub-layer and leaves the residual path untouched; it trains more stably, so modern models use it.

Question 4Why LayerNorm rather than BatchNorm in transformers?Think it through, then reveal

It normalizes within each token, so it doesn't depend on batch size or sequence length.

Question 5Roughly how many parameters does a model with 32 layers of width 4096 have, not counting embeddings?Think it through, then reveal

12 · 32 · 4096² ≈ 6.4 billion.

Question 6Encoder-only vs. decoder-only?Think it through, then reveal

Encoders attend bidirectionally and suit classification and embeddings; decoders attend causally and generate text.

Question 7What does Mixture of Experts buy you, and what does it cost?Think it through, then reveal

More total parameters at the same compute per token, since each token runs only k experts. It costs memory (all experts loaded), routing complexity and load-balancing.

Question 8Estimate the compute to train a 7B model on 2 trillion tokens.Think it through, then reveal

6 × 7e9 × 2e12 = 8.4e22 FLOPs.

Primary sources

The papers behind this lesson

Vaswani et al. (2017), Attention Is All You Need.

Introduced the transformer block: attention plus feed-forward, residuals and layer norm, stacked.

Read on rumblr →The paper
Ba, Kiros & Hinton (2016), Layer Normalization.

Normalized within each example instead of across the batch, the variant transformers use.

Read on rumblr →The paper
Zhang & Sennrich (2019), Root Mean Square Layer Normalization.

Dropped the mean-centring for a cheaper norm now used by most LLMs.

The paper
Hendrycks & Gimpel (2016), Gaussian Error Linear Units (GELUs).

The smooth activation used in GPT-2 and BERT.

The paper
Xiong et al. (2020), On Layer Normalization in the Transformer Architecture.

Explained why pre-norm trains more stably than post-norm.

The paper
Devlin et al. (2018), BERT.

The canonical encoder-only model.

The paper
Fedus, Zoph & Shazeer (2021), Switch Transformers.

Scaled Mixture of Experts and introduced the load-balancing loss built here.

The paper
Jiang et al. (2024), Mixtral of Experts.

An open top-2-of-8 MoE model: about 47B parameters, about 13B active per token.

The paper
Kaplan et al. (2020), Scaling Laws for Neural Language Models.

Popularized the 6·N·D compute estimate.

Read on rumblr →The paper

Researcher's shelf

Further reading

  • The Annotated Transformer (Harvard NLP): https://nlp.seas.harvard.edu/annotated-transformer/
  • The Illustrated Transformer (Jay Alammar): https://jalammar.github.io/illustrated-transformer/
  • Andrej Karpathy, Let's build GPT (video): https://www.youtube.com/watch?v=kCc8FmEb1nY
  • Karpathy's nanoGPT: https://github.com/karpathy/nanoGPT
  • Hugging Face LLM course, How do Transformers work?: https://huggingface.co/learn/llm-course/chapter1/4
  • Hugging Face blog, Mixture of Experts Explained: https://huggingface.co/blog/moe

About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.