Quick recap
The key takeaways of every lesson on one page. Read it in ten minutes to refresh the whole track; open a lesson when a point feels unclear.
01 MLPs and universal approximation
- An MLP alternates affine maps and activations: , , with no activation on the last layer. It has parameters.
- Without activations, any number of layers is one affine map , with rank at most the smallest width.
- One ReLU unit is a hinge with its joint at . One hidden layer of units gives a piecewise-linear function with at most pieces.
- Through any knots, the ReLU network with and (changes of slope) interpolates exactly; the error for smooth is at most .
- Universal approximation (Leshno et al. 1993): with a continuous, non-polynomial activation, one hidden layer approximates any continuous function on a compact set to any accuracy in the sup norm.
- The theorem gives existence only: no width bound, no guarantee that training finds the weights, nothing about generalization or about inputs outside the compact set.
- Depth multiplies pieces: hidden layers of width give at most pieces in 1-D, and the tent map composed times has pieces with only units.
02 Training a network
- Training minimizes the empirical risk on the training set; the validation set chooses hyperparameters, and the test set is used once for a final estimate.
- Losses are negative log-likelihoods: Gaussian noise gives the squared error, Bernoulli gives binary cross-entropy, and a softmax over classes gives cross-entropy .
- The gradient of softmax cross-entropy with respect to the logits is (and for a batch mean); for a sigmoid with BCE it is .
- Sigmoid + squared error has gradient , which almost vanishes when the model is confidently wrong; cross-entropy does not have this problem.
- Compute losses from logits with log-sum-exp: . PyTorch's
CrossEntropyLossandBCEWithLogitsLosstake logits, not probabilities. - A mini-batch gradient is unbiased, and with independent draws its covariance is : the noise falls like while the cost grows like .
- Gradient descent on converges if and only if ; in many dimensions the largest curvature sets the limit .
- The training loop is forward, loss,
zero_grad,backward,step; check the initial loss (), overfit one batch first, and read the training and validation curves together.
03 Backpropagation
- Backpropagation computes adjoints from the loss backward: the adjoint of an input is the upstream gradient times the local gradient.
- On a computational graph, each node computes a vector-Jacobian product, and a variable that fans out gets the sum of the adjoints from all its uses.
- Linear layer with : , , . Every gradient has the shape of its variable.
- MLP with softmax cross-entropy (batch mean): and ; the factor enters only once.
- Reverse mode gives the full gradient of a scalar loss for about 2× the forward cost in the backward pass (about FLOPs per token per training step), but it must store the activations.
- Activation checkpointing stores only segment inputs and recomputes the rest: about stored activations for at most one extra forward pass.
- Gradient check: central differences in float64 with to , relative error, no kinks. The error is truncation plus round-off .
04 Activations and initialization
- At initialization, : each layer multiplies the signal size by a factor, so a factor gives , exponential in depth.
- He initialization keeps the variance of a ReLU network constant, because for symmetric ; LeCun is for linear or tanh units.
- The backward pass has the same recursion with and ; Xavier is the compromise between the two conditions.
- Xavier in a deep ReLU network halves the variance in every layer: after 50 layers it is about of the start.
- Sigmoid and tanh saturate (); ReLU passes gradient 1 for positive inputs but can die; GELU and SiLU are smooth and pass some gradient for negative inputs.
- Equal (or zero) initial weights give equal units for ever (the symmetry problem); random weights break the symmetry.
- SwiGLU has three weight matrices; hidden width keeps the parameter count and FLOPs of a GELU FFN of width .
- μP also scales the learning rates with width, so that hyperparameters tuned on a small model transfer to a large one.
05 Normalization and residuals
- A normalization layer computes over a group of numbers (biased variance), then with learned .
- BatchNorm groups one channel over the batch (and positions); LayerNorm groups the features of one token; RMSNorm is LayerNorm without the mean and without .
- BatchNorm uses batch statistics in training and running statistics in eval mode (momentum 0.1, unbiased running variance in PyTorch); LayerNorm and RMSNorm are the same in both modes.
- The BatchNorm/LayerNorm backward pass is , : it removes the components along and , so .
- Transformers use LayerNorm or RMSNorm because BatchNorm depends on the batch: small batches, batch-1 decoding, padding and causal leakage.
- A residual stack has : the identity term carries the gradient to every layer.
- Without normalization, residual blocks with variance-preserving branches double the forward variance per block; fixes are normalization in the branch, zero-initialized branch ends, or scaling.
- Pre-LN keeps a pure identity path and needs a final norm and little or no warmup; post-LN has larger gradients near the output at initialization and needs warmup.
06 Regularization
- A regularizer is a change to training that aims to lower the test error, not the training error.
- Inverted dropout: in training with , in eval; and .
- Dropout on the inputs of linear regression equals a ridge penalty .
- For SGD, L2 regularization equals weight decay with factor per step.
- For Adam, L2 is not weight decay: the decay is divided by , so weights with large gradients are decayed less. AdamW decouples the decay, , then the Adam step.
- Label smoothing uses the target ; the gradient is , the minimal loss is , and the optimal logit gap is finite.
- Data augmentation with a symmetry group of the labels makes the training objective prefer invariant predictors; it must not change the label or the physics.
- Early stopping after steps of GD on least squares has filter factors , close to ridge's with .
07 Convolutional networks
- A convolution layer slides one small kernel over the input: . Deep-learning "convolution" is a cross-correlation (no kernel flip).
- Locality and weight sharing: in 1-D the layer is a banded Toeplitz matrix with parameters instead of .
- Output size ; parameters , independent of the image size; MACs .
- Receptive field: with jump ; pooling layers count like convolutions.
- im2col turns a convolution into one matrix product ; cols is about times larger than the input.
- Backward: , , : a transposed convolution, a full correlation with the -rotated kernel.
- Stride-1 convolution is translation equivariant (exactly on a circular domain); zero padding breaks it at the border, and stride keeps it only for shifts by multiples of .
- A convolution is a linear layer over channels at every pixel; the ResNet bottleneck ( down, , up) has about fewer weights than a basic block at 256 channels.
08 RNNs and LSTMs
- An embedding is a lookup: is row of , with parameters.
- A language model is trained on next-token prediction: , with the true previous tokens as inputs (teacher forcing).
- An RNN updates with the same weights at every step; BPTT is backpropagation on the unrolled network, and gradients of shared weights are sums over time.
- The gradient from step to step is a product of Jacobians , so it vanishes or explodes exponentially.
- If the long-term gradients vanish (Pascanu et al.); for a linear RNN the spectral radius decides the long run.
- Global-norm clipping keeps the direction and stops exploding steps; it does nothing for vanishing gradients.
- The LSTM cell has an additive path with Jacobian ; with near 1, memory and gradients last about steps.
- Attention and state-space models replaced RNNs for long sequences: parallel training, short gradient paths, and (for SSMs) a constant-size state with controlled eigenvalues.
09 Attention
- Attention for one query: scores , weights (positive, sum 1), output : a soft dictionary lookup.
- Self-attention: , , and ; row of the matrix holds the weights of token .
- For independent unit-variance entries, ; dividing by keeps the logits of order 1 at initialization.
- The softmax Jacobian is ; when is nearly one-hot, all its entries are small and the gradient to the logits vanishes.
- Masks add to the logits before the softmax: causal () for decoders, padding for padded keys; a fully masked row gives NaN.
- Multi-head attention splits into heads of size with a view and a transpose; it has parameters for every and costs FLOPs.
- Cross-attention takes queries from one sequence and keys and values from another; it never uses a causal mask.
- Without a mask, self-attention is permutation-equivariant, : it sees a set, so position information must be added.
10 Positional encodings
- Self-attention without positions is permutation-equivariant, so every sequence model needs a positional encoding.
- Learned absolute embeddings add a trained row to token ; they have parameters and no meaning beyond .
- Sinusoidal encodings: , , ; a shift by is a fixed block rotation, .
- Adding position to the input lets the score depend on absolute positions; it does not force relative attention.
- RoPE rotates pair of each query and key by ; since , the score depends on the offset only, with no parameters.
- Slow RoPE pairs never complete a turn during training, so new angles appear beyond ; position interpolation () and base scaling (larger ), plus a short fine-tune, extend the context.
- ALiBi adds to the logits with fixed slopes ; head has a half-life of positions, and it extrapolates well.
- The softmax ignores a constant added to a whole row, so the ALiBi biases and give the same weights.
11 Transformers and ViT
- A pre-LN transformer block is , ; attention is the only part that mixes tokens, and input and output have the same shape .
- A decoder-only language model is: token embedding plus positions, causal blocks, a final LayerNorm, and an unembedding (often tied, ) followed by a softmax over the vocabulary.
- A block with has parameters ( attention, MLP), for any number of heads.
- Forward FLOPs per token are about and training FLOPs about , where is the number of weights multiplied per token; the attention term dominates only when .
- Encoder-only models (BERT, ViT) are bidirectional; decoder-only models (GPT) use a causal mask and predict the next token; encoder–decoder models (T5, Whisper) add cross-attention in the decoder.
- With a causal mask, past keys and values never change, so a KV cache gives exact results; it holds numbers per sequence ( with grouped-query attention).
- Temperature sampling draws from : is greedy and is uniform.
- A ViT cuts an image into patches, embeds them with a convolution of kernel = stride = , adds a [CLS] token and learned position embeddings; for a new resolution it keeps and interpolates the position grid.
12 Training dynamics
- Gradient descent on a quadratic of curvature is stable only for . The sharpness of a network is often largest early, so warmup keeps the first steps below the limit.
- A schedule is a linear warmup followed by a decay: cosine, linear, or warmup–stable–decay (flat at , then a short decay at the end).
- Global-norm clipping multiplies all gradients by : the direction is kept and the norm becomes . Log the norm before clipping.
- Attention logits grow like the square of the weight scale; qk-layernorm bounds every logit by (Cauchy–Schwarz).
- Cross-entropy is unchanged by , so nothing pulls back; the z-loss does.
- An out-of-date Adam second moment gives huge steps after a quiet period; a lower (0.95) fixes it.
- Linear scaling rule: batch means learning rate for SGD, with a gradual warmup; the gain stops beyond the critical batch size.
- In a format with fraction bits, an update to is lost when ; mixed precision keeps fp32 master weights, accumulates in fp32, and in fp16 uses loss scaling.
13 Graph neural networks
- One message-passing layer: messages , a symmetric aggregation over the neighbours (sum, mean, max or attention), and an update . layers see the -hop neighbourhood.
- The GCN layer is with . Self-loops keep the node's own state; the normalization keeps the eigenvalues of in ; it acts as a low-pass filter on the graph.
- A message-passing layer is permutation-equivariant: . A sum, mean or max readout after it is permutation-invariant.
- No message-passing GNN separates two graphs that 1-WL colour refinement cannot separate (for example two triangles and a 6-ring). GIN, with sum aggregation and an MLP, reaches the 1-WL limit.
- On one-hot neighbour features, sum keeps the whole multiset, mean keeps only the proportions, and max keeps only the set of types present.
- Over-smoothing: converges to with , at rate . Deep plain GCNs lose everything except degree information.
- Over-squashing: an exponentially growing neighbourhood must pass through a few bottleneck edges into a fixed-size vector; the Jacobian decays with distance.
14 Self-supervised learning
- Self-supervised learning builds the training signal from unlabelled data. Without a second force, "make the two views close" collapses to a constant encoder.
- The InfoNCE loss is the mean cross-entropy of the rows of , with labels ; CLIP averages the row (image→text) and column (text→image) losses. In-batch items are the negatives.
- The gradient of a row loss is . A small puts the push on the hardest negatives; as the loss becomes a hinge on the hardest negative.
- For any critic, , and the bound can never exceed ; the optimal critic is the pointwise mutual information .
- SimCLR and CLIP avoid collapse with negatives; BYOL and SimSiam with a predictor and a stop-gradient; DINO with an EMA teacher plus centering and sharpening; MAE with a reconstruction target at a 75% mask ratio.
- Use the encoder output , not the projection-head output . Evaluate with a linear probe or k-NN on frozen features, fine-tune when labels are plentiful, and use CLIP zero-shot when classes are given only as text.
15 Mixture of experts
- A top- MoE layer computes : the router softmax picks the largest probabilities , and the gates are the raw probabilities (Switch) or renormalized over (Mixtral), which equals a softmax over the top- logits.
- Parameters grow with , compute per token with : total = shared + all experts, active = shared + experts per MoE layer (Mixtral 8×7B: 46.7B total, 12.9B active).
- The gate value multiplies the expert output so that the main loss sends a gradient to the router; a renormalized top-1 gate is always 1 and sends none.
- Without balancing, the router collapses onto a few experts. The Switch loss is for uniform routing and for full collapse.
- With the counts held fixed, : probability moves from busy experts to idle ones.
- Expert capacity is ; assignments beyond it are dropped and the token continues through the residual connection.
- The router z-loss fixes the free shift of the router logits and keeps them where bf16 is precise.
- Expert parallelism needs two all-to-alls per MoE layer in the forward pass and two in the backward pass; DeepSeek-V3 balances with a per-expert selection bias instead of a large auxiliary loss.
16 State-space models
- An SSM is , , sampled with step : , (state , input , as in S4).
- Zero-order hold: , ; bilinear: , .
- With fixed parameters (LTI) the recurrence is a causal convolution, with ; an FFT with zero padding to computes it in .
- If , then for every , so the recurrence cannot explode.
- S4 initializes with HiPPO and needs structure (normal plus low rank, or diagonal as in S4D) because HiPPO's eigenvectors are exponentially ill-conditioned.
- Mamba makes , , functions of the input; a small keeps the state, a large resets it; with , this is the gate .
- A time-varying linear recurrence has no single kernel, but the operator is associative, so a parallel scan computes it in depth.
- Attention trains in and stores a KV cache of ; an SSM trains in about and stores a state of , at the price of weaker exact recall.
17 Generalization
- When , infinitely many weight vectors fit the training data exactly; the training algorithm, not the loss, chooses one. This is implicit regularization.
- Gradient descent from on (step ) converges to the minimum-norm interpolant , because every update lies in the row space .
- From a start , gradient descent converges to , the interpolant closest to . Adam, another parametrization or another loss can choose a different solution.
- The minimum-norm fit has risk ; at the interpolation threshold the smallest singular value is near 0, so the noise is amplified and the test error peaks.
- Test error against model size can go down, up and down again (model-wise double descent); it also happens over training time (epoch-wise) and over sample size (more data can hurt near the threshold). Label noise makes the peak stronger.
- Ridge replaces by and removes the peak; early stopping after steps acts like ridge with .
- Networks fit random labels to 100% training accuracy, so any bound that depends only on the model class is vacuous for them; an explanation must use the data and the algorithm.