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 from exploding, learn why attention divides by √d, and watch RoPE turn positions into rotations so that depends only on . 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.
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 , multiplies each by a weight, adds them up together with a bias , and then applies a fixed function called the activation:
The weighted sum is called the pre-activation. Geometrically, 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 neurons side by side, all looking at the same input. Stack their weight vectors as the rows of a matrix (size ) and their biases into a vector . All weighted sums at once are one matrix–vector product, the thing you met in Linear Algebra chapter 3:
Row of dotted with gives neuron 's sum. A layer with inputs and outputs has weights and 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):
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 , two layers collapse into one:
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 examples as the rows of a matrix (shape ) and write the layer as , with of shape and added to every row. That's the same math transposed: . PyTorch's nn.Linear stores the version and computes . Whenever you're unsure, check shapes: the inner dimensions must match.
Worked exampleA forward pass by hand
Take , a hidden layer with , and ReLU (), then an output neuron with weights and bias .
- Pre-activations: and .
- ReLU: . The first neuron is "off" for this input.
- Output: .
Parameter count: the hidden layer has , the output , 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.
- " is ." It depends on the convention. In math () it's outputs × inputs; in batched code () 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 , 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 . What shape is ?
- 5 × 3
- 3 × 5
- 5 × 5
- 15 × 1
must turn a length-3 vector into a length-5 vector, so 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?
- 20
- 15
- 18
- 8
15 weights () plus 5 biases, one per output neuron: 20. Forgetting biases gives 15.
A ReLU neuron has weights and bias . What does it output for ?
- 1
- 0
- 2
- 3
. 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?
- 13,002
- 12,960
- 12,544
- 13,560
Weights: . Biases: . Total 13,002. (12,960 forgets the biases.)
A batch of 32 examples with 10 features goes through , a layer with 4 outputs. What shape is ?
- 32 × 4
- 4 × 32
- 10 × 4
- 32 × 10
is , so must be , and 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 . Which single layer computes the same function?
- Weights , bias
- Weights , bias
- Weights , bias
- No single layer can; two layers are strictly more powerful
Distribute: . The bias of the first layer also passes through . The order is because 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?
- 7
- 6
- 8
- 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. lines in general position cut the plane into at most regions: 7. (Not : 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)
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 for some matrix , 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:
Check: (0, 0) gives ; (1, 0) and (0, 1) give ; (1, 1) gives . The second neuron switches on only past the line 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: . Slope 1 for , slope 0 for . 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 to keep a trickle of gradient.
- Sigmoid: , squashing everything into (0, 1). Its derivative has a neat form, , which is at most (at ). For large 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, . It's zero-centred and its slope reaches 1 at the origin, but it saturates just like sigmoid.
- GELU: , where is the standard normal CDF. Think of it as a smooth ReLU: near 1·z for large positive , near 0 for very negative , with a small dip to about −0.17 around . GPT-2, BERT and most transformers use it (or the close cousin SiLU, ).
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 . That's one root of the vanishing gradient problem, and the main reason ReLU-family activations replaced sigmoid in hidden layers.
Worked exampleValues and slopes
- and .
- , so . Already less than half the peak slope.
- and ; , so .
- but . .
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: in general (try ).
- "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 . 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 ?
- 0
- −3
- 3
- 1
. ReLU zeroes every negative input.
What is for the sigmoid ?
- 0.5
- 0
- 1
- 0.25
, so . (0.25 is the slope there, not the value.)
What is the largest value the sigmoid's derivative ever takes?
- 0.25
- 0.5
- 1
- It has no maximum
, and is largest at , giving . That happens at .
Ignoring the weights, a gradient passes through 10 sigmoid layers. At best, by what factor can the activations' slopes shrink it?
- about
- about 0.025
- about 2.5
- it doesn't shrink
Each slope is at most 0.25, and the slopes multiply: . Even the best case vanishes.
Using the XOR network from this chapter (, , ), what is at ?
- 0
- 2
- 1
- −2
, , so . Past the fold the output keeps falling with slope .
, with . What is ?
- about −0.159
- 0
- about −0.841
- −1
By symmetry of the normal distribution, . So . Unlike ReLU, GELU lets a little negative signal (and gradient) through.
Why can't a 50-layer network with no activation functions solve XOR?
- It equals a single linear layer, whose boundary is a straight line
- 50 layers is too few for XOR
- Its gradients vanish, so it can't train
- XOR needs a sigmoid output to be solvable
Composing linear (affine) maps gives another affine map . Its 0.5-level set is a straight line, and no line separates XOR. Depth adds nothing without nonlinearity.
A ReLU neuron has weights and bias . All training inputs lie in the square . What happens to it during training?
- It never activates, gets zero gradient and stays exactly as it is
- It activates for about half the inputs
- Its bias grows until it switches on
- It outputs negative values that gradient descent pushes up
The largest possible pre-activation is . 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)
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 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 for classes. These can be any real numbers. To get probabilities, make them positive with the exponential and then divide by the total:
Every 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 to every logit multiplies top and bottom by , which cancels. Code uses this for safety: subtract first, so the largest exponent is and nothing overflows.
- Gaps become ratios. . A logit 1 higher means times as likely; higher means 3 times as likely.
- Temperature. Using with sharpens the distribution toward the top class (as it becomes the one-hot argmax); flattens it (as it becomes uniform). This is the "temperature" knob when you sample from a language model.
Cross-entropy loss
If the correct class is , the cross-entropy loss is
A confident correct answer () costs nearly 0; a confident wrong one () costs a lot, without bound. With a one-hot target vector the same thing is written . 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 and loss : a great sanity check for the loss at the start of training.
The gradient:
Write . Differentiate with respect to : the first term gives if and 0 otherwise; the second gives . So
Read it as: push the correct logit up by , 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.
Worked exampleThree classes
Logits . Exponentials: , , , total . So .
If the true class is the first, , and the gradient is . Gradient descent subtracts it, raising and lowering the other two. If the true class were the third, : a much bigger penalty.
Watch outCommon misconceptions
- "Softmax probabilities are proportional to the logits." They're proportional to . Logits (1, 2) don't give a 1 : 2 ratio; they give .
- "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 . Libraries fuse them (
log_softmax,cross_entropyon raw logits) and subtract the max. - "Loss 0 is the goal." It needs , 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 , 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 case: softmax over logits gives .
Practice (pick one answer per question)
What is ?
- (0.25, 0.25, 0.25, 0.25)
- (0, 0, 0, 0)
- (1, 1, 1, 1)
- undefined
Each , 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?
- 0
- 1
- −1
- infinity
. Infinity is the opposite case, probability 0 on the correct class.
What is ?
- (0.25, 0.75)
- (0.5, 0.5)
- (1/3, 2/3)
- (0.4, 0.6)
Only the difference matters: the ratio is . 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?
- about 3.30
- about 4.75
- about 0.037
- about 27
Uniform means , so (natural log). 4.75 is . If your initial loss is much bigger than , the initial logits are too large: chapter 5's lesson.
Softmax gives and the true class is the third. What is ?
- (0.7, 0.2, −0.9)
- (−0.3, 0.2, 0.1)
- (0.7, 0.2, 0.1)
- (0, 0, −2.303)
(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 as the temperature goes to 0 (logits all different)?
- It becomes one-hot on the largest logit
- It becomes uniform
- It stays the same
- Every probability goes to 0
Dividing by a tiny blows up every gap to 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 . Which formula gives the probability of the first class?
(divide top and bottom by ). 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)
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 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 , where 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, , with of shape , of shape , and suppose we already know (shape , same as ). Then
You don't have to memorize these: the gradient has the same shape as the variable, and there's only one way to multiply and to get an result. The bias gradient sums over the batch because the same bias was added to every row. Each entry checks out by hand: , so touches every row with coefficient , and its gradient is , which is entry of .
For an activation applied entry by entry, the rule is a plain product: . For ReLU that means: copy the gradient where , zero it where . And when one value feeds two places, the gradients from both places add.
Worked exampleA 2–2–1 network, every number
Input . Hidden layer (rows are neurons) , , ReLU. Output with , . Target , loss .
Forward. . Both positive, so . Then and .
Backward.
- .
- Output layer: , , and .
- Through ReLU (both units on): .
- Hidden layer: (same shape as ), .
- Input (if we wanted it): .
One step with changes to , to , and so on. Every change nudges 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 is ." Check the shapes: that's -ish nonsense. With , it's . With the math convention , it's . 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 (the coding problem below) is the standard way to test one.
Practice (pick one answer per question)
A weight matrix has shape 64 × 128. What shape is ?
- 64 × 128
- 128 × 64
- 64 × 64
- 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 : 64 × 128.
with , and . What is ?
- 6
- 2
- 3
- 1.5
Chain rule: .
A ReLU layer had pre-activations . The upstream gradient is . What is ?
- (0, 3, 3)
- (3, 3, 3)
- (0, 6, 1.5)
- (−3, 6, 1.5)
ReLU's slope is 0 where and 1 where . Multiply entry by entry: . (Multiplying by itself is a common slip.)
, with of shape 32 × 10 and of shape 32 × 4. Which expression is ?
- , shape 10 × 4
- , shape 32 × 32
- , shape 4 × 10
- , shape 32 × 32
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 : it sums over the batch of 32.
A sigmoid neuron with loss . At , , , , what is ?
- −0.25
- −0.5
- −0.125
- 0.25
Forward: , . Backward: ; ; . Product: .
A weight is used twice: and , and the loss depends on both with , . What is ?
- 14
- 12
- 2
- 8
Add the contributions of both paths: . 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?
- There's one loss and many weights; one backward sweep gives every weight's gradient at about twice the forward cost
- The chain rule only works from right to left
- The forward direction would give the wrong answer
- 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)
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 layers the size is that factor to the power . 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 (Xavier/LeCun) for tanh-like layers, (He) for ReLU.
One layer, one variance calculation
Look at one pre-activation , where 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 . Each term then has mean 0 and variance , and variances of independent terms add:
So one layer multiplies the signal's "power" by (times whatever the activation does). Stack layers and you multiply by that factor times. With and weights drawn from a standard normal (), the variance grows 512× per layer: after a few layers you get overflow. With , 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 . Xavier compromises between the forward pass (fan-in) and the backward pass (fan-out) with .
- He (Kaiming): ReLU zeroes the negative half of its input, so if is symmetric around 0, . Each ReLU layer halves the power, and to cancel that we double the weights' variance: , i.e. standard deviation .
The same argument runs backward. The gradient 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 (chapter 3). Karpathy shrinks the last layer's weights for exactly this reason.
Worked exampleHow fast does it blow up?
A ReLU network with fan-in per layer. He initialization uses standard deviation .
Suppose instead you use a round 0.1. The per-layer factor on the variance is . After 20 layers: for the variance, so the standard deviation grows by . 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 .
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 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 , so that adding up 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)
with independent zero-mean weights of variance 0.01 and inputs with . What is ?
- 1
- 0.01
- 100
- 0.1
. That's LeCun initialization: variance .
What standard deviation does He initialization use for a ReLU layer with fan-in 50?
- 0.2
- 0.04
- 0.14
- 0.02
. (0.04 is the variance; 0.14 is , the LeCun value.)
What weight variance does Xavier (Glorot) initialization give a layer from 100 to 300 neurons?
- 0.005
- 0.01
- 0.02
- 0.0033
. (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?
- about 117 times
- about 5.5 times
- about 1.1 times
- about 55 times
Factors multiply: . 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 where LeCun has 1?
- ReLU zeroes about half its inputs, halving , so the weights must double it back
- Because the backward pass is twice as expensive
- To average fan-in and fan-out
- Because ReLU's slope is 2 for positive inputs
For symmetric , : 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?
- All hidden neurons compute the same value and get the same gradient, so they stay identical
- Nothing, as long as the learning rate is small
- The gradients are all exactly zero
- 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?
- shrunk to about 0.031 times
- shrunk to about 0.001 times
- shrunk to about 0.5 times
- unchanged
Per-layer variance factor: . After 10 layers the variance is times as big, and the standard deviation is the square root of that: . (He would use .)
Code it (optional: real Python runs in your browser and is graded by test cases)
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 and . 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 , compute their mean and variance , then
The have mean 0 and variance 1 (the small , like , only prevents division by zero). Then (a learned scale) and (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 , the mean and variance are taken over the 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 and 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 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. and are still per-feature vectors of length .
- RMSNorm is layer norm without the mean subtraction: divide each row by its root-mean-square , then scale by . 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.
Worked exampleLayer norm on one row
Row . Mean . Deviations , squared , so and (ignore ).
. Check: mean 0, and the squares average to . With and (same for every feature here), the output is .
Note that or give exactly the same : layer norm ignores the row's offset and overall scale.
Watch outCommon misconceptions
- "Normalization makes every output have mean 0 and variance 1." Only does. After and 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 is a single number." It's a vector with one scale per feature (and one shift per feature): parameters for width .
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 , , ) to the row .
- (−1, 1)
- (0.25, 0.75)
- (−2, 2)
- (1, 3)
Mean 2, deviations , variance , standard deviation 1. So . (0.25, 0.75) divides by the sum, which is a different operation.
Batch norm computes its mean and variance…
- for each feature, across the examples in the batch
- for each example, across its features
- over the whole batch and all features at once
- 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 , , )?
- about (−1.22, 0, 1.22)
- (−1, 0, 1)
- (−10, 0, 10)
- about (−0.82, 0, 0.82)
Mean 20, deviations , variance , standard deviation . Divide: . Using the "sample" variance (divide by 2) would give exactly , but normalization layers divide by .
After normalizing, one entry is . Its and . What does the layer output?
- 2
- 1.5
- 3
- 0.5
.
Apply RMSNorm () to .
- about (0.849, 1.131)
- (0.6, 0.8)
- (−1, 1)
- about (0.429, 0.571)
RMS . Divide: . 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?
- LN treats each token independently, so it works for any batch size and sequence length and behaves the same in training and generation
- LN has fewer parameters than BN
- BN can't be differentiated
- 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 parameters, and both are differentiable.)
Every entry of a row is replaced by . What happens to the row's layer-norm output (, , ignoring )?
- Nothing: it is unchanged
- It is multiplied by 3
- It is shifted by 5
- It is multiplied by 3 and shifted by 5
The mean becomes and the standard deviation , so . 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)
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: . Its derivative is instead of just , 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, , and the chain rule makes the gradient at layer 1 a product of Jacobians:
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 . The block only has to learn the residual, the change to make; doing nothing is as easy as . Differentiate: the Jacobian is . Now the product becomes
Expanded, it contains the plain identity : a path from the loss straight to layer 1 that skips every block. It also contains every subset of blocks: with blocks there are paths of all lengths, so a residual network behaves somewhat like an ensemble of many shallower networks. Even if every 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 . If each residual block has , the block's slope is , the same disaster; but blocks whose 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: . 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 is the same in every layer.
Worked exampleThree blocks, both ways
Take scalar blocks with and .
- Plain (): .
- Residual (): .
Expanding the residual product: . 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 in gives every layer a direct line to the loss.
- "Residual networks can't have exploding gradients." Factors like can still compound if is consistently positive and big. That's why they're combined with normalization and careful initialization (GPT-2's scaling, chapter 5).
- " can have any shape." It must match 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 , and at the current input . What is ?
- 0.8
- −0.2
- 1.2
- 0.2
. The 1 comes from the skip connection.
All the weights inside a residual block's are zero (and so are its biases). What does the block compute?
- The identity:
- Zero
- It is undefined
, so . 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?
- about
- 10
- 0.5
- about 0.0005
. The early layers essentially receive no learning signal.
A residual network has 20 blocks, each with . By what factor is the gradient at the first block scaled?
- about 2.65
- about 1.05
- about 2.0
- about
. It neither vanishes nor explodes badly. ( would be the plain network, .)
A block's maps a 512-dimensional vector to a 256-dimensional one. Can you add a skip connection directly?
- No: the shapes don't match, so you need a projection (e.g. a 256 × 512 matrix) on the skip path
- Yes, numpy broadcasting handles it
- Yes, if you use layer norm first
- 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 constant.
In a pre-norm transformer, how does each block change the residual stream ?
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 gives one term per path the gradient can take (through each block, or around it). How many paths are there for blocks?
- 1024
- 10
- 11
- 100
Each block is either used () or skipped (1), independently: 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)
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 and a kernel with much smaller than . The output at position is the dot product of the kernel with the window of starting at :
That's outputs (a "valid" convolution, no padding). The kernel decides what each output detects: averages (blurs), measures change (edges), 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, . 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 is a fixed linear combination of the 's, so for some matrix . For and :
Two things are special. Locality: each row is zero outside a window of width . Weight sharing: every row holds the same 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 adds zeros at each end; stride moves the window steps at a time. Output length: .
- Images: the kernel is a small 2D patch (say 3 × 3) sliding in both directions. With input channels (red, green, blue, or earlier feature maps), one output channel uses a kernel and sums over all of them. A layer with output channels has weights plus biases.
- Receptive field: stacking convolutions lets later layers see further. Two 3-wide layers see 5 inputs; of them see .
Worked exampleTwo kernels on a ramp
, .
- Kernel : , , . Three outputs (), all : this kernel measures the slope (times −2), and a ramp has the same slope everywhere.
- Kernel : , the moving average.
As a matrix, the first is 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 for odd , stride 1). A valid convolution shrinks it by .
- "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?
- 8
- 10
- 7
- 12
: the window has 8 starting positions.
What is the valid convolution of with ?
- (0, 1, 0, 0)
- (0, −1, 0, 0)
- (0, 0, 1, 1)
- (0, 1, 0, 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?
- 4,640
- 4,608
- 288
- 9,248
Weights: . 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?
- 16
- 14
- 15
- 32
. Stride 2 roughly halves the size.
A kernel of length 3 is applied validly to signals of length 5, written as . What shape is and how many of its entries can be nonzero?
- 3 × 5, with 9 possibly nonzero entries
- 5 × 5, with 15 nonzero entries
- 5 × 3, with 9 nonzero entries
- 3 × 3, all 9 nonzero
3 outputs, 5 inputs, so is 3 × 5. Each row holds the 3 kernel values at a shifted position: 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?
- It shifts 4 pixels to the right too
- It doesn't change
- It changes unpredictably
- It shifts 4 pixels to the left
The same kernel is applied everywhere, so whatever it found at position it now finds at . 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)?
- 9
- 12
- 81
- 7
Each layer widens the view by : 3, 5, 7, 9. In general . 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)
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 , where is the vocabulary size. The embedding matrix has shape : row is the -dimensional vector for token . Looking up token means taking row .
Mathematically that's a matrix product. Write the token as a one-hot vector (all zeros except a 1 in position ); then is exactly row . 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 ? The dot product (Linear Algebra chapter 9) mixes two things: lengths and angle. Dividing out the lengths leaves the cosine similarity
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
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 , 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 . 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).
Worked exampleCosine similarity and an analogy
, : , , so (about 37°). And has cosine 1 with : 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 , while with prince it is . 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, , then softmax (chapter 3). GPT-2 reuses the same matrix for both ("tied weights"). The embedding matrix is big: 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)
is a embedding matrix and is the one-hot vector for token 3. What is ?
- Row 3 of
- Column 3 of
- The sum of all rows of
- A matrix
Multiplying by a one-hot row vector picks out one row: the embedding of token 3, a vector of length .
What is the cosine similarity of and ?
- 0
- 1
- −1
- 0.5
The dot product is 0, so the cosine is 0: perpendicular, "unrelated".
What is the cosine similarity of and ?
- 0.96
- 24
- 0.75
- 1
Dot product ; both lengths are 5; cosine . Close, but not the same direction.
A model has a vocabulary of 50,000 tokens and width . How many parameters does its embedding matrix have?
- 25.6 million
- 50,512
- 2.56 million
- 256 million
. 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?
- queen
- prince
- none: the result is exactly king
- 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?
- The raw dot product also grows with vector length, which can reflect things like word frequency rather than meaning
- The dot product can't be computed for long vectors
- Cosine similarity is faster to compute
- The dot product is always zero for different words
. 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 dimensions (each coordinate random with mean 0). What is their cosine similarity typically?
- about ±0.01
- about ±0.5
- exactly 0
- about ±0.0001
The dot product is a sum of independent terms, each with variance , so its variance is and its typical size is . 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)
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 and softmaxed, decide how much of each value a token receives. The whole thing is three matrix products and a softmax: .
Three projections
Stack the token vectors of a sequence as the rows of (shape ). Three learned matrices project every token at once:
with of shape and of shape . Row of is token 's query, row of is token 's key, row of 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 to token is the dot product : all of them together form the matrix . Each row is turned into weights that are positive and sum to 1 with a softmax (chapter 3), and the output for token is the weighted average of the values:
Row of the weight matrix says where token looks; the output row is . 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 and are independent with mean 0 and variance 1 (roughly what normalization and good initialization give). Then is a sum of terms of variance 1, so its variance is and its typical size is . With , 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 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 must not peek at tokens after it. Before the softmax, set every score with to . Then : 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 can see everything.
Worked exampleOne query, three keys
. Query ; keys , , ; values , , .
- Scores ; divided by : .
- Softmax: , , ; total ; weights .
- Output: .
Without the scaling, the weights would be : already more peaked, and the effect grows with .
Watch outCommon misconceptions
- "Attention weights are symmetric." in general, because queries and keys come from different matrices. "The noun attends to the adjective" doesn't imply the reverse.
- "We divide by ." By its square root: the standard deviation of the score grows like , not .
- "The mask sets future weights to 0 after the softmax." Zeroing afterwards would leave rows that don't sum to 1. The mask adds 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 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 matrix never sits in memory at once. In self-attention , , 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)
and both have shape . What shape is ?
: one score for every (query token, key token) pair.
With a causal mask, which tokens can token 3 (counting from 1) attend to?
- Tokens 1, 2 and 3
- Only token 3
- Tokens 3 onwards
- Tokens 1 and 2 only
The mask blocks positions . Token 3 sees itself and everything before it.
A head has . What are the scores divided by?
- 8
- 64
- 32
- 4096
.
have independent entries, each with mean 0 and variance 1. What is the standard deviation of ?
- 4
- 16
- 1
- 256
Each product has variance ; 16 independent ones add to variance 16, standard deviation 4. Dividing by brings it back to 1.
A row of scores is after masking. What are the attention weights?
- (0.5, 0.5, 0)
- (1/3, 1/3, 1/3)
- (1, 1, 0)
- (0.5, 0.5, −∞)
; normalized: . The masked position disappears and the rest still sum to 1.
Token has scores against two tokens (already scaled) whose values are and . What is its attention output?
- (1, 3)
- (2, 2)
- (3, 1)
- (0, 4)
Weights: . Output: .
Without the scaling, what goes wrong when is large?
- Scores get large, softmax saturates to nearly one-hot, and its gradients become tiny
- The scores all become nearly equal, so attention is uniform
- The weights no longer sum to 1
- Nothing: softmax only depends on differences between scores
Softmax does depend only on differences, but those differences are what grow: their spread scales like . 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)
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 smaller ones in parallel, each on its own slice of 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 heads side by side. With model width , each head uses dimensions, so the total cost equals that of one full-width head.
In code it's a reshape. Compute as usual (shape ), then view the columns as groups of :
Do the same for and , run attention independently in each of the slices (a batched matrix product), then undo the reshape, putting the heads' outputs side by side again as , and multiply by an output matrix () that mixes information across heads:
Parameters: are each , so (plus biases), independent of .
The block
A modern ("pre-norm") transformer block updates the residual stream (one row per token) in two steps:
Attention is where tokens communicate: it's the only step that mixes information between positions. The MLP, with a hidden width of usually , 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 , MLP , so about (biases and layer norms add only a few thousand). A model with blocks has about parameters, plus the embeddings (chapter 9). GPT-2 small (, , vocabulary 50,257, 1,024 positions) has M block parameters and about 39.4M embedding parameters, roughly 124M in all.
Worked exampleShapes through one block
Batch , sequence , width , heads (so ).
- Input : . After LN: same shape.
- : each , reshaped to .
- Scores : , one 10 × 10 matrix per example per head. After softmax, times : .
- Merge heads: ; times : ; add to .
- MLP: ; add to .
Parameters (no biases): attention , MLP .
Watch outCommon misconceptions
- "More heads means more parameters." With , the four matrices are the same size for any . Heads just partition them.
- "Reshape straight to ." A plain reshape would scramble tokens and features. You must reshape to and then transpose to .
- "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 and 96 heads of size 128; B 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 and heads. What is the head size ?
- 64
- 512
- 4096
- 8
.
Which sublayer of a transformer block moves information between different token positions?
- Attention
- The MLP
- Layer norm
- 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 hold together when ?
- 1,048,576
- 262,144
- 131,072
- 2,097,152
, whatever the number of heads.
has shape and there are 4 heads. What shape is it after splitting into heads?
- (2, 4, 10, 16)
- (2, 10, 4, 64)
- (8, 10, 64)
- (2, 4, 10, 64)
Split into 4 × 16 to get , then move the head axis forward: .
An MLP with width and hidden size , without biases. How many parameters?
- 8,388,608
- 4,194,304
- 1,048,576
- 16,777,216
. Twice as many as the attention sublayer.
Which is the pre-norm block?
- , then
- , then
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?
- about 537 million
- about 131 thousand
- about 16.8 million
- about 4.3 billion
Each head has a matrix: . Times 32 heads: . 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)
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 depends only on the distance . And once tokens know their context, the MLP blocks act like a giant lookup table: rows of ask questions, columns of add the answers.
Attention can't see order
Look at chapter 10's formula again: nothing in 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 to each token's embedding. Its coordinates come in pairs, one pair per frequency :
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, is a fixed linear map (a rotation by in every pair) of , 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 into pairs ; at position , rotate pair by the angle using the 2D rotation matrix from Linear Algebra chapter 3:
Now the magic. Rotations are orthogonal, so , and rotations compose by adding angles. Therefore
The score depends on the content (, ) and the relative position 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 span fast pairs (sensitive to nearby positions) and slow pairs (which barely rotate, so they can match content across long distances).
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, :
- Each row of is a direction; its dot product with the token's vector 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 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 maps "pattern present" to "add ". 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, per position, , . Plain dot product: .
Put at position and at . The relative rotation is , and , so . Rotating each separately gives the same thing: , , dot product . Positions or also give −1.
Sinusoidal: with , position 1's first pair is , and position 0's is .
Watch outCommon misconceptions
- "RoPE adds a position vector to the embedding." It rotates and 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 , 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 , 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?
- The outputs are shuffled the same way, otherwise unchanged
- The outputs change completely
- The outputs stay in the original order
- 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 per position (for one pair), by what angle is the query at position 3 rotated?
- 30°
- 10°
- 3°
- 13°
Position rotates by .
What is the sinusoidal positional encoding of position 0 (pairs )?
- (0, 1, 0, 1, …)
- all zeros
- all ones
- (1, 0, 1, 0, …)
and for every frequency.
RoPE with per position. is at position 1 and at position 2. What is ?
- −1
- 0
- 1
- 2
Relative rotation : , and . Directly: , , product .
Which fact about rotation matrices makes RoPE scores depend only on ?
- for all
, and the transpose of a rotation is the reverse rotation, so the product is . (Rotations have determinant 1, not 0.)
RoPE uses . For , what is , the frequency of the pair halfway along?
- 0.01 radians per position
- 0.5 radians per position
- 1 radian per position
- 0.0001 radians per position
. The first pair turns 1 radian per position, the last only about 0.00012.
An MLP neuron computes , where is a unit vector for "Michael Jordan", and writes that amount of a "basketball" vector into the stream. Token A has and token B has , with . How much "basketball" does each receive?
- A: 0.5, B: 0
- A: 1.0, B: 0.4
- A: 0.5, B: −0.1
- A: 1.3, B: 0.4
(the part is perpendicular), so A gives . , and . 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 are examples, .
Layers (ch 1)
Neuron: . Layer: , is out × in.
Batch: , is in × out. Params of a dense layer: .
No activation ⇒ layers collapse: .
Activations (ch 2)
ReLU , slope 0 or 1. Sigmoid , .
. GELU . Flat regions ⇒ tiny gradients (saturation, dead ReLU).
Softmax & cross-entropy (ch 3)
; only differences matter; subtract the max.
; uniform guess ⇒ . Gradient: .
Temperature: . Two classes: . Perplexity .
Backprop (ch 4)
, : , , .
Elementwise : multiply by . Reused values: gradients add. A gradient has its variable's shape.
Initialization (ch 5)
; layers multiply the factor times.
LeCun , Xavier , He (ReLU halves ).
Never all-equal weights (symmetry).
Normalization (ch 6)
, .
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)
, Jacobian .
Plain: (vanishes/explodes). Residual: , paths incl. the identity.
Convolution (ch 8)
(no flip). Output .
Toeplitz matrix: local + shared weights. 2D params: . Receptive field of 3-wide layers: .
Embeddings (ch 9)
is ; lookup . Cosine .
Analogy: . Random unit vectors in dims: cosine . Unembedding: .
Attention (ch 10)
; .
⇒ divide by . Causal: above the diagonal before softmax.
Transformer block (ch 11)
heads, : .
; . Params ≈ per block.
Positions & facts (ch 12)
Sinusoidal: , .
RoPE: per pair; .
MLP as memory: rows of detect, columns of 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)