Math for ML / Deep Learning & Transformer Math
0 / 12
Module 6

Deep Learning & Transformer Math

A neural network is just linear maps and simple nonlinear functions, composed many times, and a transformer is a clever arrangement of the same pieces. This module builds both from the ground up: you'll compute a forward pass and backpropagate through it by hand, see why the right initialization keeps Var(z)\mathrm{Var}(z) from exploding, learn why attention divides by √d, and watch RoPE turn positions into rotations so that qm⊤knq_m^\top k_n depends only on n−mn-m. It leans on the Linear Algebra module (matrices, dot products, rotations) and on basic calculus (the chain rule).

How to use this module

  • Watch, then play. Chapters link to the best videos on each idea. Watch, then come back and drag the figure until it feels obvious.
  • Questions get harder as you go: Warm-up Practice Think Challenge. Pick one answer, press Check answer, and the worked solution opens.
  • Code it: Python runs in your browser and is graded by test cases. The first run downloads Python (internet needed once).
  • Your progress is saved in this browser. Tick "mark as done" at the end of each chapter.
Chapter 1

Neurons and layers: a network is linear maps plus bends

Watch: But what is a neural network? (3Blue1Brown) Watch: Building micrograd (Andrej Karpathy)

A neuron takes a weighted sum of its inputs, adds a bias and passes the result through a simple nonlinear function. A layer does this for many neurons at once, which is one matrix–vector product. A network is layers composed one after another: matrix, bend, matrix, bend, …

Forget brains for a moment. A neuron in deep learning is a tiny formula. It receives numbers x1,…,xnx_1, \dots, x_n, multiplies each by a weight, adds them up together with a bias bb, and then applies a fixed function σ\sigma called the activation:

a=σ(w1x1+w2x2+⋯+wnxn+b)=σ(w⋅x+b).a = \sigma(w_1x_1 + w_2x_2 + \dots + w_nx_n + b) = \sigma(\mathbf{w}\cdot\mathbf{x} + b).

The weighted sum z=w⋅x+bz = \mathbf{w}\cdot\mathbf{x} + b is called the pre-activation. Geometrically, w⋅x+b=0\mathbf{w}\cdot\mathbf{x} + b = 0 is a line (in 2D) or a flat hyperplane (in more dimensions). The neuron measures how far, and on which side, the input sits relative to that hyperplane. The weights pick the direction it "looks" in; the bias shifts the threshold.

A layer is a matrix

Now put mm neurons side by side, all looking at the same input. Stack their weight vectors as the rows of a matrix WW (size m×nm\times n) and their biases into a vector b\mathbf{b}. All mm weighted sums at once are one matrix–vector product, the thing you met in Linear Algebra chapter 3:

z=Wx+b,a=σ(z) (applied to each entry).\mathbf{z} = W\mathbf{x} + \mathbf{b}, \qquad \mathbf{a} = \sigma(\mathbf{z}) \text{ (applied to each entry).}

Row ii of WW dotted with x\mathbf{x} gives neuron ii's sum. A layer with nn inputs and mm outputs has mnmn weights and mm biases: its parameters, the numbers training will tune.

A network is a composition

Feed one layer's output into the next and you have a multilayer perceptron (MLP):

f(x)=W3 σ(W2 σ(W1x+b1)+b2)+b3.f(\mathbf{x}) = W_3\,\sigma\big(W_2\,\sigma(W_1\mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2\big) + \mathbf{b}_3.

Read it inside-out: transform linearly, bend, transform linearly, bend, transform linearly. The middle outputs are hidden activations. The last layer usually has no activation (or a special one, like softmax in chapter 3). 3Blue1Brown's digit recognizer is exactly this with sizes 784 → 16 → 16 → 10: 784 pixel brightnesses in, ten digit scores out.

Why the bends? Without σ\sigma, two layers collapse into one:

W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2),W_2(W_1\mathbf{x}+\mathbf{b}_1)+\mathbf{b}_2 = (W_2W_1)\mathbf{x} + (W_2\mathbf{b}_1+\mathbf{b}_2),

which is again just one linear layer. Stacking a hundred linear layers buys nothing. Chapter 2 is all about this.

Batches: the code convention

In code we push many examples through at once. Put NN examples as the rows of a matrix XX (shape N×nN\times n) and write the layer as Z=XW+bZ = XW + \mathbf{b}, with WW of shape n×mn\times m and b\mathbf{b} added to every row. That's the same math transposed: Wcode=Wmath⊤W_{\text{code}} = W_{\text{math}}^\top. PyTorch's nn.Linear stores the m×nm\times n version and computes XW⊤+bXW^\top + \mathbf{b}. Whenever you're unsure, check shapes: the inner dimensions must match.

A real network with 2 inputs, one hidden layer of tanh neurons and a sigmoid output, classifying the two colours of points. The background shows its prediction everywhere; the dark curve is the decision boundary. Press Train and watch gradient descent bend the boundary; drag points around while it trains. Untick nonlinear and the boundary can only ever be a straight line, however many neurons you add.

Worked exampleA forward pass by hand

Take x=(1,2)\mathbf{x} = (1, 2), a hidden layer with W1=[1−120]W_1 = \begin{bmatrix}1 & -1\\ 2 & 0\end{bmatrix}, b1=(0,−1)\mathbf{b}_1 = (0, -1) and ReLU (σ(z)=max⁡(0,z)\sigma(z) = \max(0, z)), then an output neuron with weights (1,1)(1, 1) and bias 0.50.5.

  • Pre-activations: z1=1⋅1+(−1)⋅2+0=−1z_1 = 1\cdot1 + (-1)\cdot2 + 0 = -1 and z2=2⋅1+0⋅2−1=1z_2 = 2\cdot1 + 0\cdot2 - 1 = 1.
  • ReLU: h=(max⁡(0,−1),max⁡(0,1))=(0,1)\mathbf{h} = (\max(0,-1), \max(0,1)) = (0, 1). The first neuron is "off" for this input.
  • Output: y=1⋅0+1⋅1+0.5=1.5y = 1\cdot0 + 1\cdot1 + 0.5 = 1.5.

Parameter count: the hidden layer has 2⋅2+2=62\cdot2 + 2 = 6, the output 2+1=32 + 1 = 3, so 9 in total.

Watch outCommon misconceptions

  • "Neurons are where the learning lives." The learned numbers are the weights and biases, the connections. The activation function is fixed.
  • "More layers always means more power." Only with nonlinearities between them. Linear layers stacked are one linear layer.
  • "WW is inputs×outputs\text{inputs}\times\text{outputs}." It depends on the convention. In math (WxW\mathbf{x}) it's outputs × inputs; in batched code (XWXW) it's inputs × outputs. Let shapes, not habit, decide.
  • "Biases are optional details." Without a bias, every neuron's hyperplane must pass through the origin, which is a real restriction.

In ML & deep learningWhere this shows up

Every modern architecture is built from this block. The "MLP" (or "feed-forward") half of every transformer layer is exactly W2 σ(W1x+b1)+b2W_2\,\sigma(W_1\mathbf{x}+\mathbf{b}_1)+\mathbf{b}_2, applied to each token separately, and it holds about two-thirds of a large language model's parameters. Counting parameters, as in the questions below, is how people quote model sizes like "7B".

Practice (pick one answer per question)

A layer maps 3 inputs to 5 outputs, written as z=Wx+b\mathbf{z} = W\mathbf{x} + \mathbf{b}. What shape is WW?

  1. 5 × 3
  2. 3 × 5
  3. 5 × 5
  4. 15 × 1

WxW\mathbf{x} must turn a length-3 vector into a length-5 vector, so WW has 5 rows (one per neuron) and 3 columns (one per input): 5 × 3.

How many parameters (weights and biases) does a dense layer from 3 inputs to 5 outputs have?

  1. 20
  2. 15
  3. 18
  4. 8

15 weights (5×35\times3) plus 5 biases, one per output neuron: 20. Forgetting biases gives 15.

A ReLU neuron has weights w=(2,−1,0.5)\mathbf{w} = (2, -1, 0.5) and bias b=1b = 1. What does it output for x=(1,3,2)\mathbf{x} = (1, 3, 2)?

  1. 1
  2. 0
  3. 2
  4. 3

z=2⋅1−1⋅3+0.5⋅2+1=2−3+1+1=1z = 2\cdot1 - 1\cdot3 + 0.5\cdot2 + 1 = 2 - 3 + 1 + 1 = 1. ReLU leaves a positive number alone, so the output is 1.

How many parameters does the 784 → 16 → 16 → 10 digit network have in total?

  1. 13,002
  2. 12,960
  3. 12,544
  4. 13,560

Weights: 784⋅16+16⋅16+16⋅10=12544+256+160=12960784\cdot16 + 16\cdot16 + 16\cdot10 = 12544 + 256 + 160 = 12960. Biases: 16+16+10=4216 + 16 + 10 = 42. Total 13,002. (12,960 forgets the biases.)

A batch XX of 32 examples with 10 features goes through Z=XW+bZ = XW + \mathbf{b}, a layer with 4 outputs. What shape is ZZ?

  1. 32 × 4
  2. 4 × 32
  3. 10 × 4
  4. 32 × 10

XX is 32×1032\times10, so WW must be 10×410\times4, and XWXW is 32 × 4: one row of 4 outputs per example. The bias (length 4) is added to every row.

Two layers with no activation between them compute W2(W1x+b1)+b2W_2(W_1\mathbf{x}+\mathbf{b}_1)+\mathbf{b}_2. Which single layer computes the same function?

  1. Weights W2W1W_2W_1, bias W2b1+b2W_2\mathbf{b}_1+\mathbf{b}_2
  2. Weights W1W2W_1W_2, bias b1+b2\mathbf{b}_1+\mathbf{b}_2
  3. Weights W2W1W_2W_1, bias b1+b2\mathbf{b}_1+\mathbf{b}_2
  4. No single layer can; two layers are strictly more powerful

Distribute: W2W1x+W2b1+b2W_2W_1\mathbf{x} + W_2\mathbf{b}_1 + \mathbf{b}_2. The bias of the first layer also passes through W2W_2. The order is W2W1W_2W_1 because W1W_1 acts first (Linear Algebra chapter 4). So the stack collapses to one linear layer.

A network has 2 inputs, one hidden layer of 3 ReLU neurons and a linear output. Each hidden neuron switches on and off along a line in the input plane. At most how many regions, each with its own linear formula, can the plane be cut into?

  1. 7
  2. 6
  3. 8
  4. 3

Inside each region every neuron is either on or off, so the network is linear there. The regions are cut out by 3 lines. nn lines in general position cut the plane into at most 1+n+(n2)1 + n + \binom{n}{2} regions: 1+3+3=1 + 3 + 3 = 7. (Not 23=82^3 = 8: three lines can't make all 8 on/off patterns.)

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 2

Activation functions, and why nonlinearity matters

Watch: Neural Networks Pt. 3, ReLU in action (StatQuest) Watch: makemore Part 3, activations & gradients (Andrej Karpathy)

Linear layers alone can only draw straight boundaries, because a composition of linear maps is linear. A cheap nonlinear function after each layer (ReLU, sigmoid, tanh, GELU) lets the network bend space. Which one you pick changes how gradients flow: flat regions of the curve mean zero slope, and zero slope means no learning.

Why a straight line isn't enough

The classic example is XOR: label the points (0, 0) and (1, 1) with 0, and (1, 0) and (0, 1) with 1. No single straight line separates the 1s from the 0s. A purely linear network, however deep, computes Ax+cA\mathbf{x}+\mathbf{c} for some matrix AA, so its decision boundary is always one straight line (a hyperplane in higher dimensions). It cannot solve XOR.

Add one bend and it can. Two ReLU neurons do it:

h1=ReLU(x1+x2),h2=ReLU(x1+x2−1),y=h1−2h2.h_1 = \mathrm{ReLU}(x_1 + x_2),\quad h_2 = \mathrm{ReLU}(x_1 + x_2 - 1),\quad y = h_1 - 2h_2.

Check: (0, 0) gives 0−0=00 - 0 = 0; (1, 0) and (0, 1) give 1−0=11 - 0 = 1; (1, 1) gives 2−2⋅1=02 - 2\cdot1 = 0. The second neuron switches on only past the line x1+x2=1x_1+x_2=1 and folds the rising ramp back down. That's what activations are for: each one adds a fold, and many folds can approximate any reasonable shape (the universal approximation idea).

The usual suspects

  • ReLU: max⁡(0,z)\max(0, z). Slope 1 for z>0z>0, slope 0 for z<0z\lt 0. Dirt cheap, and positive inputs pass their gradient through unchanged. Its weakness: a neuron whose pre-activation is negative for every input has slope 0 everywhere and gets no gradient, ever. It's a dead ReLU. Leaky ReLU uses a small slope such as 0.01 for z<0z\lt0 to keep a trickle of gradient.
  • Sigmoid: σ(z)=11+e−z\sigma(z) = \frac{1}{1+e^{-z}}, squashing everything into (0, 1). Its derivative has a neat form, σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1-\sigma(z)), which is at most 0.250.25 (at z=0z=0). For large ∣z∣|z| the curve is flat: it saturates and the slope is nearly 0. Today it's used mainly for outputs that are probabilities and for gates.
  • tanh: squashes into (−1, 1) and is a stretched sigmoid, tanh⁡z=2σ(2z)−1\tanh z = 2\sigma(2z) - 1. It's zero-centred and its slope 1−tanh⁡2z1-\tanh^2 z reaches 1 at the origin, but it saturates just like sigmoid.
  • GELU: z Φ(z)z\,\Phi(z), where Φ\Phi is the standard normal CDF. Think of it as a smooth ReLU: near 1·z for large positive zz, near 0 for very negative zz, with a small dip to about −0.17 around z≈−0.75z\approx-0.75. GPT-2, BERT and most transformers use it (or the close cousin SiLU, z σ(z)z\,\sigma(z)).

Slopes multiply

Backpropagation (chapter 4) multiplies the activation's slope at every layer into the gradient. With sigmoid, each layer contributes a factor of at most 0.25, so ten layers shrink the gradient by at least 0.2510≈10−60.25^{10}\approx 10^{-6}. That's one root of the vanishing gradient problem, and the main reason ReLU-family activations replaced sigmoid in hidden layers.

Pick an activation. The gold curve is the function, the dashed teal curve its slope. Drag the point along the curve; the readout shows the value and slope there. Red shading marks where the slope is almost zero: dead (ReLU) or saturated (sigmoid, tanh). Gradients that land there barely get through.

Worked exampleValues and slopes

  • σ(0)=11+1=0.5\sigma(0) = \frac{1}{1+1} = 0.5 and σ′(0)=0.5⋅0.5=0.25\sigma'(0) = 0.5\cdot0.5 = 0.25.
  • σ(2)=11+e−2≈0.881\sigma(2) = \frac{1}{1+e^{-2}} \approx 0.881, so σ′(2)≈0.881⋅0.119≈0.105\sigma'(2) \approx 0.881\cdot0.119 \approx 0.105. Already less than half the peak slope.
  • tanh⁡(0)=0\tanh(0) = 0 and tanh⁡′(0)=1−0=1\tanh'(0) = 1 - 0 = 1; tanh⁡(2)≈0.964\tanh(2)\approx0.964, so tanh⁡′(2)≈1−0.929=0.071\tanh'(2) \approx 1-0.929 = 0.071.
  • ReLU′(3)=1\mathrm{ReLU}'(3) = 1 but ReLU′(−1)=0\mathrm{ReLU}'(-1) = 0. GELU(1)=1⋅Φ(1)≈0.841\mathrm{GELU}(1) = 1\cdot\Phi(1) \approx 0.841.

Watch outCommon misconceptions

  • "Nonlinearity is there to make the output a probability." That's the job of the last layer's function. Hidden activations are there so the layers don't collapse into one linear map.
  • "ReLU is linear, so it can't help." It's linear on each side of 0, but the kink makes it nonlinear overall: ReLU(a+b)≠ReLU(a)+ReLU(b)\mathrm{ReLU}(a+b) \ne \mathrm{ReLU}(a)+\mathrm{ReLU}(b) in general (try a=1,b=−1a=1,b=-1).
  • "A dead ReLU comes back on its own." If a neuron is negative for every training input, its weights receive zero gradient and never change. Something else has to move it (other layers shifting its inputs), and often nothing does.
  • "ReLU isn't differentiable at 0, so gradient descent breaks." Frameworks just pick a slope (0) at exactly z=0z=0. Hitting exactly 0 almost never matters.

In ML & deep learningWhere this shows up

CNNs like ResNet use ReLU; transformers use GELU or SiLU in their MLP blocks (LLaMA's "SwiGLU" multiplies a SiLU branch by a linear branch). Sigmoid lives on in binary classifiers, in the gates of LSTMs, and in mixture-of-experts routers. Karpathy's makemore lecture shows the practical symptom of saturation: histograms of tanh outputs piled up at ±1, and "white" neurons that never learn.

Practice (pick one answer per question)

What is ReLU(−3)\mathrm{ReLU}(-3)?

  1. 0
  2. −3
  3. 3
  4. 1

max⁡(0,−3)=0\max(0, -3) = 0. ReLU zeroes every negative input.

What is σ(0)\sigma(0) for the sigmoid σ(z)=1/(1+e−z)\sigma(z) = 1/(1+e^{-z})?

  1. 0.5
  2. 0
  3. 1
  4. 0.25

e0=1e^0 = 1, so σ(0)=1/2\sigma(0) = 1/2. (0.25 is the slope there, not the value.)

What is the largest value the sigmoid's derivative σ′(z)\sigma'(z) ever takes?

  1. 0.25
  2. 0.5
  3. 1
  4. It has no maximum

σ′=σ(1−σ)\sigma' = \sigma(1-\sigma), and s(1−s)s(1-s) is largest at s=0.5s = 0.5, giving 0.250.25. That happens at z=0z = 0.

Ignoring the weights, a gradient passes through 10 sigmoid layers. At best, by what factor can the activations' slopes shrink it?

  1. about 9.5×10−79.5\times10^{-7}
  2. about 0.025
  3. about 2.5
  4. it doesn't shrink

Each slope is at most 0.25, and the slopes multiply: 0.2510=1/1048576≈9.5×10−70.25^{10} = 1/1048576 \approx 9.5\times10^{-7}. Even the best case vanishes.

Using the XOR network from this chapter (h1=ReLU(x1+x2)h_1 = \mathrm{ReLU}(x_1+x_2), h2=ReLU(x1+x2−1)h_2 = \mathrm{ReLU}(x_1+x_2-1), y=h1−2h2y = h_1 - 2h_2), what is yy at (x1,x2)=(2,0)(x_1,x_2) = (2, 0)?

  1. 0
  2. 2
  3. 1
  4. −2

h1=2h_1 = 2, h2=ReLU(1)=1h_2 = \mathrm{ReLU}(1) = 1, so y=2−2=0y = 2 - 2 = 0. Past the fold the output keeps falling with slope 1−2=−11 - 2 = -1.

GELU(z)=z Φ(z)\mathrm{GELU}(z) = z\,\Phi(z), with Φ(1)≈0.841\Phi(1)\approx0.841. What is GELU(−1)\mathrm{GELU}(-1)?

  1. about −0.159
  2. 0
  3. about −0.841
  4. −1

By symmetry of the normal distribution, Φ(−1)=1−Φ(1)≈0.159\Phi(-1) = 1 - \Phi(1) \approx 0.159. So GELU(−1)=−1⋅0.159≈−0.159\mathrm{GELU}(-1) = -1\cdot0.159 \approx -0.159. Unlike ReLU, GELU lets a little negative signal (and gradient) through.

Why can't a 50-layer network with no activation functions solve XOR?

  1. It equals a single linear layer, whose boundary is a straight line
  2. 50 layers is too few for XOR
  3. Its gradients vanish, so it can't train
  4. XOR needs a sigmoid output to be solvable

Composing linear (affine) maps gives another affine map Ax+cA\mathbf{x}+\mathbf{c}. Its 0.5-level set is a straight line, and no line separates XOR. Depth adds nothing without nonlinearity.

A ReLU neuron has weights w=(1,−2)\mathbf{w} = (1, -2) and bias b=−4b = -4. All training inputs lie in the square −1≤x1,x2≤1-1\le x_1, x_2 \le 1. What happens to it during training?

  1. It never activates, gets zero gradient and stays exactly as it is
  2. It activates for about half the inputs
  3. Its bias grows until it switches on
  4. It outputs negative values that gradient descent pushes up

The largest possible pre-activation is 1⋅1+(−2)(−1)−4=−1<01\cdot1 + (-2)(-1) - 4 = -1 \lt 0. So the neuron outputs 0 for every input and its slope is 0 everywhere: every gradient through it is 0. It is a dead ReLU.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 3

Softmax and cross-entropy: from logits to a loss

Watch: ArgMax and SoftMax (StatQuest) Watch: Cross Entropy (StatQuest) Watch: Transformers, the tech behind LLMs: softmax with temperature (3Blue1Brown)

A classifier's last layer outputs one raw score per class, the logits. Softmax turns them into probabilities by exponentiating and normalizing. Cross-entropy then charges −log⁡p-\log p for the probability given to the correct class. The gradient of the two together is beautifully simple: predicted probabilities minus the one-hot truth.

Softmax

Suppose the network outputs z=(z1,…,zK)\mathbf{z} = (z_1,\dots,z_K) for KK classes. These can be any real numbers. To get probabilities, make them positive with the exponential and then divide by the total:

pi=softmax(z)i=ezi∑j=1Kezj.p_i = \mathrm{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_{j=1}^K e^{z_j}}.

Every pip_i is positive and they sum to 1. The biggest logit gets the biggest probability, but the others aren't zeroed out: it's a "soft" version of picking the max. Three properties matter in practice:

  • Only differences matter. Adding the same constant cc to every logit multiplies top and bottom by ece^c, which cancels. Code uses this for safety: subtract max⁡jzj\max_j z_j first, so the largest exponent is e0=1e^0=1 and nothing overflows.
  • Gaps become ratios. pi/pj=ezi−zjp_i/p_j = e^{z_i - z_j}. A logit 1 higher means e≈2.7e\approx2.7 times as likely; ln⁡3≈1.1\ln 3\approx1.1 higher means 3 times as likely.
  • Temperature. Using softmax(z/T)\mathrm{softmax}(\mathbf{z}/T) with T<1T\lt1 sharpens the distribution toward the top class (as T→0T\to0 it becomes the one-hot argmax); T>1T\gt1 flattens it (as T→∞T\to\infty it becomes uniform). This is the "temperature" knob when you sample from a language model.

Cross-entropy loss

If the correct class is yy, the cross-entropy loss is

L=−log⁡py.L = -\log p_y.

A confident correct answer (py→1p_y\to1) costs nearly 0; a confident wrong one (py→0p_y\to0) costs a lot, without bound. With a one-hot target vector y\mathbf{y} the same thing is written L=−∑iyilog⁡piL = -\sum_i y_i \log p_i. Averaged over a dataset, minimizing it is the same as maximizing the likelihood of the data under the model. A model that guesses uniformly has py=1/Kp_y = 1/K and loss log⁡K\log K: a great sanity check for the loss at the start of training.

The gradient: p−y\mathbf{p} - \mathbf{y}

Write L=−zy+log⁡∑jezjL = -z_y + \log\sum_j e^{z_j}. Differentiate with respect to ziz_i: the first term gives −1-1 if i=yi=y and 0 otherwise; the second gives ezi/∑jezj=pie^{z_i}/\sum_j e^{z_j} = p_i. So

∂L∂zi=pi−yi,∇zL=p−y.\frac{\partial L}{\partial z_i} = p_i - y_i, \qquad \nabla_{\mathbf{z}} L = \mathbf{p} - \mathbf{y}.

Read it as: push the correct logit up by 1−py1 - p_y, and push every wrong logit down by however much probability it stole. The gradient is never bigger than 1 in size, and it fades smoothly as the prediction becomes right.

Drag the four logits (left) up and down; the right side shows the softmax probabilities. Pick the true class with the buttons: its bar is outlined and the readout gives the cross-entropy loss and the gradient p−y\mathbf{p}-\mathbf{y}. Slide the temperature: low makes the top class take everything, high flattens all bars toward 0.25. Then add the same amount to every logit and notice that nothing changes.

Worked exampleThree classes

Logits z=(2,1,0)\mathbf{z} = (2, 1, 0). Exponentials: e2≈7.389e^2\approx7.389, e1≈2.718e^1\approx2.718, e0=1e^0 = 1, total ≈11.107\approx11.107. So p≈(0.665,0.245,0.090)\mathbf{p}\approx(0.665, 0.245, 0.090).

If the true class is the first, L=−ln⁡0.665≈0.408L = -\ln 0.665 \approx 0.408, and the gradient is p−y≈(−0.335,0.245,0.090)\mathbf{p}-\mathbf{y} \approx (-0.335, 0.245, 0.090). Gradient descent subtracts it, raising z1z_1 and lowering the other two. If the true class were the third, L=−ln⁡0.090≈2.408L = -\ln 0.090\approx2.408: a much bigger penalty.

Watch outCommon misconceptions

  • "Softmax probabilities are proportional to the logits." They're proportional to ezie^{z_i}. Logits (1, 2) don't give a 1 : 2 ratio; they give 1:e1 : e.
  • "Negative logits mean negative probability." Exponentials are always positive. Logit −5 just means unlikely.
  • "Compute softmax, then take the log." For large logits the exponentials overflow, and tiny probabilities round to 0 and give log⁡0\log 0. Libraries fuse them (log_softmax, cross_entropy on raw logits) and subtract the max.
  • "Loss 0 is the goal." It needs py=1p_y=1, meaning infinitely large logit gaps. A model that gets there is usually overconfident and overfit.

In ML & deep learningWhere this shows up

Every image classifier and every language model ends with softmax + cross-entropy: an LLM's vocabulary of ~50,000 tokens is a 50,000-way classification at every position. People report perplexity eLe^{L}, the "effective number of choices" the model is torn between. Softmax also appears inside transformers: attention weights are a softmax over scores (chapter 10). Binary classification is the K=2K=2 case: softmax over logits (a,b)(a, b) gives σ(a−b)\sigma(a-b).

Practice (pick one answer per question)

What is softmax(0,0,0,0)\mathrm{softmax}(0, 0, 0, 0)?

  1. (0.25, 0.25, 0.25, 0.25)
  2. (0, 0, 0, 0)
  3. (1, 1, 1, 1)
  4. undefined

Each e0=1e^0 = 1, the total is 4, so every class gets 1/4. Equal logits mean a uniform guess.

The model gives the correct class probability 1. What is the cross-entropy loss?

  1. 0
  2. 1
  3. −1
  4. infinity

−log⁡1=0-\log 1 = 0. Infinity is the opposite case, probability 0 on the correct class.

What is softmax(1, 1+ln⁡3)\mathrm{softmax}(1,\ 1+\ln 3)?

  1. (0.25, 0.75)
  2. (0.5, 0.5)
  3. (1/3, 2/3)
  4. (0.4, 0.6)

Only the difference matters: the ratio is p2/p1=eln⁡3=3p_2/p_1 = e^{\ln 3} = 3. Probabilities in ratio 1 : 3 that sum to 1 are (0.25, 0.75).

A freshly initialized model predicts the next character out of 27 options, almost uniformly. Roughly what loss should you see at step 0?

  1. about 3.30
  2. about 4.75
  3. about 0.037
  4. about 27

Uniform means py=1/27p_y = 1/27, so L=ln⁡27≈3.30L = \ln 27 \approx 3.30 (natural log). 4.75 is log⁡227\log_2 27. If your initial loss is much bigger than ln⁡K\ln K, the initial logits are too large: chapter 5's lesson.

Softmax gives p=(0.7,0.2,0.1)\mathbf{p} = (0.7, 0.2, 0.1) and the true class is the third. What is ∇zL\nabla_{\mathbf{z}}L?

  1. (0.7, 0.2, −0.9)
  2. (−0.3, 0.2, 0.1)
  3. (0.7, 0.2, 0.1)
  4. (0, 0, −2.303)

p−y=(0.7,0.2,0.1)−(0,0,1)=\mathbf{p} - \mathbf{y} = (0.7, 0.2, 0.1) - (0, 0, 1) = (0.7, 0.2, −0.9). The wrong-but-confident first class gets the biggest push down; the true class gets pushed up hard.

What happens to softmax(z/T)\mathrm{softmax}(\mathbf{z}/T) as the temperature TT goes to 0 (logits all different)?

  1. It becomes one-hot on the largest logit
  2. It becomes uniform
  3. It stays the same
  4. Every probability goes to 0

Dividing by a tiny TT blows up every gap (zi−zmax⁡)/T(z_i - z_{\max})/T to −∞-\infty except for the top class, so all probability moves onto the argmax. High temperature does the opposite: gaps shrink and the distribution flattens.

A binary classifier uses softmax over two logits (a,b)(a, b). Which formula gives the probability of the first class?

  1. σ(a−b)\sigma(a - b)
  2. σ(a)/(σ(a)+σ(b))\sigma(a)/(\sigma(a)+\sigma(b))
  3. σ(a+b)\sigma(a + b)
  4. a/(a+b)a/(a+b)

eaea+eb=11+e−(a−b)=σ(a−b)\frac{e^a}{e^a+e^b} = \frac{1}{1+e^{-(a-b)}} = \sigma(a-b) (divide top and bottom by eae^a). So sigmoid is two-class softmax with one logit fixed at 0, and only the difference of logits matters.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 4

Backpropagation through an MLP, by hand

Watch: Backpropagation, intuitively (3Blue1Brown) Watch: Backpropagation calculus (3Blue1Brown) Watch: Gradient descent, how neural networks learn (3Blue1Brown)

Training needs the slope of the loss with respect to every weight. Backpropagation gets all of them in one backward sweep: start from ∂L/∂L=1\partial L/\partial L = 1 at the end and apply the chain rule layer by layer, reusing what the forward pass stored. Every gradient has exactly the shape of the thing it's the gradient of, which pins down each formula.

The plan: forward, then backward

Gradient descent updates every parameter by θ←θ−η ∂L/∂θ\theta \leftarrow \theta - \eta\,\partial L/\partial\theta, where η\eta is the learning rate. A network has millions of parameters but only one loss, and the chain rule lets us share work: the gradient of a layer's inputs is built from the gradient of its outputs. So we run the network forward, keeping every intermediate value, then walk backward from the loss, turning "how much does the loss care about this layer's output?" into "how much does it care about this layer's weights, and about its input?".

A useful mindset is "local gradient times upstream gradient". Each operation only needs to know its own derivative; the gradient arriving from above (upstream) tells it how much the loss cares about its output.

The rules for one dense layer

Take a batch, Z=XW+bZ = XW + \mathbf{b}, with XX of shape N×nN\times n, WW of shape n×mn\times m, and suppose we already know G=∂L/∂ZG = \partial L/\partial Z (shape N×mN\times m, same as ZZ). Then

∂L∂W=X⊤G  (n×m),∂L∂b=∑rowsG  (m),∂L∂X=G W⊤  (N×n).\frac{\partial L}{\partial W} = X^\top G\ \ (n\times m),\qquad \frac{\partial L}{\partial \mathbf{b}} = \textstyle\sum_{\text{rows}} G\ \ (m),\qquad \frac{\partial L}{\partial X} = G\,W^\top\ \ (N\times n).

You don't have to memorize these: the gradient has the same shape as the variable, and there's only one way to multiply XX and GG to get an n×mn\times m result. The bias gradient sums over the batch because the same bias was added to every row. Each entry checks out by hand: Zkm=∑jXkjWjmZ_{km} = \sum_j X_{kj}W_{jm}, so WjmW_{jm} touches every row kk with coefficient XkjX_{kj}, and its gradient is ∑kXkjGkm\sum_k X_{kj}G_{km}, which is entry (j,m)(j,m) of X⊤GX^\top G.

For an activation H=σ(Z)H = \sigma(Z) applied entry by entry, the rule is a plain product: ∂L/∂Z=∂L/∂H⊙σ′(Z)\partial L/\partial Z = \partial L/\partial H \odot \sigma'(Z). For ReLU that means: copy the gradient where Z>0Z\gt0, zero it where Z<0Z\lt0. And when one value feeds two places, the gradients from both places add.

A 2–2–1 network with ReLU hidden units and squared-error loss, using the numbers in the worked example below. Press Next to run the forward pass node by node, then the backward pass. Values are in the nodes, gradients appear in red beside them and on every weight. Press Gradient step to update all weights with η = 0.1 and see the loss drop. Change the inputs or target with the sliders.

Worked exampleA 2–2–1 network, every number

Input x=(1,2)\mathbf{x} = (1, 2). Hidden layer (rows are neurons) W1=[1−10.51]W_1 = \begin{bmatrix}1 & -1\\ 0.5 & 1\end{bmatrix}, b1=(2,0)\mathbf{b}_1 = (2, 0), ReLU. Output y=v⋅h+cy = \mathbf{v}\cdot\mathbf{h} + c with v=(2,−1)\mathbf{v} = (2, -1), c=0.5c = 0.5. Target t=1t = 1, loss L=12(y−t)2L = \tfrac12(y-t)^2.

Forward. z=W1x+b1=(1−2+2, 0.5+2+0)=(1,2.5)\mathbf{z} = W_1\mathbf{x}+\mathbf{b}_1 = (1-2+2,\ 0.5+2+0) = (1, 2.5). Both positive, so h=(1,2.5)\mathbf{h} = (1, 2.5). Then y=2−2.5+0.5=0y = 2 - 2.5 + 0.5 = 0 and L=12(0−1)2=0.5L = \tfrac12(0-1)^2 = 0.5.

Backward.

  • ∂L/∂y=y−t=−1\partial L/\partial y = y - t = -1.
  • Output layer: ∂L/∂v=(−1) h=(−1,−2.5)\partial L/\partial\mathbf{v} = (-1)\,\mathbf{h} = (-1, -2.5), ∂L/∂c=−1\partial L/\partial c = -1, and ∂L/∂h=(−1) v=(−2,1)\partial L/\partial\mathbf{h} = (-1)\,\mathbf{v} = (-2, 1).
  • Through ReLU (both units on): ∂L/∂z=(−2,1)\partial L/\partial\mathbf{z} = (-2, 1).
  • Hidden layer: ∂L/∂W1=(∂L/∂z) x⊤=[−2−412]\partial L/\partial W_1 = (\partial L/\partial\mathbf{z})\,\mathbf{x}^\top = \begin{bmatrix}-2 & -4\\ 1 & 2\end{bmatrix} (same shape as W1W_1), ∂L/∂b1=(−2,1)\partial L/\partial\mathbf{b}_1 = (-2, 1).
  • Input (if we wanted it): ∂L/∂x=W1⊤(−2,1)=(−1.5,3)\partial L/\partial\mathbf{x} = W_1^\top(-2, 1) = (-1.5, 3).

One step with η=0.1\eta = 0.1 changes cc to 0.60.6, v\mathbf{v} to (2.1,−0.75)(2.1, -0.75), and so on. Every change nudges yy up toward the target.

Watch outCommon misconceptions

  • "Backprop is a learning algorithm." It only computes gradients. Gradient descent (or Adam, …) is what uses them to change the weights.
  • "The gradient of WW is G X⊤G\,X^\top." Check the shapes: that's N×NN\times N-ish nonsense. With Z=XWZ = XW, it's X⊤GX^\top G. With the math convention z=Wx\mathbf{z} = W\mathbf{x}, it's gx⊤\mathbf{g}\mathbf{x}^\top. Shapes always tell you which.
  • "Gradients of a reused value overwrite each other." They add. In code, that's why frameworks accumulate with += (and why you must zero gradients between steps).
  • "Backward costs as much as computing each gradient separately." The whole backward pass costs about twice the forward pass, for all parameters at once. That's what makes training huge networks possible.

In ML & deep learningWhere this shows up

PyTorch's loss.backward() does exactly this on the recorded computation graph (reverse-mode automatic differentiation). Karpathy's micrograd builds the whole mechanism in about 100 lines of Python. Knowing the shape rules by heart is what lets you debug custom layers, and checking your gradient against a finite difference L(θ+h)−L(θ−h)2h\frac{L(\theta+h)-L(\theta-h)}{2h} (the coding problem below) is the standard way to test one.

Practice (pick one answer per question)

A weight matrix WW has shape 64 × 128. What shape is ∂L/∂W\partial L/\partial W?

  1. 64 × 128
  2. 128 × 64
  3. 64 × 64
  4. 1 × 1, since the loss is a single number

The gradient has one entry per weight, saying how the loss responds to that weight, so it has the shape of WW: 64 × 128.

y=wxy = wx with x=3x = 3, and ∂L/∂y=2\partial L/\partial y = 2. What is ∂L/∂w\partial L/\partial w?

  1. 6
  2. 2
  3. 3
  4. 1.5

Chain rule: ∂L/∂w=∂L/∂y⋅∂y/∂w=2⋅x=6\partial L/\partial w = \partial L/\partial y\cdot\partial y/\partial w = 2\cdot x = 6.

A ReLU layer had pre-activations z=(−1,2,0.5)\mathbf{z} = (-1, 2, 0.5). The upstream gradient ∂L/∂h\partial L/\partial\mathbf{h} is (3,3,3)(3, 3, 3). What is ∂L/∂z\partial L/\partial\mathbf{z}?

  1. (0, 3, 3)
  2. (3, 3, 3)
  3. (0, 6, 1.5)
  4. (−3, 6, 1.5)

ReLU's slope is 0 where z<0z\lt0 and 1 where z>0z\gt0. Multiply entry by entry: (3⋅0,3⋅1,3⋅1)=(0,3,3)(3\cdot0, 3\cdot1, 3\cdot1) = (0, 3, 3). (Multiplying by zz itself is a common slip.)

Z=XWZ = XW, with XX of shape 32 × 10 and ∂L/∂Z\partial L/\partial Z of shape 32 × 4. Which expression is ∂L/∂W\partial L/\partial W?

  1. X⊤ (∂L/∂Z)X^\top\,(\partial L/\partial Z), shape 10 × 4
  2. (∂L/∂Z) X⊤(\partial L/\partial Z)\,X^\top, shape 32 × 32
  3. (∂L/∂Z)⊤X(\partial L/\partial Z)^\top X, shape 4 × 10
  4. X (∂L/∂Z)⊤X\,(\partial L/\partial Z)^\top, shape 32 × 32

WW is 10 × 4, so its gradient must be too. The only product of a 32 × 10 and a 32 × 4 matrix giving 10 × 4 is X⊤GX^\top G: it sums over the batch of 32.

A sigmoid neuron a=σ(wx+b)a = \sigma(wx + b) with loss L=12(a−t)2L = \tfrac12(a - t)^2. At w=0w = 0, b=0b = 0, x=2x = 2, t=1t = 1, what is ∂L/∂w\partial L/\partial w?

  1. −0.25
  2. −0.5
  3. −0.125
  4. 0.25

Forward: z=0z = 0, a=0.5a = 0.5. Backward: ∂L/∂a=a−t=−0.5\partial L/\partial a = a - t = -0.5; ∂a/∂z=σ′(0)=0.25\partial a/\partial z = \sigma'(0) = 0.25; ∂z/∂w=x=2\partial z/\partial w = x = 2. Product: −0.5⋅0.25⋅2=−0.25-0.5\cdot0.25\cdot2 = -0.25.

A weight w=3w = 3 is used twice: a=2wa = 2w and b=w2b = w^2, and the loss depends on both with ∂L/∂a=1\partial L/\partial a = 1, ∂L/∂b=2\partial L/\partial b = 2. What is ∂L/∂w\partial L/\partial w?

  1. 14
  2. 12
  3. 2
  4. 8

Add the contributions of both paths: 1⋅dadw+2⋅dbdw=1⋅2+2⋅(2w)=2+12=141\cdot\frac{da}{dw} + 2\cdot\frac{db}{dw} = 1\cdot2 + 2\cdot(2w) = 2 + 12 = 14. Keeping only one path gives 2 or 12.

Why does backpropagation go from the output back to the input, rather than forward from each weight?

  1. There's one loss and many weights; one backward sweep gives every weight's gradient at about twice the forward cost
  2. The chain rule only works from right to left
  3. The forward direction would give the wrong answer
  4. So that the weights can be updated while the gradient is being computed

Forward-mode differentiation tracks how one input perturbation spreads to all outputs, so it would need one sweep per parameter (millions). Reverse mode tracks how one output (the scalar loss) depends on everything, which is exactly our situation. Both give the same, correct numbers; reverse mode is just vastly cheaper here.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 5

Initialization, and vanishing and exploding gradients

Watch: makemore Part 3, activations, gradients & BatchNorm (Andrej Karpathy)

Each layer multiplies the size of the signal by roughly the same factor, so after LL layers the size is that factor to the power LL. Unless the factor is very close to 1, activations and gradients explode or vanish. A variance calculation tells you how big the random starting weights must be for the factor to be 1: variance 1/n1/n (Xavier/LeCun) for tanh-like layers, 2/n2/n (He) for ReLU.

One layer, one variance calculation

Look at one pre-activation z=∑i=1nwixiz = \sum_{i=1}^{n} w_i x_i, where nn is the layer's fan-in (number of inputs). At initialization the weights are random, independent of each other and of the inputs, with mean 0 and variance Var(w)\mathrm{Var}(w). Each term wixiw_ix_i then has mean 0 and variance Var(w) E[xi2]\mathrm{Var}(w)\,\mathbb{E}[x_i^2], and variances of independent terms add:

Var(z)=n Var(w) E[x2].\mathrm{Var}(z) = n\,\mathrm{Var}(w)\,\mathbb{E}[x^2].

So one layer multiplies the signal's "power" by n Var(w)n\,\mathrm{Var}(w) (times whatever the activation does). Stack LL layers and you multiply by that factor LL times. With n=512n = 512 and weights drawn from a standard normal (Var(w)=1\mathrm{Var}(w) = 1), the variance grows 512× per layer: after a few layers you get overflow. With Var(w)=0.012\mathrm{Var}(w) = 0.01^2, it shrinks about 20× per layer, and after 10 layers the signal is essentially zero. Neither network can learn.

Choosing the scale

  • LeCun / Xavier (Glorot): for activations that behave like the identity near 0 (tanh, or none), make the factor 1 with Var(w)=1/nin\mathrm{Var}(w) = 1/n_{\text{in}}. Xavier compromises between the forward pass (fan-in) and the backward pass (fan-out) with Var(w)=2nin+nout\mathrm{Var}(w) = \frac{2}{n_{\text{in}}+n_{\text{out}}}.
  • He (Kaiming): ReLU zeroes the negative half of its input, so if zz is symmetric around 0, E[ReLU(z)2]=12Var(z)\mathbb{E}[\mathrm{ReLU}(z)^2] = \tfrac12\mathrm{Var}(z). Each ReLU layer halves the power, and to cancel that we double the weights' variance: Var(w)=2/nin\mathrm{Var}(w) = 2/n_{\text{in}}, i.e. standard deviation 2/nin\sqrt{2/n_{\text{in}}}.

The same argument runs backward. The gradient ∂L/∂x=W⊤ ∂L/∂z\partial L/\partial\mathbf{x} = W^\top\,\partial L/\partial\mathbf{z} sums over the fan-out, and each layer also multiplies in the activation's slopes (chapter 2). Get the scale wrong and gradients at the first layers explode or vanish, so those layers either diverge or never learn. That's the vanishing/exploding gradient problem, and good initialization is the first line of defence; normalization (chapter 6) and residual connections (chapter 7) are the other two.

Two more initialization rules

  • Never all equal. If every weight starts at the same value, every hidden neuron computes the same thing and receives the same gradient, so they stay identical forever. Randomness breaks the symmetry.
  • Check the loss at step 0. The output logits should start small, so the first predictions are nearly uniform and the loss is about ln⁡K\ln K (chapter 3). Karpathy shrinks the last layer's weights for exactly this reason.
A 20-layer network, 100 neurons wide, with random weights and a batch of random inputs. The gold line is the typical size (standard deviation) of each layer's activations; the purple line is the size of the gradient arriving at each layer during backprop. The vertical axis is logarithmic: each grid line is a factor of 10. Try each initialization with tanh and with ReLU. Only the matching scale keeps both lines flat.

Worked exampleHow fast does it blow up?

A ReLU network with fan-in n=256n = 256 per layer. He initialization uses standard deviation 2/256≈0.0884\sqrt{2/256} \approx 0.0884.

Suppose instead you use a round 0.1. The per-layer factor on the variance is n Var(w)⋅12=256⋅0.01⋅0.5=1.28n\,\mathrm{Var}(w)\cdot\tfrac12 = 256\cdot0.01\cdot0.5 = 1.28. After 20 layers: 1.2820≈1391.28^{20}\approx 139 for the variance, so the standard deviation grows by 139≈11.8\sqrt{139}\approx 11.8. A small-looking difference (0.1 vs 0.088) compounds into an order of magnitude. With 0.05 instead, the factor is 0.32 and after 20 layers the variance has shrunk by 0.3220≈1.3×10−100.32^{20}\approx 1.3\times10^{-10}.

Watch outCommon misconceptions

  • "Initialize with small random numbers, like 0.01." Small is not safe: in a deep network it makes the signal vanish. The right size depends on the fan-in.
  • "Zero initialization is neutral." All-zero (or all-equal) weights make every neuron identical forever. Biases can start at zero; weight matrices can't.
  • "He and Xavier are interchangeable." The factor 2 matters: Xavier on a deep ReLU network halves the variance at every layer (try it in the figure).
  • "Good initialization fixes training for good." It only gets the starting point right. As weights change, the scales drift, which is why normalization layers exist.

In ML & deep learningWhere this shows up

PyTorch's nn.Linear uses a uniform distribution scaled by 1/nin1/\sqrt{n_{\text{in}}} by default, and torch.nn.init.kaiming_normal_ gives He. GPT-2 initializes weights with standard deviation 0.02 and additionally shrinks the layers that write into the residual stream by 1/2L1/\sqrt{2L}, so that adding up 2L2L contributions (chapter 7) doesn't grow the variance with depth. Karpathy's makemore lecture measures these effects live with histograms.

Practice (pick one answer per question)

z=∑i=1100wixiz = \sum_{i=1}^{100} w_ix_i with independent zero-mean weights of variance 0.01 and inputs with E[x2]=1\mathbb{E}[x^2] = 1. What is Var(z)\mathrm{Var}(z)?

  1. 1
  2. 0.01
  3. 100
  4. 0.1

n Var(w) E[x2]=100⋅0.01⋅1=1n\,\mathrm{Var}(w)\,\mathbb{E}[x^2] = 100\cdot0.01\cdot1 = 1. That's LeCun initialization: variance 1/n1/n.

What standard deviation does He initialization use for a ReLU layer with fan-in 50?

  1. 0.2
  2. 0.04
  3. 0.14
  4. 0.02

2/50=0.04=0.2\sqrt{2/50} = \sqrt{0.04} = 0.2. (0.04 is the variance; 0.14 is 1/50\sqrt{1/50}, the LeCun value.)

What weight variance does Xavier (Glorot) initialization give a layer from 100 to 300 neurons?

  1. 0.005
  2. 0.01
  3. 0.02
  4. 0.0033

2nin+nout=2400=0.005\frac{2}{n_{\text{in}} + n_{\text{out}}} = \frac{2}{400} = 0.005. (0.01 uses only the fan-in; 0.0033 only the fan-out.)

A bad initialization multiplies the activation variance by 1.1 per layer. Roughly how much bigger is it after 50 layers?

  1. about 117 times
  2. about 5.5 times
  3. about 1.1 times
  4. about 55 times

Factors multiply: 1.150≈1171.1^{50} \approx 117. A 10% error per layer becomes two orders of magnitude. Adding instead of multiplying gives the 5.5 or 55 distractors.

Why does He initialization have a 2 in Var(w)=2/n\mathrm{Var}(w) = 2/n where LeCun has 1?

  1. ReLU zeroes about half its inputs, halving E[a2]\mathbb{E}[a^2], so the weights must double it back
  2. Because the backward pass is twice as expensive
  3. To average fan-in and fan-out
  4. Because ReLU's slope is 2 for positive inputs

For symmetric zz, E[ReLU(z)2]=12E[z2]\mathbb{E}[\mathrm{ReLU}(z)^2] = \tfrac12\mathbb{E}[z^2]: the negative half contributes nothing. To keep the signal power constant from layer to layer, the weights carry an extra factor of 2.

Every weight of a hidden layer is initialized to 0.5. What goes wrong?

  1. All hidden neurons compute the same value and get the same gradient, so they stay identical
  2. Nothing, as long as the learning rate is small
  3. The gradients are all exactly zero
  4. The activations explode immediately

Identical weights give identical outputs and identical gradients, so after every update the neurons are still identical: the layer acts like a single neuron. Random initialization breaks this symmetry. (The gradients aren't zero, just equal.)

A 10-layer ReLU network has fan-in 400 everywhere and weights with standard deviation 0.05. By roughly what factor has the activations' standard deviation changed after 10 layers?

  1. shrunk to about 0.031 times
  2. shrunk to about 0.001 times
  3. shrunk to about 0.5 times
  4. unchanged

Per-layer variance factor: n Var(w)⋅12=400⋅0.0025⋅0.5=0.5n\,\mathrm{Var}(w)\cdot\tfrac12 = 400\cdot0.0025\cdot0.5 = 0.5. After 10 layers the variance is 0.510≈0.0010.5^{10}\approx 0.001 times as big, and the standard deviation is the square root of that: 0.55=1/32≈0.0310.5^5 = 1/32\approx0.031. (He would use 2/400≈0.071\sqrt{2/400}\approx0.071.)

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 6

Normalization: batch norm and layer norm

Watch: makemore Part 3, the BatchNorm section (Andrej Karpathy) Watch: Let's build GPT, the layer norm section (Andrej Karpathy)

Instead of hoping activations keep a sensible scale, force it: subtract the mean and divide by the standard deviation, then let the network rescale with two learned parameters γ\gamma and β\beta. Batch norm computes the statistics for each feature across the examples in a batch; layer norm computes them for each example across its features. Same formula, different axis.

The formula

Given a group of numbers x1,…,xmx_1,\dots,x_m, compute their mean μ\mu and variance σ2\sigma^2, then

x^i=xi−μσ2+ε,yi=γ x^i+β.\hat x_i = \frac{x_i - \mu}{\sqrt{\sigma^2 + \varepsilon}}, \qquad y_i = \gamma\,\hat x_i + \beta.

The x^i\hat x_i have mean 0 and variance 1 (the small ε\varepsilon, like 10−510^{-5}, only prevents division by zero). Then γ\gamma (a learned scale) and β\beta (a learned shift) let the network choose any mean and spread it likes, including undoing the normalization entirely if that helps. The point is that the scale is now controlled by two parameters instead of being an accident of every weight upstream.

Which numbers form a group?

Activations in a batch form a table: one row per example, one column per feature (neuron).

  • Batch norm (BN) normalizes each column: for feature jj, the mean and variance are taken over the NN examples in the batch. So each example's output depends on which other examples happen to share its batch. At test time there may be just one example, so BN keeps running averages of μ\mu and σ2\sigma^2 during training and uses those instead. Train and test behave differently, a classic source of bugs.
  • Layer norm (LN) normalizes each row: for one example, the mean and variance are over its dd features. No dependence on the batch, identical behaviour in training and testing, and it works with batch size 1 and with sequences of any length. γ\gamma and β\beta are still per-feature vectors of length dd.
  • RMSNorm is layer norm without the mean subtraction: divide each row by its root-mean-square 1d∑xi2\sqrt{\frac1d\sum x_i^2}, then scale by γ\gamma. Slightly cheaper and works just as well; LLaMA and most recent LLMs use it.

Why it helps

Normalization keeps each layer's inputs at a predictable scale no matter how the weights upstream drift during training, so the variance argument of chapter 5 stays true all through training, not just at step 0. In practice that means you can use larger learning rates, deep networks train much more reliably, and initialization matters less. Layer norm also makes the output invariant to the scale of its input: multiply a whole row by 3 and LN's output is unchanged.

A batch of 4 examples (rows) × 5 features (columns), with features on very different scales. Switch between batch norm (each column normalized, outlined in gold) and layer norm (each row normalized). The right table is the result before γ and β; colour shows sign and size. The readout lists the mean and standard deviation of each group after normalizing: always 0 and 1. Press New batch and watch batch norm's output for row 1 change even though row 1's own numbers didn't.

Worked exampleLayer norm on one row

Row x=(2,4,6,8)\mathbf{x} = (2, 4, 6, 8). Mean μ=5\mu = 5. Deviations (−3,−1,1,3)(-3, -1, 1, 3), squared (9,1,1,9)(9, 1, 1, 9), so σ2=20/4=5\sigma^2 = 20/4 = 5 and σ=5≈2.236\sigma = \sqrt{5} \approx 2.236 (ignore ε\varepsilon).

x^=(−3,−1,1,3)/2.236≈(−1.342,−0.447,0.447,1.342)\hat{\mathbf{x}} = (-3, -1, 1, 3)/2.236 \approx (-1.342, -0.447, 0.447, 1.342). Check: mean 0, and the squares average to (1.8+0.2+0.2+1.8)/4=1(1.8 + 0.2 + 0.2 + 1.8)/4 = 1. With γ=2\gamma = 2 and β=1\beta = 1 (same for every feature here), the output is (−1.683,0.106,1.894,3.683)(-1.683, 0.106, 1.894, 3.683).

Note that (12,14,16,18)(12, 14, 16, 18) or (20,40,60,80)(20, 40, 60, 80) give exactly the same x^\hat{\mathbf{x}}: layer norm ignores the row's offset and overall scale.

Watch outCommon misconceptions

  • "Normalization makes every output have mean 0 and variance 1." Only x^\hat x does. After γ\gamma and β\beta the network can choose any scale and offset.
  • "Batch norm and layer norm normalize the same thing." BN normalizes each feature across the batch; LN normalizes each example across its features. In a table, columns versus rows.
  • "Batch norm behaves the same at test time." In training it uses the current batch's statistics; at test time it uses running averages. Forgetting model.eval() in PyTorch is a famous bug.
  • "Layer norm's γ\gamma is a single number." It's a vector with one scale per feature (and β\beta one shift per feature): 2d2d parameters for width dd.

In ML & deep learningWhere this shows up

Batch norm made very deep CNNs (like ResNet) practical in 2015. Transformers use layer norm (or RMSNorm) instead, because sequences vary in length, batches can be small, and generating text runs one example at a time. Modern transformers put the norm before each attention and MLP block ("pre-norm", chapter 11), plus one final norm before the output layer.

Practice (pick one answer per question)

Apply layer norm (no ε\varepsilon, γ=1\gamma=1, β=0\beta=0) to the row (1,3)(1, 3).

  1. (−1, 1)
  2. (0.25, 0.75)
  3. (−2, 2)
  4. (1, 3)

Mean 2, deviations (−1,1)(-1, 1), variance (1+1)/2=1(1+1)/2 = 1, standard deviation 1. So x^=(−1,1)\hat{\mathbf{x}} = (-1, 1). (0.25, 0.75) divides by the sum, which is a different operation.

Batch norm computes its mean and variance…

  1. for each feature, across the examples in the batch
  2. for each example, across its features
  3. over the whole batch and all features at once
  4. for each weight matrix, across its entries

BN works column by column: each feature gets its own mean and variance, computed over the batch. Per example, across features, is layer norm.

A feature takes the values 10, 20, 30 in a batch of 3. What does batch norm turn them into (no ε\varepsilon, γ=1\gamma=1, β=0\beta=0)?

  1. about (−1.22, 0, 1.22)
  2. (−1, 0, 1)
  3. (−10, 0, 10)
  4. about (−0.82, 0, 0.82)

Mean 20, deviations (−10,0,10)(-10, 0, 10), variance 200/3≈66.7200/3\approx66.7, standard deviation ≈8.165\approx8.165. Divide: ≈(−1.22,0,1.22)\approx(-1.22, 0, 1.22). Using the "sample" variance (divide by 2) would give exactly (−1,0,1)(-1, 0, 1), but normalization layers divide by NN.

After normalizing, one entry is x^=0.5\hat x = 0.5. Its γ=2\gamma = 2 and β=1\beta = 1. What does the layer output?

  1. 2
  2. 1.5
  3. 3
  4. 0.5

γx^+β=2⋅0.5+1=2\gamma\hat x + \beta = 2\cdot0.5 + 1 = 2.

Apply RMSNorm (γ=1\gamma=1) to (3,4)(3, 4).

  1. about (0.849, 1.131)
  2. (0.6, 0.8)
  3. (−1, 1)
  4. about (0.429, 0.571)

RMS =(9+16)/2=12.5≈3.536= \sqrt{(9+16)/2} = \sqrt{12.5} \approx 3.536. Divide: (0.849,1.131)(0.849, 1.131). No mean is subtracted, so the signs stay. (0.6, 0.8) divides by the Euclidean length 5 instead of the RMS.

Why do transformers use layer norm rather than batch norm?

  1. LN treats each token independently, so it works for any batch size and sequence length and behaves the same in training and generation
  2. LN has fewer parameters than BN
  3. BN can't be differentiated
  4. LN makes attention weights sum to 1

BN couples examples in a batch and needs running statistics at test time; for variable-length text, tiny batches and one-token-at-a-time generation that's awkward. LN only looks at one token's own vector. (Both have 2d2d parameters, and both are differentiable.)

Every entry of a row x\mathbf{x} is replaced by 3xi+53x_i + 5. What happens to the row's layer-norm output (γ=1\gamma=1, β=0\beta=0, ignoring ε\varepsilon)?

  1. Nothing: it is unchanged
  2. It is multiplied by 3
  3. It is shifted by 5
  4. It is multiplied by 3 and shifted by 5

The mean becomes 3μ+53\mu + 5 and the standard deviation 3σ3\sigma, so (3xi+5)−(3μ+5)3σ=xi−μσ\frac{(3x_i+5) - (3\mu+5)}{3\sigma} = \frac{x_i-\mu}{\sigma}. Layer norm removes any common shift and any positive overall scale. (A negative scale would flip the signs.)

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 7

Residual connections: why they make deep networks trainable

Watch: Let's build GPT, the residual connections section (Andrej Karpathy) Watch: Transformers, the tech behind LLMs (3Blue1Brown)

A residual block outputs its input plus a correction: y=x+F(x)\mathbf{y} = \mathbf{x} + F(\mathbf{x}). Its derivative is I+F′I + F' instead of just F′F', so the backward pass always has an identity "highway" through which the gradient reaches early layers undiminished. That one plus sign is why networks with hundreds of layers train.

The problem with plain depth

In a plain network, xl+1=Fl(xl)\mathbf{x}_{l+1} = F_l(\mathbf{x}_l), and the chain rule makes the gradient at layer 1 a product of LL Jacobians:

∂L∂x1=∂L∂xL+1 FL′ FL−1′⋯F1′.\frac{\partial L}{\partial \mathbf{x}_1} = \frac{\partial L}{\partial \mathbf{x}_{L+1}}\,F_L'\,F_{L-1}'\cdots F_1'.

Chapters 2 and 5 showed what products do: if each factor shrinks vectors a little, the gradient vanishes; if each grows them a little, it explodes. Even with good initialization, plain networks much deeper than ~20 layers trained worse than shallower ones, not because they overfit but because the optimizer couldn't make progress. That observation led to ResNet (2015).

Add the input back

A residual block computes xl+1=xl+Fl(xl)\mathbf{x}_{l+1} = \mathbf{x}_l + F_l(\mathbf{x}_l). The block only has to learn the residual, the change to make; doing nothing is as easy as F=0F = 0. Differentiate: the Jacobian is I+Fl′I + F_l'. Now the product becomes

∏l(I+Fl′)=I+∑lFl′+∑l>kFl′Fk′+…\prod_l (I + F_l') = I + \sum_l F_l' + \sum_{l\gt k} F_l'F_k' + \dots

Expanded, it contains the plain identity II: a path from the loss straight to layer 1 that skips every block. It also contains every subset of blocks: with LL blocks there are 2L2^L paths of all lengths, so a residual network behaves somewhat like an ensemble of many shallower networks. Even if every Fl′F_l' is small, the gradient doesn't vanish.

In one dimension it's easy to see. If each plain layer has slope 0.5, twenty layers give 0.520≈10−60.5^{20}\approx10^{-6}. If each residual block has F′=−0.5F' = -0.5, the block's slope is 1−0.5=0.51 - 0.5 = 0.5, the same disaster; but blocks whose F′F' is small and of either sign give factors like 0.95 or 1.05, whose product stays near 1.

The residual stream

Transformers take this idea to its conclusion. A vector for each token flows from the embedding to the output along the residual stream; every attention and MLP block reads from it (through a layer norm) and adds its output back: x←x+Block(LN(x))\mathbf{x} \leftarrow \mathbf{x} + \text{Block}(\mathrm{LN}(\mathbf{x})). Nothing is ever overwritten, only added to. That requires every block's output to have the same shape as its input, which is why the model width dd is the same in every layer.

A deep network of random tanh layers (32 neurons wide). The plot shows the size of the gradient reaching each layer, on a log scale (each grid line is a factor of 10), when the loss gradient at the top has size 1. Purple: plain layers x←tanh⁡(Wx)\mathbf{x}\leftarrow\tanh(W\mathbf{x}). Green: residual layers x←x+tanh⁡(Wx)\mathbf{x}\leftarrow\mathbf{x}+\tanh(W\mathbf{x}). Increase the depth and lower the weight scale: the plain gradient collapses while the residual one stays usable.

Worked exampleThree blocks, both ways

Take scalar blocks with Fl(x)=wlxF_l(x) = w_lx and w=(−0.5,0.2,−0.3)w = (-0.5, 0.2, -0.3).

  • Plain (x←wlxx \leftarrow w_lx): dx4/dx1=(−0.5)(0.2)(−0.3)=0.03dx_4/dx_1 = (-0.5)(0.2)(-0.3) = 0.03.
  • Residual (x←x+wlxx \leftarrow x + w_lx): dx4/dx1=(1−0.5)(1+0.2)(1−0.3)=0.5⋅1.2⋅0.7=0.42dx_4/dx_1 = (1-0.5)(1+0.2)(1-0.3) = 0.5\cdot1.2\cdot0.7 = 0.42.

Expanding the residual product: 1+(−0.5+0.2−0.3)+(−0.1+0.15−0.06)+0.03=1−0.6−0.01+0.03=0.421 + (-0.5+0.2-0.3) + (-0.1+0.15-0.06) + 0.03 = 1 - 0.6 - 0.01 + 0.03 = 0.42. The "1" is the skip-everything path, and the plain network's 0.03 is just the single path that goes through all three blocks.

Watch outCommon misconceptions

  • "Residual connections add parameters." The skip itself is a plain addition with no weights (unless shapes differ and a projection is needed).
  • "They help because the network can copy its input." Being able to start near the identity helps, but the main effect is on the gradient: the II in I+F′I + F' gives every layer a direct line to the loss.
  • "Residual networks can't have exploding gradients." Factors like 1+F′1 + F' can still compound if F′F' is consistently positive and big. That's why they're combined with normalization and careful initialization (GPT-2's 1/2L1/\sqrt{2L} scaling, chapter 5).
  • "F(x)F(\mathbf{x}) can have any shape." It must match x\mathbf{x} so the two can be added.

In ML & deep learningWhere this shows up

ResNet-152 (152 layers) won ImageNet in 2015 thanks to residual blocks. Every transformer is a residual network: GPT-3 has 96 layers, each adding attention and MLP outputs into a 12,288-dimensional residual stream. Interpretability research reads the residual stream as a shared "workspace" that blocks communicate through, which is the picture 3Blue1Brown uses too.

Practice (pick one answer per question)

A scalar residual block computes y=x+F(x)y = x + F(x), and at the current input F′(x)=−0.2F'(x) = -0.2. What is dy/dxdy/dx?

  1. 0.8
  2. −0.2
  3. 1.2
  4. 0.2

dy/dx=1+F′(x)=1−0.2=0.8dy/dx = 1 + F'(x) = 1 - 0.2 = 0.8. The 1 comes from the skip connection.

All the weights inside a residual block's FF are zero (and so are its biases). What does the block compute?

  1. The identity: y=x\mathbf{y} = \mathbf{x}
  2. Zero
  3. 2x2\mathbf{x}
  4. It is undefined

F(x)=0F(\mathbf{x}) = \mathbf{0}, so y=x+0=x\mathbf{y} = \mathbf{x} + \mathbf{0} = \mathbf{x}. A plain layer with zero weights would output zero and block everything.

A plain network has 20 layers, each with slope 0.5 (scalar picture). By what factor is the gradient at the first layer scaled?

  1. about 9.5×10−79.5\times10^{-7}
  2. 10
  3. 0.5
  4. about 0.0005

0.520=1/1048576≈9.5×10−70.5^{20} = 1/1048576 \approx 9.5\times10^{-7}. The early layers essentially receive no learning signal.

A residual network has 20 blocks, each with F′=0.05F' = 0.05. By what factor is the gradient at the first block scaled?

  1. about 2.65
  2. about 1.05
  3. about 2.0
  4. about 10−2610^{-26}

(1+0.05)20≈2.65(1 + 0.05)^{20} \approx 2.65. It neither vanishes nor explodes badly. (10−2610^{-26} would be the plain network, 0.05200.05^{20}.)

A block's FF maps a 512-dimensional vector to a 256-dimensional one. Can you add a skip connection x+F(x)\mathbf{x} + F(\mathbf{x}) directly?

  1. No: the shapes don't match, so you need a projection (e.g. a 256 × 512 matrix) on the skip path
  2. Yes, numpy broadcasting handles it
  3. Yes, if you use layer norm first
  4. No, skip connections only work in convolutional networks

Vector addition needs equal shapes. ResNet uses a learned linear projection on the skip path when dimensions change; transformers avoid the issue by keeping the width dd constant.

In a pre-norm transformer, how does each block change the residual stream x\mathbf{x}?

  1. x←x+Block(LN(x))\mathbf{x} \leftarrow \mathbf{x} + \text{Block}(\mathrm{LN}(\mathbf{x}))
  2. x←Block(LN(x))\mathbf{x} \leftarrow \text{Block}(\mathrm{LN}(\mathbf{x}))
  3. x←LN(x)+Block(x)\mathbf{x} \leftarrow \mathrm{LN}(\mathbf{x}) + \text{Block}(\mathbf{x})
  4. x←x⋅Block(x)\mathbf{x} \leftarrow \mathbf{x}\cdot\text{Block}(\mathbf{x})

The block reads a normalized copy and adds its output. The stream itself is never normalized or replaced in place, so the identity path stays clean all the way down.

Expanding ∏l=1L(1+Fl′)\prod_{l=1}^{L}(1 + F_l') gives one term per path the gradient can take (through each block, or around it). How many paths are there for L=10L = 10 blocks?

  1. 1024
  2. 10
  3. 11
  4. 100

Each block is either used (Fl′F_l') or skipped (1), independently: 210=10242^{10} = 1024 paths. Most are short, which is part of why residual networks act like ensembles of shallower networks.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 8

Convolution as a linear map: sliding dot products and weight sharing

Watch: But what is a convolution? (3Blue1Brown)

A convolution slides a small kernel along the input and takes a dot product at every position. It is a linear map, so it could be written as a matrix, but a very special one: each row is the same few weights shifted along by one. Locality (each output looks at a small window) and weight sharing (the same weights everywhere) make it a dense layer with almost all its parameters removed.

Sliding dot products

Take a signal x=(x0,…,xn−1)\mathbf{x} = (x_0, \dots, x_{n-1}) and a kernel k=(k0,…,km−1)\mathbf{k} = (k_0, \dots, k_{m-1}) with mm much smaller than nn. The output at position ii is the dot product of the kernel with the window of x\mathbf{x} starting at ii:

yi=∑j=0m−1kj xi+j,i=0,1,…,n−m.y_i = \sum_{j=0}^{m-1} k_j\,x_{i+j}, \qquad i = 0, 1, \dots, n-m.

That's n−m+1n - m + 1 outputs (a "valid" convolution, no padding). The kernel decides what each output detects: (13,13,13)(\tfrac13,\tfrac13,\tfrac13) averages (blurs), (−1,1)(-1, 1) measures change (edges), (−1,2,−1)(-1, 2, -1) responds to spikes. In deep learning the kernel isn't designed by hand. It's learned by backprop like any other weights.

(A pedantic note: mathematicians, and 3Blue1Brown's video, define convolution with the kernel flipped, ∑jkj xi−j\sum_j k_j\,x_{i-j}. What deep-learning libraries compute is technically cross-correlation, unflipped. Since the kernel is learned, the network just learns the flipped version, and nobody minds.)

It's a matrix, a very sparse one

Every yiy_i is a fixed linear combination of the xx's, so y=Kx\mathbf{y} = K\mathbf{x} for some (n−m+1)×n(n-m+1)\times n matrix KK. For k=(k0,k1,k2)\mathbf{k} = (k_0,k_1,k_2) and n=5n = 5:

K=[k0k1k2000k0k1k2000k0k1k2].K = \begin{bmatrix} k_0 & k_1 & k_2 & 0 & 0\\ 0 & k_0 & k_1 & k_2 & 0\\ 0 & 0 & k_0 & k_1 & k_2\end{bmatrix}.

Two things are special. Locality: each row is zero outside a window of width mm. Weight sharing: every row holds the same mm numbers, shifted. A dense layer from 1,000 inputs to 998 outputs has about a million weights; the convolution doing the same shape has 3. A matrix whose diagonals are constant like this is called a Toeplitz matrix.

Weight sharing also gives shift equivariance: shift the input one step to the right and the output shifts one step to the right too. A cat detector learned in one corner of an image works in every corner.

Sizes, padding, stride, channels

  • Padding pp adds pp zeros at each end; stride ss moves the window ss steps at a time. Output length: ⌊n+2p−ms⌋+1\left\lfloor\frac{n + 2p - m}{s}\right\rfloor + 1.
  • Images: the kernel is a small 2D patch (say 3 × 3) sliding in both directions. With CinC_{\text{in}} input channels (red, green, blue, or earlier feature maps), one output channel uses a Cin×3×3C_{\text{in}}\times3\times3 kernel and sums over all of them. A layer with CoutC_{\text{out}} output channels has Cout⋅Cin⋅3⋅3C_{\text{out}}\cdot C_{\text{in}}\cdot3\cdot3 weights plus CoutC_{\text{out}} biases.
  • Receptive field: stacking convolutions lets later layers see further. Two 3-wide layers see 5 inputs; LL of them see 2L+12L+1.
Top: the input signal. Bottom: the output of a valid convolution with the kernel you type into the boxes (or pick a preset). Drag the gold marker on the output: the highlighted window on the input is what gets dotted with the kernel, and the readout shows the sum term by term. Try edge on the step signal: the output is zero on flat stretches and spikes at the jump.

Worked exampleTwo kernels on a ramp

x=(1,2,3,4,5)\mathbf{x} = (1, 2, 3, 4, 5), n=5n = 5.

  • Kernel (1,0,−1)(1, 0, -1): y0=1−3=−2y_0 = 1 - 3 = -2, y1=2−4=−2y_1 = 2 - 4 = -2, y2=3−5=−2y_2 = 3 - 5 = -2. Three outputs (5−3+15-3+1), all −2-2: this kernel measures the slope (times −2), and a ramp has the same slope everywhere.
  • Kernel (13,13,13)(\tfrac13, \tfrac13, \tfrac13): (2,3,4)(2, 3, 4), the moving average.

As a matrix, the first is K=[10−100010−100010−1]K = \begin{bmatrix}1&0&-1&0&0\\0&1&0&-1&0\\0&0&1&0&-1\end{bmatrix} with 9 nonzero entries and only 3 distinct parameters.

Watch outCommon misconceptions

  • "A convolution layer is nonlinear." The convolution itself is linear (a matrix). The nonlinearity comes from the activation applied afterwards.
  • "Each output position has its own kernel." That would be a "locally connected" layer. Convolution shares one kernel across all positions; that's the whole point.
  • "The output has the same length as the input." Only with the right padding ("same" padding p=(m−1)/2p = (m-1)/2 for odd mm, stride 1). A valid convolution shrinks it by m−1m - 1.
  • "Convolution is invariant to shifts." It's equivariant: the output moves with the input. Invariance comes later, from pooling or global averaging.

In ML & deep learningWhere this shows up

Convolutional neural networks (LeNet, AlexNet, ResNet) dominated computer vision for a decade, and still power many vision and audio models. 1D convolutions appear in speech models (WaveNet), and some language-model variants use short causal convolutions inside their blocks. Even Vision Transformers start by cutting an image into patches with what is effectively a strided convolution.

Practice (pick one answer per question)

A signal of length 10 is convolved with a kernel of length 3: no padding, stride 1. How long is the output?

  1. 8
  2. 10
  3. 7
  4. 12

n−m+1=10−3+1=8n - m + 1 = 10 - 3 + 1 = 8: the window has 8 starting positions.

What is the valid convolution of x=(0,0,1,1,1)\mathbf{x} = (0, 0, 1, 1, 1) with k=(−1,1)\mathbf{k} = (-1, 1)?

  1. (0, 1, 0, 0)
  2. (0, −1, 0, 0)
  3. (0, 0, 1, 1)
  4. (0, 1, 0, 0, 0)

yi=−xi+xi+1y_i = -x_i + x_{i+1}: (0,1,0,0)(0, 1, 0, 0). The kernel fires exactly where the signal steps up. Flipping the kernel (true convolution) gives the −1 version.

A 2D conv layer has 3 × 3 kernels, 16 input channels and 32 output channels, with biases. How many parameters?

  1. 4,640
  2. 4,608
  3. 288
  4. 9,248

Weights: 32⋅16⋅3⋅3=460832\cdot16\cdot3\cdot3 = 4608. Biases: 32. Total 4,640. Note it doesn't depend on the image size at all.

Input width 32, kernel 5, padding 2, stride 2. What is the output width?

  1. 16
  2. 14
  3. 15
  4. 32

⌊(32+2⋅2−5)/2⌋+1=⌊31/2⌋+1=15+1=16\lfloor(32 + 2\cdot2 - 5)/2\rfloor + 1 = \lfloor31/2\rfloor + 1 = 15 + 1 = 16. Stride 2 roughly halves the size.

A kernel of length 3 is applied validly to signals of length 5, written as y=Kx\mathbf{y} = K\mathbf{x}. What shape is KK and how many of its entries can be nonzero?

  1. 3 × 5, with 9 possibly nonzero entries
  2. 5 × 5, with 15 nonzero entries
  3. 5 × 3, with 9 nonzero entries
  4. 3 × 3, all 9 nonzero

3 outputs, 5 inputs, so KK is 3 × 5. Each row holds the 3 kernel values at a shifted position: 3⋅3=93\cdot3 = 9 entries, yet only 3 distinct parameters.

You shift an image 4 pixels to the right and run it through a conv layer (stride 1, ignoring the borders). How does the output feature map change?

  1. It shifts 4 pixels to the right too
  2. It doesn't change
  3. It changes unpredictably
  4. It shifts 4 pixels to the left

The same kernel is applied everywhere, so whatever it found at position ii it now finds at i+4i + 4. This is shift equivariance.

You stack 4 convolution layers, each with kernel size 3 and stride 1. How many input positions can one final output depend on (its receptive field)?

  1. 9
  2. 12
  3. 81
  4. 7

Each layer widens the view by m−1=2m - 1 = 2: 3, 5, 7, 9. In general 1+L(m−1)=1+4⋅2=91 + L(m-1) = 1 + 4\cdot2 = 9. In 2D, two stacked 3 × 3 layers see as far as one 5 × 5 layer with fewer weights (18 vs 25 per channel pair) and an extra nonlinearity, one reason VGG used 3 × 3 kernels throughout.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 9

Embeddings: words as vectors

Watch: Transformers, the tech behind LLMs: the embedding section (3Blue1Brown) Watch: Word Embedding and Word2Vec (StatQuest)

A network can't multiply a word, so each token in the vocabulary gets its own learned vector, stored as one row of an embedding matrix. Training arranges these vectors so that geometry carries meaning: similar words point in similar directions (measured by the dot product or cosine similarity), and some relationships become consistent directions you can add and subtract.

Lookup is a matrix product

Text is first split into tokens (words or word pieces), each with an integer id from 0 to V−1V-1, where VV is the vocabulary size. The embedding matrix EE has shape V×dV\times d: row ii is the dd-dimensional vector for token ii. Looking up token ii means taking row ii.

Mathematically that's a matrix product. Write the token as a one-hot vector ei\mathbf{e}_i (all zeros except a 1 in position ii); then ei⊤E\mathbf{e}_i^\top E is exactly row ii. So the embedding layer is a linear layer applied to one-hot inputs, and its rows are trained by backprop like any weights. (Code uses indexing, E[ids], because multiplying by a mostly-zero vector would be wasteful.)

Similarity is a dot product

How alike are two embeddings u,v\mathbf{u}, \mathbf{v}? The dot product u⋅v=∥u∥∥v∥cos⁡θ\mathbf{u}\cdot\mathbf{v} = \|\mathbf{u}\|\|\mathbf{v}\|\cos\theta (Linear Algebra chapter 9) mixes two things: lengths and angle. Dividing out the lengths leaves the cosine similarity

cos⁡θ=u⋅v∥u∥ ∥v∥∈[−1,1].\cos\theta = \frac{\mathbf{u}\cdot\mathbf{v}}{\|\mathbf{u}\|\,\|\mathbf{v}\|} \in [-1, 1].

1 means the same direction, 0 means perpendicular (unrelated), −1 opposite. Search engines and retrieval-augmented LLMs rank documents by exactly this number.

Directions carry meaning

Why would training produce meaningful geometry? Word2vec trained vectors so that a word's vector predicts the words appearing near it. Words used in similar contexts ("cat", "dog") end up with similar vectors. More surprisingly, consistent relationships become consistent offsets: the arrow from "man" to "woman" is roughly the same as from "king" to "queen", so

vking−vman+vwoman≈vqueen.\mathbf{v}_{\text{king}} - \mathbf{v}_{\text{man}} + \mathbf{v}_{\text{woman}} \approx \mathbf{v}_{\text{queen}}.

The analogy only holds approximately, and only for some relationships, but it shows that directions in embedding space can encode concepts like gender, plurality or country → capital. In a transformer the embedding is just the starting point: attention layers (chapter 10) then move each token's vector so that it soaks up meaning from context ("bank" by a river vs at a bank).

Lots of room in high dimensions

Real embeddings are wide: GPT-2 small uses d=768d = 768, GPT-3 uses 12,288. In high dimensions, random directions are almost perpendicular to each other: the cosine between two random unit vectors is typically about 1/d1/\sqrt{d}. So a space with a few thousand dimensions can hold vastly more than a few thousand nearly independent directions, which is one reason models can represent so many concepts (3Blue1Brown returns to this in chapter 12's video).

A toy 2D embedding space. Drag the purple query vector q around: the readout ranks every word by cosine similarity to q (only the direction matters, not the length). Drag the words too. Tick analogy to draw king − man + woman and see which word lands closest.

Worked exampleCosine similarity and an analogy

u=(1,2)\mathbf{u} = (1, 2), v=(2,1)\mathbf{v} = (2, 1): u⋅v=4\mathbf{u}\cdot\mathbf{v} = 4, ∥u∥=∥v∥=5\|\mathbf{u}\| = \|\mathbf{v}\| = \sqrt{5}, so cos⁡θ=4/5=0.8\cos\theta = 4/5 = 0.8 (about 37°). And (3,6)(3, 6) has cosine 1 with (1,2)(1, 2): same direction, different length.

Toy embeddings: man = (1, 0), woman = (1, 1), king = (3, 0). Then king − man + woman = (3, 1). If queen = (3, 1.1) and prince = (2.8, −0.3), the cosine of (3, 1) with queen is 9+1.110 10.21≈0.9996\frac{9 + 1.1}{\sqrt{10} \,\sqrt{10.21}}\approx 0.9996, while with prince it is 8.4−0.310 7.93≈0.910\frac{8.4 - 0.3}{\sqrt{10} \,\sqrt{7.93}}\approx 0.910. Queen wins.

Watch outCommon misconceptions

  • "Each dimension means one thing (dimension 7 = gender)." Meaningful directions are usually combinations of many coordinates. Rotate the whole space and the model works just as well.
  • "Embeddings are fixed dictionary entries." They're learned parameters, trained together with the rest of the network for its task.
  • "Dot product and cosine similarity are the same." Only for unit vectors. Long vectors get big dot products even at a wider angle.
  • "king − man + woman lands exactly on queen." It lands near it, and the analogy benchmarks usually exclude the three input words from the search, since the nearest vector is often king itself.

In ML & deep learningWhere this shows up

Every language model starts with an embedding lookup and (often) ends with the unembedding: logits are dot products of the final vector with every token's embedding, logits=hE⊤\text{logits} = \mathbf{h}E^\top, then softmax (chapter 3). GPT-2 reuses the same matrix for both ("tied weights"). The embedding matrix is big: V⋅dV\cdot d parameters. Recommender systems embed users and items, and image–text models like CLIP put pictures and captions in one space where matching pairs have high cosine similarity.

Practice (pick one answer per question)

EE is a V×dV\times d embedding matrix and e3\mathbf{e}_3 is the one-hot vector for token 3. What is e3⊤E\mathbf{e}_3^\top E?

  1. Row 3 of EE
  2. Column 3 of EE
  3. The sum of all rows of EE
  4. A V×dV\times d matrix

Multiplying by a one-hot row vector picks out one row: the embedding of token 3, a vector of length dd.

What is the cosine similarity of (1,0)(1, 0) and (0,1)(0, 1)?

  1. 0
  2. 1
  3. −1
  4. 0.5

The dot product is 0, so the cosine is 0: perpendicular, "unrelated".

What is the cosine similarity of (3,4)(3, 4) and (4,3)(4, 3)?

  1. 0.96
  2. 24
  3. 0.75
  4. 1

Dot product 12+12=2412 + 12 = 24; both lengths are 5; cosine =24/25=0.96= 24/25 = 0.96. Close, but not the same direction.

A model has a vocabulary of 50,000 tokens and width d=512d = 512. How many parameters does its embedding matrix have?

  1. 25.6 million
  2. 50,512
  3. 2.56 million
  4. 256 million

V⋅d=50000⋅512=25,600,000V\cdot d = 50000\cdot512 = 25{,}600{,}000. One 512-number vector per token.

Toy embeddings: man = (1, 0), woman = (1, 1), king = (3, 0). Candidates: queen = (3, 1.1), prince = (2.8, −0.3), woman = (1, 1). Excluding the three input words, which candidate has the highest cosine similarity with king − man + woman?

  1. queen
  2. prince
  3. none: the result is exactly king
  4. they tie

king − man + woman = (3, 1). Cosine with queen ≈ 0.9996, with prince ≈ 0.910 (see the worked example). Queen.

Why do retrieval systems usually compare embeddings by cosine similarity rather than the raw dot product?

  1. The raw dot product also grows with vector length, which can reflect things like word frequency rather than meaning
  2. The dot product can't be computed for long vectors
  3. Cosine similarity is faster to compute
  4. The dot product is always zero for different words

u⋅v=∥u∥∥v∥cos⁡θ\mathbf{u}\cdot\mathbf{v} = \|\mathbf{u}\|\|\mathbf{v}\|\cos\theta. Normalizing removes the length factors and compares directions only. (If vectors are normalized to length 1 in advance, the two coincide, and that's what systems often do.)

Two random unit vectors in d=10,000d = 10{,}000 dimensions (each coordinate random with mean 0). What is their cosine similarity typically?

  1. about ±0.01
  2. about ±0.5
  3. exactly 0
  4. about ±0.0001

The dot product is a sum of dd independent terms, each with variance 1/d21/d^2, so its variance is 1/d1/d and its typical size is 1/d=0.011/\sqrt{d} = 0.01. Random directions in high dimensions are nearly, but not exactly, perpendicular.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 10

Attention: queries, keys, values, and why we divide by √d

Watch: Attention in transformers, step-by-step (3Blue1Brown) Watch: Let's build GPT, the self-attention section (Andrej Karpathy)

Attention lets every token gather information from other tokens. Each token emits a query ("what am I looking for?"), a key ("what do I contain?") and a value ("what will I pass on?"). Query–key dot products, scaled by 1/dk1/\sqrt{d_k} and softmaxed, decide how much of each value a token receives. The whole thing is three matrix products and a softmax: softmax(QK⊤/dk) V\mathrm{softmax}(QK^\top/\sqrt{d_k})\,V.

Three projections

Stack the TT token vectors of a sequence as the rows of XX (shape T×dT\times d). Three learned matrices project every token at once:

Q=XWQ,K=XWK,V=XWV,Q = XW_Q,\quad K = XW_K,\quad V = XW_V,

with WQ,WKW_Q, W_K of shape d×dkd\times d_k and WVW_V of shape d×dvd\times d_v. Row ii of QQ is token ii's query, row jj of KK is token jj's key, row jj of VV its value. 3Blue1Brown's example: a noun's query might ask "are there adjectives in front of me?", and an adjective's key answers "yes, I'm an adjective"; their dot product is large, so the noun attends to the adjective and absorbs its value, which nudges "creature" toward "fluffy blue creature".

Scores, weights, output

The relevance of token jj to token ii is the dot product qi⋅kj\mathbf{q}_i\cdot\mathbf{k}_j: all of them together form the T×TT\times T matrix QK⊤QK^\top. Each row is turned into weights that are positive and sum to 1 with a softmax (chapter 3), and the output for token ii is the weighted average of the values:

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V.\mathrm{Attention}(Q,K,V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V.

Row ii of the weight matrix AA says where token ii looks; the output row ii is ∑jAijvj\sum_j A_{ij}\mathbf{v}_j. In a transformer this output is then added to the token's vector in the residual stream (chapters 7 and 11).

Why divide by √dk?

Suppose the entries of q\mathbf{q} and k\mathbf{k} are independent with mean 0 and variance 1 (roughly what normalization and good initialization give). Then q⋅k=∑m=1dkqmkm\mathbf{q}\cdot\mathbf{k} = \sum_{m=1}^{d_k} q_mk_m is a sum of dkd_k terms of variance 1, so its variance is dkd_k and its typical size is dk\sqrt{d_k}. With dk=64d_k = 64, scores of ±8 or ±16 are normal. Softmax of numbers that far apart is essentially one-hot: one token gets all the weight, and the gradient through softmax nearly vanishes (it is saturated, just like a sigmoid). Dividing by dk\sqrt{d_k} brings the scores back to variance 1, so attention starts out soft and trainable whatever the head size.

The causal mask

A language model predicts the next token, so token ii must not peek at tokens after it. Before the softmax, set every score with j>ij\gt i to −∞-\infty. Then e−∞=0e^{-\infty} = 0: those positions get exactly zero weight, and each row still sums to 1 over the allowed tokens. The weight matrix becomes lower-triangular. Token 1 can only attend to itself; token TT can see everything.

A five-token sentence. Each token has a 2D query and key (pick a token with the buttons, then drag its purple query and the gold keys). The heatmap shows every token's attention weights (row = who is looking, column = who is looked at). Toggle the causal mask to blank the future, and ÷√d to switch the scaling. Make the vectors longer with the slider and watch rows become one-hot.
Why the √d. One query and eight keys with random entries (mean 0, variance 1) in dd dimensions. The bars are the softmax weights. Raise dd without scaling: the scores spread out like d\sqrt{d} and one key takes almost everything. Turn on ÷√d and the weights stay spread out at any dd. Press New vectors to resample.

Worked exampleOne query, three keys

dk=2d_k = 2. Query q=(1,1)\mathbf{q} = (1, 1); keys k1=(1,0)\mathbf{k}_1 = (1, 0), k2=(0,2)\mathbf{k}_2 = (0, 2), k3=(−1,0)\mathbf{k}_3 = (-1, 0); values v1=(1,0)\mathbf{v}_1 = (1, 0), v2=(0,1)\mathbf{v}_2 = (0, 1), v3=(1,1)\mathbf{v}_3 = (1, 1).

  • Scores q⋅kj=(1,2,−1)\mathbf{q}\cdot\mathbf{k}_j = (1, 2, -1); divided by 2\sqrt{2}: (0.707,1.414,−0.707)(0.707, 1.414, -0.707).
  • Softmax: e0.707≈2.028e^{0.707}\approx2.028, e1.414≈4.113e^{1.414}\approx4.113, e−0.707≈0.493e^{-0.707}\approx0.493; total 6.6346.634; weights ≈(0.306,0.620,0.074)\approx(0.306, 0.620, 0.074).
  • Output: 0.306 (1,0)+0.620 (0,1)+0.074 (1,1)≈(0.380,0.694)0.306\,(1,0) + 0.620\,(0,1) + 0.074\,(1,1) \approx (0.380, 0.694).

Without the scaling, the weights would be softmax(1,2,−1)≈(0.259,0.705,0.035)\mathrm{softmax}(1, 2, -1)\approx(0.259, 0.705, 0.035): already more peaked, and the effect grows with dkd_k.

Watch outCommon misconceptions

  • "Attention weights are symmetric." qi⋅kj≠qj⋅ki\mathbf{q}_i\cdot\mathbf{k}_j \ne \mathbf{q}_j\cdot\mathbf{k}_i in general, because queries and keys come from different matrices. "The noun attends to the adjective" doesn't imply the reverse.
  • "We divide by dkd_k." By its square root: the standard deviation of the score grows like dk\sqrt{d_k}, not dkd_k.
  • "The mask sets future weights to 0 after the softmax." Zeroing afterwards would leave rows that don't sum to 1. The mask adds −∞-\infty to the scores before the softmax.
  • "Attention has a fixed window." Every token can attend to every allowed token, near or far. The cost is the T×TT\times T score matrix: quadratic in sequence length.

In ML & deep learningWhere this shows up

This formula is the core of every transformer: GPT, BERT, LLaMA, Vision Transformers, Whisper. PyTorch has it as F.scaled_dot_product_attention, and FlashAttention computes it in blocks so that the T×TT\times T matrix never sits in memory at once. In self-attention QQ, KK, VV all come from the same sequence; in cross-attention (translation, image captioning) the queries come from one sequence and the keys and values from another.

Practice (pick one answer per question)

QQ and KK both have shape T×dkT\times d_k. What shape is QK⊤QK^\top?

  1. T×TT\times T
  2. dk×dkd_k\times d_k
  3. T×dkT\times d_k
  4. 1×11\times1

(T×dk)(dk×T)=T×T(T\times d_k)(d_k\times T) = T\times T: one score for every (query token, key token) pair.

With a causal mask, which tokens can token 3 (counting from 1) attend to?

  1. Tokens 1, 2 and 3
  2. Only token 3
  3. Tokens 3 onwards
  4. Tokens 1 and 2 only

The mask blocks positions j>ij\gt i. Token 3 sees itself and everything before it.

A head has dk=64d_k = 64. What are the scores divided by?

  1. 8
  2. 64
  3. 32
  4. 4096

64=8\sqrt{64} = 8.

q,k\mathbf{q}, \mathbf{k} have d=16d = 16 independent entries, each with mean 0 and variance 1. What is the standard deviation of q⋅k\mathbf{q}\cdot\mathbf{k}?

  1. 4
  2. 16
  3. 1
  4. 256

Each product qmkmq_mk_m has variance 1⋅1=11\cdot1 = 1; 16 independent ones add to variance 16, standard deviation 4. Dividing by 16=4\sqrt{16} = 4 brings it back to 1.

A row of scores is (2,2,−∞)(2, 2, -\infty) after masking. What are the attention weights?

  1. (0.5, 0.5, 0)
  2. (1/3, 1/3, 1/3)
  3. (1, 1, 0)
  4. (0.5, 0.5, −∞)

e2,e2,e−∞=0e^2, e^2, e^{-\infty} = 0; normalized: (0.5,0.5,0)(0.5, 0.5, 0). The masked position disappears and the rest still sum to 1.

Token ii has scores (0,ln⁡3)(0, \ln 3) against two tokens (already scaled) whose values are v1=(4,0)\mathbf{v}_1 = (4, 0) and v2=(0,4)\mathbf{v}_2 = (0, 4). What is its attention output?

  1. (1, 3)
  2. (2, 2)
  3. (3, 1)
  4. (0, 4)

Weights: softmax(0,ln⁡3)=(1/4,3/4)\mathrm{softmax}(0, \ln 3) = (1/4, 3/4). Output: 14(4,0)+34(0,4)=(1,3)\tfrac14(4, 0) + \tfrac34(0, 4) = (1, 3).

Without the 1/dk1/\sqrt{d_k} scaling, what goes wrong when dkd_k is large?

  1. Scores get large, softmax saturates to nearly one-hot, and its gradients become tiny
  2. The scores all become nearly equal, so attention is uniform
  3. The weights no longer sum to 1
  4. Nothing: softmax only depends on differences between scores

Softmax does depend only on differences, but those differences are what grow: their spread scales like dk\sqrt{d_k}. Large gaps make softmax nearly one-hot, where its slopes are nearly 0 (as in the figure). Scaling keeps the score variance near 1 for any head size.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 11

Multi-head attention and the transformer block

Watch: Let's build GPT: from scratch, in code, spelled out (Andrej Karpathy) Watch: Attention in transformers, the multi-head section (3Blue1Brown)

Instead of one big attention, a transformer runs hh smaller ones in parallel, each on its own slice of d/hd/h dimensions, then concatenates the results and mixes them with one more matrix. A block is: layer norm → multi-head attention → add to the residual stream; layer norm → MLP → add to the residual stream. Stack that block dozens of times and you have GPT.

Many heads, same cost

A single attention head can only produce one weighting per token: one "question". But a token may need several kinds of information at once: the previous word, the subject of the sentence, the matching bracket. Multi-head attention runs hh heads side by side. With model width dd, each head uses dk=d/hd_k = d/h dimensions, so the total cost equals that of one full-width head.

In code it's a reshape. Compute Q=XWQQ = XW_Q as usual (shape T×dT\times d), then view the dd columns as hh groups of d/hd/h:

(T, d)  →  (T, h, d/h)  →  (h, T, d/h)(with a batch: (B,T,d)→(B,h,T,d/h)).(T,\ d) \;\to\; (T,\ h,\ d/h) \;\to\; (h,\ T,\ d/h)\quad\text{(with a batch: } (B, T, d)\to(B, h, T, d/h)\text{)}.

Do the same for KK and VV, run attention independently in each of the hh slices (a batched matrix product), then undo the reshape, putting the heads' outputs side by side again as T×dT\times d, and multiply by an output matrix WOW_O (d×dd\times d) that mixes information across heads:

MHA(X)=Concat(head1,…,headh) WO,headi=Attention(XWQ(i),XWK(i),XWV(i)).\mathrm{MHA}(X) = \mathrm{Concat}(\text{head}_1,\dots,\text{head}_h)\,W_O,\qquad \text{head}_i = \mathrm{Attention}(XW_Q^{(i)}, XW_K^{(i)}, XW_V^{(i)}).

Parameters: WQ,WK,WV,WOW_Q, W_K, W_V, W_O are each d×dd\times d, so 4d24d^2 (plus biases), independent of hh.

The block

A modern ("pre-norm") transformer block updates the residual stream XX (one row per token) in two steps:

X←X+MHA(LN(X)),X←X+MLP(LN(X)).X \leftarrow X + \mathrm{MHA}(\mathrm{LN}(X)),\qquad X \leftarrow X + \mathrm{MLP}(\mathrm{LN}(X)).

Attention is where tokens communicate: it's the only step that mixes information between positions. The MLP, GELU(XW1+b1)W2+b2\mathrm{GELU}(XW_1+\mathbf{b}_1)W_2+\mathbf{b}_2 with a hidden width of usually 4d4d, is where each token computes on its own, separately and identically at every position (chapter 1). Layer norms (chapter 6) keep the inputs of each sublayer well scaled; the residual additions (chapter 7) keep gradients flowing through dozens of blocks.

Counting a GPT

Per block: attention 4d24d^2, MLP d⋅4d+4d⋅d=8d2d\cdot4d + 4d\cdot d = 8d^2, so about 12d212d^2 (biases and layer norms add only a few thousand). A model with LL blocks has about 12Ld212Ld^2 parameters, plus the embeddings (chapter 9). GPT-2 small (d=768d = 768, L=12L = 12, vocabulary 50,257, 1,024 positions) has 12⋅12⋅7682≈84.912\cdot12\cdot768^2\approx 84.9M block parameters and about 39.4M embedding parameters, roughly 124M in all.

Six tokens with width d=12d = 12 (each row of the top grid is a token's query vector). Choose the number of heads: the columns are split into hh groups of d/hd/h, and each group produces its own 6 × 6 attention pattern (below), computed from its own slice. Different heads look at different things. Toggle the causal mask. The readout tracks the shapes through the reshape.

Worked exampleShapes through one block

Batch B=2B = 2, sequence T=10T = 10, width d=64d = 64, heads h=4h = 4 (so dk=16d_k = 16).

  • Input XX: (2,10,64)(2, 10, 64). After LN: same shape.
  • Q,K,VQ, K, V: each (2,10,64)(2, 10, 64), reshaped to (2,4,10,16)(2, 4, 10, 16).
  • Scores QK⊤/16QK^\top/\sqrt{16}: (2,4,10,10)(2, 4, 10, 10), one 10 × 10 matrix per example per head. After softmax, times VV: (2,4,10,16)(2, 4, 10, 16).
  • Merge heads: (2,10,64)(2, 10, 64); times WOW_O: (2,10,64)(2, 10, 64); add to XX.
  • MLP: (2,10,64)→(2,10,256)→(2,10,64)(2, 10, 64)\to(2, 10, 256)\to(2, 10, 64); add to XX.

Parameters (no biases): attention 4⋅642=16,3844\cdot64^2 = 16{,}384, MLP 8⋅642=32,7688\cdot64^2 = 32{,}768.

Watch outCommon misconceptions

  • "More heads means more parameters." With dk=d/hd_k = d/h, the four d×dd\times d matrices are the same size for any hh. Heads just partition them.
  • "Reshape (T,d)(T, d) straight to (h,T,d/h)(h, T, d/h)." A plain reshape would scramble tokens and features. You must reshape to (T,h,d/h)(T, h, d/h) and then transpose to (h,T,d/h)(h, T, d/h).
  • "The MLP mixes tokens." It's applied to each token on its own. Only attention moves information between positions.
  • "The block replaces the token vectors." It adds to them. Each sublayer writes a change into the residual stream.

In ML & deep learningWhere this shows up

GPT-3 has 96 blocks with d=12,288d = 12{,}288 and 96 heads of size 128; 12⋅96⋅122882≈17412\cdot96\cdot12288^2\approx174B of its 175B parameters are in the blocks. Interpretability work has found heads with specific jobs, like "previous token" heads and "induction" heads that copy patterns. Newer models share keys and values across groups of heads (grouped-query attention) to save memory during generation.

Practice (pick one answer per question)

A model has width d=512d = 512 and h=8h = 8 heads. What is the head size dkd_k?

  1. 64
  2. 512
  3. 4096
  4. 8

d/h=512/8=64d/h = 512/8 = 64.

Which sublayer of a transformer block moves information between different token positions?

  1. Attention
  2. The MLP
  3. Layer norm
  4. The residual addition

The MLP and layer norm act on each token separately, and the residual addition is per token too. Only attention combines different positions.

How many weights (no biases) do WQ,WK,WV,WOW_Q, W_K, W_V, W_O hold together when d=512d = 512?

  1. 1,048,576
  2. 262,144
  3. 131,072
  4. 2,097,152

4d2=4⋅262,144=1,048,5764d^2 = 4\cdot262{,}144 = 1{,}048{,}576, whatever the number of heads.

QQ has shape (B,T,d)=(2,10,64)(B, T, d) = (2, 10, 64) and there are 4 heads. What shape is it after splitting into heads?

  1. (2, 4, 10, 16)
  2. (2, 10, 4, 64)
  3. (8, 10, 64)
  4. (2, 4, 10, 64)

Split d=64d = 64 into 4 × 16 to get (2,10,4,16)(2, 10, 4, 16), then move the head axis forward: (2,4,10,16)(2, 4, 10, 16).

An MLP with width d=1024d = 1024 and hidden size 4d4d, without biases. How many parameters?

  1. 8,388,608
  2. 4,194,304
  3. 1,048,576
  4. 16,777,216

d⋅4d+4d⋅d=8d2=8⋅1,048,576=8,388,608d\cdot4d + 4d\cdot d = 8d^2 = 8\cdot1{,}048{,}576 = 8{,}388{,}608. Twice as many as the attention sublayer.

Which is the pre-norm block?

  1. X←X+MHA(LN(X))X\leftarrow X+\mathrm{MHA}(\mathrm{LN}(X)), then X←X+MLP(LN(X))X\leftarrow X+\mathrm{MLP}(\mathrm{LN}(X))
  2. X←LN(X+MHA(X))X\leftarrow \mathrm{LN}(X+\mathrm{MHA}(X)), then X←LN(X+MLP(X))X\leftarrow\mathrm{LN}(X+\mathrm{MLP}(X))
  3. X←MLP(MHA(LN(X)))X\leftarrow \mathrm{MLP}(\mathrm{MHA}(\mathrm{LN}(X)))
  4. X←X+LN(MHA(X)+MLP(X))X\leftarrow X+\mathrm{LN}(\mathrm{MHA}(X)+\mathrm{MLP}(X))

Pre-norm normalizes the input of each sublayer and adds the result to the untouched stream. The second option is the original 2017 "post-norm" design, which puts LN on the stream itself and is harder to train when deep.

A model with 32 heads processes a sequence of 4,096 tokens. How many attention weights does one layer compute for one sequence?

  1. about 537 million
  2. about 131 thousand
  3. about 16.8 million
  4. about 4.3 billion

Each head has a T×TT\times T matrix: 40962=16,777,2164096^2 = 16{,}777{,}216. Times 32 heads: 536,870,912536{,}870{,}912. That quadratic growth is why long contexts are expensive and why FlashAttention avoids storing the matrix.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 12

Positional encodings, RoPE as rotations, and how LLMs store facts

Watch: How might LLMs store facts (3Blue1Brown) Watch: Transformers, the tech behind LLMs (3Blue1Brown)

Attention by itself ignores word order, so position must be injected. Sinusoidal encodings add a fingerprint of waves at many frequencies; RoPE instead rotates each pair of query and key coordinates by an angle proportional to the position, so the dot product qm⋅kn\mathbf{q}_m\cdot\mathbf{k}_n depends only on the distance n−mn-m. And once tokens know their context, the MLP blocks act like a giant lookup table: rows of WupW_{\text{up}} ask questions, columns of WdownW_{\text{down}} add the answers.

Attention can't see order

Look at chapter 10's formula again: nothing in softmax(QK⊤/dk)V\mathrm{softmax}(QK^\top/\sqrt{d_k})V knows which row is first. Shuffle the input tokens and the outputs come out shuffled in the same way, otherwise unchanged: attention is permutation-equivariant. "Dog bites man" and "man bites dog" would get the same set of vectors. (The causal mask breaks this a little, but models still need explicit positions.)

Sinusoidal encodings

The original transformer adds a fixed vector ppos\mathbf{p}_{\text{pos}} to each token's embedding. Its coordinates come in pairs, one pair per frequency ωi=10000−2i/d\omega_i = 10000^{-2i/d}:

ppos, 2i=sin⁡(pos⋅ωi),ppos, 2i+1=cos⁡(pos⋅ωi).p_{\text{pos},\,2i} = \sin(\text{pos}\cdot\omega_i),\qquad p_{\text{pos},\,2i+1} = \cos(\text{pos}\cdot\omega_i).

Each pair is a point going round a circle as the position increases: fast for the first pairs (one radian per step), extremely slow for the last. Like the hands of a clock, all of them together pin down the position uniquely. And because each pair moves by rotation, ppos+k\mathbf{p}_{\text{pos}+k} is a fixed linear map (a rotation by k ωik\,\omega_i in every pair) of ppos\mathbf{p}_{\text{pos}}, which makes relative offsets easy for the network to use. GPT-2 instead learns its position vectors as an ordinary embedding table (1,024 of them).

RoPE: positions as rotations

Rotary position embedding (RoPE), used by LLaMA and most current LLMs, doesn't add anything to the embeddings. Instead, right before attention, it rotates the query and key. Split q\mathbf{q} into pairs (q2i,q2i+1)(q_{2i}, q_{2i+1}); at position mm, rotate pair ii by the angle mθim\theta_i using the 2D rotation matrix from Linear Algebra chapter 3:

R(α)=[cos⁡α−sin⁡αsin⁡αcos⁡α],qm=R(mθ) q,kn=R(nθ) k  (pair by pair).R(\alpha) = \begin{bmatrix}\cos\alpha & -\sin\alpha\\ \sin\alpha & \cos\alpha\end{bmatrix},\qquad \mathbf{q}_m = R(m\theta)\,\mathbf{q},\quad \mathbf{k}_n = R(n\theta)\,\mathbf{k}\ \ \text{(pair by pair)}.

Now the magic. Rotations are orthogonal, so R(α)⊤=R(−α)R(\alpha)^\top = R(-\alpha), and rotations compose by adding angles. Therefore

qm⋅kn=q⊤R(mθ)⊤R(nθ) k=q⊤R((n−m)θ) k.\mathbf{q}_m\cdot\mathbf{k}_n = \mathbf{q}^\top R(m\theta)^\top R(n\theta)\,\mathbf{k} = \mathbf{q}^\top R\big((n-m)\theta\big)\,\mathbf{k}.

The score depends on the content (q\mathbf{q}, k\mathbf{k}) and the relative position n−mn-m only. Shift the whole sentence 100 places later and every attention score is identical. Rotations also preserve length, so RoPE never changes the size of a query or key. The frequencies θi=10000−2i/d\theta_i = 10000^{-2i/d} span fast pairs (sensitive to nearby positions) and slow pairs (which barely rotate, so they can match content across long distances).

RoPE in one 2D pair. Drag the faint base vectors q (purple) and k (gold); the solid arrows are q rotated by m·θ and k rotated by n·θ. Move the positions m and n with the sliders, or press Shift both +1: the arrows turn, but their angle, and so the dot product in the readout, stays the same. Only n − m matters.
Sinusoidal positional encodings for positions 0–63 (rows) and 32 dimensions (columns): gold is positive, purple negative. Early columns oscillate fast, later ones slowly. Slide the position to highlight one row; the readout gives its first few entries and its dot product with position 0, which depends only on the distance between positions.

Where are the facts? The MLPs

Ask a model "Michael Jordan plays the sport of" and it answers "basketball". 3Blue1Brown's video walks through one plausible mechanism, supported by interpretability research, using the MLP block of chapter 11, x↦Wdown GELU(Wupx+b)\mathbf{x}\mapsto W_{\text{down}}\,\mathrm{GELU}(W_{\text{up}}\mathbf{x} + \mathbf{b}):

  • Each row of WupW_{\text{up}} is a direction; its dot product with the token's vector x\mathbf{x} asks a question like "does this vector encode Michael and Jordan?". The bias sets a threshold, and the nonlinearity switches the neuron on only when the answer is clearly yes.
  • Each column of WdownW_{\text{down}} is what that neuron writes into the residual stream when it fires, for instance the direction meaning "basketball".

So the MLP is a key–value memory: neuron jj maps "pattern rj\mathbf{r}_j present" to "add cj\mathbf{c}_j". The MLPs hold about two-thirds of a model's parameters, which suggests where much of its knowledge lives. And because nearly perpendicular directions are so plentiful in high dimensions (chapter 9), a model can store far more features than it has dimensions, packed into almost-orthogonal directions. This is called superposition.

Worked exampleRoPE by hand

One pair, θ=30°\theta = 30° per position, q=(2,1)\mathbf{q} = (2, 1), k=(1,1)\mathbf{k} = (1, 1). Plain dot product: q⋅k=3\mathbf{q}\cdot\mathbf{k} = 3.

Put q\mathbf{q} at position m=2m = 2 and k\mathbf{k} at n=5n = 5. The relative rotation is (5−2)⋅30°=90°(5-2)\cdot30° = 90°, and R(90°)k=(−1,1)R(90°)\mathbf{k} = (-1, 1), so q2⋅k5=q⋅R(90°)k=−2+1=−1\mathbf{q}_2\cdot\mathbf{k}_5 = \mathbf{q}\cdot R(90°)\mathbf{k} = -2 + 1 = -1. Rotating each separately gives the same thing: q2=R(60°)q≈(0.134,2.232)\mathbf{q}_2 = R(60°)\mathbf{q}\approx(0.134, 2.232), k5=R(150°)k≈(−1.366,−0.366)\mathbf{k}_5 = R(150°)\mathbf{k}\approx(-1.366, -0.366), dot product ≈−0.183−0.817=−1\approx -0.183 - 0.817 = -1. Positions m=0,n=3m = 0, n = 3 or m=10,n=13m = 10, n = 13 also give −1.

Sinusoidal: with ω0=1\omega_0 = 1, position 1's first pair is (sin⁡1,cos⁡1)≈(0.841,0.540)(\sin 1, \cos 1)\approx(0.841, 0.540), and position 0's is (0,1)(0, 1).

Watch outCommon misconceptions

  • "RoPE adds a position vector to the embedding." It rotates q\mathbf{q} and k\mathbf{k} inside each attention layer; the values and the residual stream are not touched.
  • "RoPE rotates the whole vector by one angle." It rotates each 2D pair by its own angle mθim\theta_i, with frequencies from fast to slow.
  • "Without positional encodings a transformer reads text as a bag of words, period." The causal mask leaks some order information, but explicit positions work far better.
  • "Facts are stored in one neuron each." The key–value picture is a useful simplification; real features are spread across many neurons in superposition.

In ML & deep learningWhere this shows up

LLaMA, Mistral, Qwen and most open models use RoPE. Extending a model's context window (from 4k to 128k tokens, say) is often done by rescaling RoPE's frequencies ("position interpolation", "NTK scaling", YaRN). Model-editing methods like ROME locate a fact in a specific MLP layer and change it with a small rank-one update to WdownW_{\text{down}}, which fits the key–value picture.

Practice (pick one answer per question)

With no positional information at all, what does self-attention (no mask) do if you shuffle the input tokens?

  1. The outputs are shuffled the same way, otherwise unchanged
  2. The outputs change completely
  3. The outputs stay in the original order
  4. It raises an error

Attention only uses dot products between tokens and a sum over all of them, so it is permutation-equivariant: each token's output doesn't depend on where it sits.

In RoPE with θ=10°\theta = 10° per position (for one pair), by what angle is the query at position 3 rotated?

  1. 30°
  2. 10°
  3. 3°
  4. 13°

Position mm rotates by mθ=3⋅10°=30°m\theta = 3\cdot10° = 30°.

What is the sinusoidal positional encoding of position 0 (pairs sin⁡,cos⁡\sin, \cos)?

  1. (0, 1, 0, 1, …)
  2. all zeros
  3. all ones
  4. (1, 0, 1, 0, …)

sin⁡0=0\sin 0 = 0 and cos⁡0=1\cos 0 = 1 for every frequency.

RoPE with θ=90°\theta = 90° per position. q=(1,0)\mathbf{q} = (1, 0) is at position 1 and k=(0,1)\mathbf{k} = (0, 1) at position 2. What is q1⋅k2\mathbf{q}_1\cdot\mathbf{k}_2?

  1. −1
  2. 0
  3. 1
  4. 2

Relative rotation 90°90°: R(90°)k=(−1,0)R(90°)\mathbf{k} = (-1, 0), and q⋅(−1,0)=−1\mathbf{q}\cdot(-1, 0) = -1. Directly: q1=(0,1)\mathbf{q}_1 = (0, 1), k2=R(180°)k=(0,−1)\mathbf{k}_2 = R(180°)\mathbf{k} = (0, -1), product −1-1.

Which fact about rotation matrices makes RoPE scores depend only on n−mn - m?

  1. R(α)⊤R(β)=R(β−α)R(\alpha)^\top R(\beta) = R(\beta - \alpha)
  2. R(α)+R(β)=R(α+β)R(\alpha) + R(\beta) = R(\alpha + \beta)
  3. det⁡R(α)=0\det R(\alpha) = 0
  4. R(α)v=vR(\alpha)\mathbf{v} = \mathbf{v} for all v\mathbf{v}

qm⋅kn=q⊤R(mθ)⊤R(nθ)k\mathbf{q}_m\cdot\mathbf{k}_n = \mathbf{q}^\top R(m\theta)^\top R(n\theta)\mathbf{k}, and the transpose of a rotation is the reverse rotation, so the product is R((n−m)θ)R((n-m)\theta). (Rotations have determinant 1, not 0.)

RoPE uses θi=10000−2i/d\theta_i = 10000^{-2i/d}. For d=128d = 128, what is θ32\theta_{32}, the frequency of the pair halfway along?

  1. 0.01 radians per position
  2. 0.5 radians per position
  3. 1 radian per position
  4. 0.0001 radians per position

10000−64/128=10000−1/2=0.0110000^{-64/128} = 10000^{-1/2} = 0.01. The first pair turns 1 radian per position, the last only about 0.00012.

An MLP neuron computes ReLU(r⋅x−0.5)\mathrm{ReLU}(\mathbf{r}\cdot\mathbf{x} - 0.5), where r\mathbf{r} is a unit vector for "Michael Jordan", and writes that amount of a "basketball" vector into the stream. Token A has xA=1.0 r+0.3 u\mathbf{x}_A = 1.0\,\mathbf{r} + 0.3\,\mathbf{u} and token B has xB=0.4 r\mathbf{x}_B = 0.4\,\mathbf{r}, with u⊥r\mathbf{u}\perp\mathbf{r}. How much "basketball" does each receive?

  1. A: 0.5, B: 0
  2. A: 1.0, B: 0.4
  3. A: 0.5, B: −0.1
  4. A: 1.3, B: 0.4

r⋅xA=1.0\mathbf{r}\cdot\mathbf{x}_A = 1.0 (the u\mathbf{u} part is perpendicular), so A gives ReLU(0.5)=0.5\mathrm{ReLU}(0.5) = 0.5. r⋅xB=0.4\mathbf{r}\cdot\mathbf{x}_B = 0.4, and ReLU(−0.1)=0\mathrm{ReLU}(-0.1) = 0. The bias acts as a threshold: only a clear match triggers the fact.

Code it (optional: real Python runs in your browser and is graded by test cases)

Final tests

3 full-length tests covering the whole module, with single-concept and multi-concept questions and Python problems graded by test cases. You get a score, a chapter-by-chapter breakdown and the worked answer to every question. Your best score is saved in this browser.

One-page cheat sheet

The whole module, compressed. Code convention: rows of XX are examples, Z=XW+bZ = XW + \mathbf{b}.

Layers (ch 1)

Neuron: a=σ(w⋅x+b)a = \sigma(\mathbf{w}\cdot\mathbf{x} + b). Layer: a=σ(Wx+b)\mathbf{a} = \sigma(W\mathbf{x}+\mathbf{b}), WW is out × in.

Batch: Z=XW+bZ = XW + \mathbf{b}, WW is in × out. Params of a dense layer: ninnout+noutn_{\text{in}}n_{\text{out}} + n_{\text{out}}.

No activation ⇒ layers collapse: W2W1x+(W2b1+b2)W_2W_1\mathbf{x} + (W_2\mathbf{b}_1+\mathbf{b}_2).

Activations (ch 2)

ReLU max⁡(0,z)\max(0,z), slope 0 or 1. Sigmoid σ=1/(1+e−z)\sigma = 1/(1+e^{-z}), σ′=σ(1−σ)≤0.25\sigma' = \sigma(1-\sigma)\le 0.25.

tanh⁡′=1−tanh⁡2≤1\tanh' = 1-\tanh^2\le1. GELU =z Φ(z)= z\,\Phi(z). Flat regions ⇒ tiny gradients (saturation, dead ReLU).

Softmax & cross-entropy (ch 3)

pi=ezi/∑jezjp_i = e^{z_i}/\sum_j e^{z_j}; only differences matter; subtract the max.

L=−log⁡pyL = -\log p_y; uniform guess ⇒ L=ln⁡KL = \ln K. Gradient: ∇zL=p−y\nabla_{\mathbf{z}}L = \mathbf{p}-\mathbf{y}.

Temperature: softmax(z/T)\mathrm{softmax}(\mathbf{z}/T). Two classes: σ(a−b)\sigma(a-b). Perplexity eLe^L.

Backprop (ch 4)

Z=XW+bZ = XW+\mathbf{b}, G=∂L/∂ZG = \partial L/\partial Z: ∂W=X⊤G\partial W = X^\top G, ∂b=∑rowsG\partial\mathbf{b} = \sum_{\text{rows}}G, ∂X=GW⊤\partial X = GW^\top.

Elementwise σ\sigma: multiply by σ′(Z)\sigma'(Z). Reused values: gradients add. A gradient has its variable's shape.

Initialization (ch 5)

Var(z)=n Var(w) E[x2]\mathrm{Var}(z) = n\,\mathrm{Var}(w)\,\mathbb{E}[x^2]; LL layers multiply the factor LL times.

LeCun 1/nin1/n_{\text{in}}, Xavier 2/(nin+nout)2/(n_{\text{in}}+n_{\text{out}}), He 2/nin2/n_{\text{in}} (ReLU halves E[a2]\mathbb{E}[a^2]).

Never all-equal weights (symmetry).

Normalization (ch 6)

x^=(x−μ)/σ2+ε\hat x = (x-\mu)/\sqrt{\sigma^2+\varepsilon}, y=γx^+βy = \gamma\hat x + \beta.

Batch norm: per feature over the batch (running stats at test). Layer norm: per example over features. RMSNorm: divide by RMS only.

Residuals (ch 7)

y=x+F(x)\mathbf{y} = \mathbf{x} + F(\mathbf{x}), Jacobian I+F′I + F'.

Plain: ∏Fl′\prod F_l' (vanishes/explodes). Residual: ∏(1+Fl′)\prod(1+F_l'), 2L2^L paths incl. the identity.

Convolution (ch 8)

yi=∑jkjxi+jy_i = \sum_j k_jx_{i+j} (no flip). Output ⌊(n+2p−m)/s⌋+1\lfloor(n+2p-m)/s\rfloor+1.

Toeplitz matrix: local + shared weights. 2D params: CoutCinkhkw+CoutC_{\text{out}}C_{\text{in}}k_hk_w + C_{\text{out}}. Receptive field of LL 3-wide layers: 2L+12L+1.

Embeddings (ch 9)

EE is V×dV\times d; lookup =ei⊤E=\mathbf{e}_i^\top E. Cosine =u⋅v∥u∥∥v∥=\frac{\mathbf{u}\cdot\mathbf{v}}{\|\mathbf{u}\|\|\mathbf{v}\|}.

Analogy: vb−va+vc\mathbf{v}_b-\mathbf{v}_a+\mathbf{v}_c. Random unit vectors in dd dims: cosine ≈±1/d\approx\pm1/\sqrt{d}. Unembedding: hE⊤\mathbf{h}E^\top.

Attention (ch 10)

Q=XWQ,K=XWK,V=XWVQ = XW_Q, K = XW_K, V = XW_V; softmax(QK⊤/dk) V\mathrm{softmax}(QK^\top/\sqrt{d_k})\,V.

Var(q⋅k)=dk\mathrm{Var}(\mathbf{q}\cdot\mathbf{k}) = d_k ⇒ divide by dk\sqrt{d_k}. Causal: −∞-\infty above the diagonal before softmax.

Transformer block (ch 11)

hh heads, dk=d/hd_k = d/h: (T,d)→(T,h,dk)→(h,T,dk)(T,d)\to(T,h,d_k)\to(h,T,d_k).

X+=MHA(LN(X))X \mathrel{+}= \mathrm{MHA}(\mathrm{LN}(X)); X+=MLP(LN(X))X \mathrel{+}= \mathrm{MLP}(\mathrm{LN}(X)). Params ≈ 4d2+8d2=12d24d^2 + 8d^2 = 12d^2 per block.

Positions & facts (ch 12)

Sinusoidal: (sin⁡(pos ωi),cos⁡(pos ωi))(\sin(\text{pos}\,\omega_i), \cos(\text{pos}\,\omega_i)), ωi=10000−2i/d\omega_i = 10000^{-2i/d}.

RoPE: qm=R(mθ)q\mathbf{q}_m = R(m\theta)\mathbf{q} per pair; qm⋅kn=q⊤R((n−m)θ)k\mathbf{q}_m\cdot\mathbf{k}_n = \mathbf{q}^\top R((n-m)\theta)\mathbf{k}.

MLP as memory: rows of WupW_{\text{up}} detect, columns of WdownW_{\text{down}} write.

Glossary

Activation function
The fixed nonlinear function applied after each layer's linear map (ReLU, sigmoid, tanh, GELU). Without it, layers collapse into one linear map. (Ch 2)
Attention
Each token takes a weighted average of other tokens' values, with weights from a softmax of query–key dot products: softmax(QKᵀ/√dk)V. (Ch 10)
Backpropagation
Computing the gradient of the loss with respect to every parameter in one backward sweep of the chain rule, reusing values stored in the forward pass. (Ch 4)
Batch norm
Normalizing each feature using the mean and variance over the examples in a batch, then scaling by γ and shifting by β. (Ch 6)
Causal mask
Setting attention scores to −∞ for later positions so each token only attends to itself and earlier tokens. (Ch 10)
Convolution
Sliding a small kernel along the input and taking a dot product at each position: a linear map with local, shared weights. (Ch 8)
Cosine similarity
The dot product of two vectors divided by both lengths: the cosine of the angle between them. (Ch 9)
Cross-entropy loss
−log of the probability the model gives the correct class. (Ch 3)
Dead ReLU
A ReLU unit whose input is negative for every example, so it outputs 0 and gets zero gradient forever. (Ch 2)
Embedding
A learned vector for each token, stored as a row of the V × d embedding matrix. (Ch 9)
Fan-in / fan-out
The number of inputs to / outputs from a layer; they set the right initialization scale. (Ch 5)
He initialization
Random weights with variance 2/fan-in, keeping signal size constant through ReLU layers. (Ch 5)
Layer norm
Normalizing each example's vector across its own features; independent of the batch. Used in transformers. (Ch 6)
Logits
The raw, unnormalized scores a classifier outputs before softmax. (Ch 3)
MLP (multilayer perceptron)
Dense layers alternating with activation functions; the feed-forward half of every transformer block. (Ch 1, 11)
Multi-head attention
Running h attention heads in parallel, each on d/h dimensions, then concatenating and mixing with WO. (Ch 11)
Positional encoding
Information about each token's position, added to the embeddings (sinusoidal, learned) or applied inside attention (RoPE). (Ch 12)
Pre-activation
The weighted sum z = w·x + b before the activation function is applied. (Ch 1)
Query, key, value
Three linear projections of each token: what it looks for, what it offers to be matched on, and what it passes on. (Ch 10)
Residual connection
Adding a block's input to its output, y = x + F(x), giving gradients an identity path. (Ch 7)
Residual stream
The per-token vector in a transformer that every block reads from and adds to. (Ch 7, 11)
RMSNorm
Layer norm without mean subtraction: divide by the root-mean-square, then scale by γ. (Ch 6)
RoPE
Rotary position embedding: rotate each 2D pair of query and key coordinates by an angle proportional to position, so scores depend on relative position. (Ch 12)
Saturation
When an activation like sigmoid or tanh is in its flat region, so its slope (and the gradient through it) is nearly zero. (Ch 2, 5)
Softmax
Exponentiate and normalize: turns any vector of scores into positive probabilities that sum to 1. (Ch 3)
Superposition
Storing more features than dimensions by using nearly perpendicular directions. (Ch 9, 12)
Temperature
Dividing logits by T before softmax: T < 1 sharpens, T > 1 flattens. (Ch 3)
Vanishing / exploding gradients
Gradients shrinking or growing exponentially with depth because per-layer factors multiply. (Ch 2, 5, 7)
Weight sharing
Using the same parameters at many positions, as a convolution does. (Ch 8)
Xavier (Glorot) initialization
Random weights with variance 2/(fan-in + fan-out), balancing forward and backward signal. (Ch 5)

Where to go next