Breadth: deep learning, from initialization to diffusion and flow matching
Before this lesson: lesson 07 (AdamW and mixed precision in code) and lesson 08 (attention). Depth: the Deep learning track, especially initialization, normalization and residuals and training dynamics; the Optimization lessons on Adam and AdamW and schedules and clipping; the Generative models track for diffusion and flow matching. Time: about 95 minutes, plus the notebook.
Why this matters #
Deep-learning breadth questions come in phone screens, in "ML knowledge" rounds, and as follow-ups in ML-coding rounds ("why did you put the LayerNorm there?"). Research scientist loops often add a deep dive on generative models. Three failures are common:
- a popular but weak explanation: "BatchNorm works because it removes internal covariate shift" (this explanation is disputed);
- a wrong detail: "AdamW is Adam with L2 regularization";
- no number: "diffusion is slow" instead of "about 10–50 network calls with an ODE solver, 1–4 after distillation".
Use the four-part answer of lesson 09: one sentence that defines the thing, the formula or mechanism, one trade-off, one number or example.
1. Predict first #
2. The picture #
2.1 One number per layer #
Start with the simplest deep network: one number per layer, . The output is , and by the chain rule the gradient with respect to is the same product. With and the product is about : the gradient vanishes. With it is about : the gradient explodes. Most tools of this lesson keep the per-layer gains near 1, or let training survive when they are not:
| Tool | What it does to the gain |
|---|---|
| initialization (Xavier, He) | sets the gain to 1 at step 0 |
| normalization (BatchNorm, LayerNorm, RMSNorm) | resets the scale of the activations at every layer and every step |
| residual connection | adds an identity path, so the gain cannot fall below the identity |
| gradient clipping | caps the size of one step when a gain blows up |
| warmup | keeps the steps small while the curvature and Adam's statistics settle |
| Adam | gives each parameter its own step scale, about |
Move the gain below and above 1. The plot shows the expected size (RMS) of the signal after each block, on a log scale. In a plain stack it is : it vanishes or explodes. In a residual stack the branch adds to an identity path, so the signal never vanishes, but it grows like . Scaling each branch by (GPT-2 style) or normalizing its input (pre-LN) keeps the growth slow.
2.2 Initialization: keep the variance constant #
A layer computes . If the weights are random with variance , each output adds up random terms, so its variance is about times the input's second moment. A ReLU then sets half of the values to zero, which halves the second moment. To keep the signal at the same size through many layers, choose for ReLU (He initialization); section 3.3 proves it.
Start with the preset of predict 1: width 512, 12 layers, weights with variance , ReLU. The blue line is the second moment of the activations in each layer (from a real random network), the dashed line is the theory. Switch to He () and the line becomes flat. The orange line is the second moment of the gradient in the backward pass: it shrinks or grows in the same way.
2.3 An architecture is an inductive bias #
An architecture fixes which inputs interact and which symmetry is built in; this is its inductive bias. A CNN mixes only nearby pixels and shares its weights across positions. An RNN reads one step at a time through a state of fixed size. A transformer lets every token interact with every other token, at a cost that grows like for tokens, and it knows the order only through positional information. Less built-in bias means more data is needed.
2.4 Three ways to turn noise into data #
- Autoregressive: generate one piece at a time, each conditioned on the pieces before it: sequential network calls for tokens.
- Diffusion: corrupt data with Gaussian noise in small steps, learn to predict the noise, and remove it step by step: about 10–1000 calls, each on the whole sample.
- Flow matching: join each noise sample to a data sample by a straight line, learn the average velocity at each point, and integrate an ODE: about 10–50 calls.
With Gaussian noise, diffusion and flow matching are one model family (section 3.7).
Start with 1 Euler step: every sample lands on 0, the mean of the data, and none on . Increase the number of steps and watch the samples split into the two data points. The faint lines are a few straight training paths from noise to data; they cross, so the learned field (arrows) is their average and the exact ODE paths curve. Try the uneven data: one step lands on the mean 0.4.
A deep ReLU network is initialized with Xavier initialization, , and all layers have width . What happens to the second moment of the activations from layer to layer?
With equal widths Xavier gives , so . Xavier assumes a unit gain near 0 (tanh, linear). ReLU sets half of the pre-activations to 0, which halves the second moment, so after layers it is times the start. He initialization, , adds the missing factor 2.
3. Definitions and main results #
3.1 Optimizers: SGD, momentum, Adam, AdamW #
Notation: are the parameters, the minibatch gradient at step , the learning rate. All operations on vectors are elementwise.
- SGD: .
- Momentum: and , with . It averages the gradient over about steps: it damps the zig-zag across a narrow valley and speeds up the travel along it.
- Adam: and ; bias corrections and ; update , where the small constant prevents a division by 0. Defaults: , (0.95 in LLM training), . The step of each coordinate is about times a signal-to-noise ratio, so it does not depend on the scale of the gradient. The bias corrections undo the zero start of and (lesson 07 proves it).
- AdamW: the Adam step plus a separate decay, (PyTorch's form). The weight decay is typically 0.1 in LLM training. It is applied to weight matrices; biases and normalization gains are usually excluded.
Proposition (L2 = weight decay for SGD, but not for Adam; Loshchilov and Hutter).
- L2 regularization adds to the loss, so the gradient becomes .
- SGD: . This is weight decay with rate per step: the same method.
- Adam: the term enters and and is then divided by . A weight with large gradients has a large , so its decay is small; a weight with small gradients is decayed strongly. No single gives every weight the same decay.
- AdamW applies the decay outside the adaptive step, so every weight shrinks by the same factor per step.
Worked example 4A puts numbers on step 3.
Which optimizer. SGD with momentum is still strong for CNNs on images. Transformers train much better with Adam-type methods, and AdamW is the default. Matrix optimizers such as Muon (orthogonalized momentum for weight matrices) are a newer option for large models.
3.2 Schedules, clipping, large batches, mixed precision #
- Warmup: raise linearly from about 0 to its peak over the first steps (often a few hundred to a few thousand). At initialization the curvature is high and Adam's rests on few samples; post-LN transformers diverge without warmup (section 3.4).
- Decay: a cosine schedule decays smoothly to about 10% of the peak at the planned last step. Warmup–stable–decay (WSD) keeps the peak and decays only in the last 10–20% of the steps, so a run can be extended from a checkpoint of the stable phase.
- Global-norm clipping: stack all gradients in one vector and use , often with . It keeps the direction and caps the step. Log before clipping: a rising norm warns of a loss spike.
- Large batches: for SGD, multiply by when the batch grows by (the linear scaling rule, Goyal et al., 2017), with warmup. The rule fails above a critical batch size. For Adam a common heuristic is for batch size .
- Mixed precision: compute the matrix products in 16 bits; keep fp32 master weights and accumulate sums in fp32. bf16 has the range of fp32 and needs no loss scaling; fp16 has a small range and needs loss scaling (multiply the loss by , divide the gradients by ). See lesson 07 for the details.
Switch between cosine and WSD, then press "extend the run by 50%". A cosine run must decay again from a high learning rate, because its decay depends on the planned length. A WSD run continues its stable phase and only moves the final decay, so the old checkpoints stay useful. Move the step slider to read .
3.3 Initialization from variance propagation #
Theorem. Let with ( is the fan-in). The entries are independent with mean 0 and variance , independent of , and every has the same second moment . Then
If is symmetric about 0, then .
Proof.
- . Each term has mean , so .
- For : . The cross terms vanish.
- So .
- ReLU keeps when and outputs 0 otherwise. By symmetry, the positive half carries half of : .
Consequences.
- ReLU: the second moment stays constant from layer to layer when , that is (He or Kaiming initialization).
- tanh or linear units (gain about 1 near 0): (LeCun). The backward pass gives the same condition with ; Xavier (Glorot) initialization takes the compromise .
- All weights equal to 0 (or to one constant) fails: every unit of a layer gets the same gradient, and the units stay identical. Random initialization breaks this symmetry. Biases start at 0.
- Transformers: GPT-2 uses a fixed standard deviation of 0.02 and scales the output projection of each residual branch by , with the number of residual layers, so the residual stream does not grow with depth.
3.4 Normalization and residual connections #
For one group of numbers with mean and variance : and , with a small constant (often ), a learned gain and a learned shift . The norms differ in the group of numbers they use:
| Norm | Normalizes over | Train vs eval | Used in |
|---|---|---|---|
| BatchNorm | one channel, over the batch (and space) | batch statistics in training, running averages in eval | CNNs |
| LayerNorm | the features of one token or sample | the same function | original transformer, BERT, GPT-2 |
| RMSNorm | the features of one token, with no mean and no : | the same function | T5, Llama and most recent LLMs |
| GroupNorm | groups of channels of one sample | the same function | small-batch vision, diffusion U-Nets |
Here is the number of features. Why normalization helps. It keeps the activations in a good range at every step, not only at initialization, and it makes the output invariant to the scale of the incoming weights. Santurkar et al. (2018) showed that BatchNorm's benefit is not explained by less "internal covariate shift"; it makes the loss and its gradients smoother, which allows larger learning rates.
Problems of BatchNorm. The output for one sample depends on the rest of the batch. The
statistics are noisy with a small batch per GPU; training and eval compute different functions
(forgetting model.eval() is a classic bug); autoregressive decoding has no batch; and statistics
over the time axis leak future tokens into a causal model. So transformers use LayerNorm or RMSNorm.
Residual connections. . With , the Jacobian is
Expanding the product gives the identity plus other terms, so the gradient reaches every layer directly, however small the are. A plain stack has the product , which vanishes or explodes. This made networks with more than 100 layers trainable (ResNet).
Pre-LN vs post-LN. Post-LN (the original transformer) is : the norm sits on the residual path. Pre-LN (GPT-2 and later) is , plus one final norm before the output head: the residual path is a clean identity. Xiong et al. (2020) showed that post-LN has large gradients near the output at initialization, so it needs warmup; pre-LN trains stably at depth, even without warmup. The price of pre-LN: the norm of the residual stream grows with depth, so each later block changes it relatively less.
A CNN with BatchNorm is trained with a batch of 2 images per GPU, without synchronizing the statistics. Training accuracy is fine, but in eval mode the validation accuracy is much worse. What is the most likely cause?
In training, BatchNorm normalizes with the mean and variance of the current batch; in eval it uses running averages. With 2 samples the batch statistics are very noisy, so the two modes compute different functions. Fixes: synchronized BatchNorm across GPUs, GroupNorm or LayerNorm, a larger batch per GPU, or frozen statistics from a pretrained model.
3.5 Regularization in deep networks #
- Dropout: in training, set each activation to 0 with probability and scale the others by (inverted dropout), so the expected value does not change; at eval, do nothing. It acts like an average over many sub-networks. Single-epoch LLM pretraining often uses ; fine-tuning on small data often uses about 0.1.
- Weight decay (section 3.1).
- Data augmentation encodes symmetries you know (flips, crops, colour changes). It is the strongest regularizer in vision.
- Label smoothing trains on the target for classes and smoothing (often 0.1). It stops the logits from growing without bound.
- Early stopping on a validation metric.
See the regularization lesson of the Deep learning track.
3.6 Architectures and their inductive biases #
| Architecture | Built-in assumption | Cost per layer ( positions, width ) | Weak spot |
|---|---|---|---|
| CNN | locality, translation equivariance (shared kernels) | for kernel size | long-range context needs depth or pooling |
| RNN / LSTM | sequential order, a state of fixed size | , sequential in | no parallel training over time; gradient paths of length |
| Transformer | every pair interacts; order only through positional information | , parallel | cost quadratic in ; weak bias, needs much data |
| ViT | a transformer on patches, for an image | as the transformer | weaker bias than a CNN: needs large-scale pretraining or strong augmentation |
| GNN | permutation equivariance on a graph | for edges , nodes | over-smoothing with depth |
Formulas that interviewers ask:
- Conv output size: for input size , padding , kernel , stride . For , , , : .
- Receptive field of stacked convolutions with stride 1: . Two layers see with 18 weights per channel pair instead of 25, and add one more nonlinearity (the VGG argument).
- Attention: . If the entries of a query and a key are independent with mean 0 and variance 1, then has variance . Dividing by brings it back to 1, so the softmax does not saturate at initialization.
- LSTM: the cell state is updated by addition, (forget gate , input gate , candidate ). With near 1 the gradient flows along without repeated products with a weight matrix, so it keeps longer dependencies than a plain RNN.
- Transformer parameters: about per block: for and for an MLP with hidden size . GPT-2 small ( blocks, , vocabulary 50,257, context 1,024): $12 \cdot 12 \cdot 768^2 = 84.9$M in the blocks, plus $38.6$M token and $0.8$M position embeddings: about $124$M.
Newer blocks: a mixture of experts sends each token to the top- of expert MLPs, so the parameters grow with and the compute per token with (mixture of experts); a state-space model (Mamba) replaces attention by a linear recurrence, linear in but weaker at exact recall from a long context (state-space models).
3.7 Generative models: autoregressive, diffusion, flow matching #
Notation: is a clean data sample and is Gaussian noise of the same shape. Time conventions differ: in DDPM, is data; in flow matching as written here, is noise and is data.
Autoregressive models. The chain rule of probability gives .
- Training: minimize with teacher forcing; all positions train in parallel under a causal mask.
- Sampling: sequential calls; a KV cache makes each call cheap, but the calls cannot run in parallel.
- Likelihood: exact. Natural for discrete tokens; continuous data first needs a tokenizer (for example a VQ autoencoder). At sampling time the model conditions on its own outputs, which it never saw in training, so errors can compound (exposure bias).
VAE and GAN in one paragraph each. A VAE trains an encoder and a decoder by maximizing the ELBO (a reconstruction term minus a KL term to the prior); sampling is one decoder call; the likelihood is only bounded; samples tend to be blurry. A GAN trains a generator against a discriminator in a minimax game; sampling is one call; there is no likelihood; training can be unstable, and mode collapse (the generator covers only part of the data) is the typical failure.
Diffusion (DDPM). The forward process is for , where falls from about 1 (clean) to about 0 (pure noise).
- Training: sample and , form , and minimize . This is a reweighted ELBO. The network is a denoiser with three equivalent readings: the noise ; the clean estimate ; and the score (Tweedie's formula).
- Sampling: ancestral sampling takes steps ( in Ho et al., 2020). The deterministic DDIM sampler and higher-order ODE solvers need about 10–50 network calls; distillation and consistency models need 1–4.
- Likelihood: a bound (the ELBO), or exact through the probability-flow ODE at a high cost.
- Conditioning: classifier-free guidance drops the condition for about 10–20% of the training examples, then samples with . is plain conditional sampling; trades diversity for fidelity to .
Flow matching (rectified flow). The path is for .
- Training: sample , and , form , and minimize .
- Sampling: start from and integrate from to (Euler or Heun, about 10–50 steps).
Theorem (what flow matching learns). Let and be independent. The minimizer of the loss is the conditional mean velocity
If is regular enough for the ODE to have unique solutions (for example, Lipschitz in ), the ODE started from has the same distribution as at every ; at it gives the data distribution.
Why this is true, in one line. A regression with squared loss learns the average target at each input, and moving probability mass with its average velocity keeps the densities right.
Proof (sketch).
- The loss is a regression of the target on the input .
- For fixed , is minimized over vectors by the conditional mean . To see it, write with ; the cross term has conditional mean 0, so the loss is plus a constant.
- Along each training line, . So is the average velocity of the probability mass that passes through at time . A field that moves the mass with its average velocity keeps the same densities (the continuity equation).
Diffusion and flow matching are one family (Gao et al., 2024). Both use a Gaussian path : flow matching has , ; DDPM has , . The network outputs convert into each other. With and , the identity gives
DDIM sampling is the same as Euler sampling of the flow-matching ODE, once you rescale and match the times by their noise level . What really differs: (1) the noise schedule, (2) the network output (, or ), (3) the weight of each in the loss, and (4) a stochastic (SDE) or deterministic (ODE) sampler.
"Straight paths" is only half true. Each training line is straight. But lines from different pairs cross, and averages them, so the learned paths curve. One Euler step from lands on , the mean of the data (predict 2; worked example 4B). Fixes for few-step sampling: reflow (retrain on the model's own noise–sample pairs; Liu et al., 2022), distillation and consistency models.
| Autoregressive | Diffusion | Flow matching | VAE | GAN | |
|---|---|---|---|---|---|
| network learns | the noise (a denoiser, equivalent to the score) | the velocity | encoder , decoder | generator against a discriminator | |
| training loss | cross-entropy | MSE on (a weighted ELBO) | MSE on the velocity | ELBO: reconstruction + KL | minimax game |
| network calls per sample | , sequential | 10–1000 (1–4 distilled) | 10–50 (1–4 after reflow or distillation) | 1 | 1 |
| likelihood | exact | bound, or exact through the ODE (costly) | exact through the ODE (costly) | bound | none |
| typical failure | slow sampling, compounding errors | slow sampling | slow sampling, curved paths | blurry samples, posterior collapse | mode collapse, unstable training |
| typical use | LLMs, code, other discrete tokens | images, video, audio, weather ensembles | images, video, science | the latent space of latent diffusion | fast one-step generation, adversarial loss terms |
Which to choose. Discrete sequences (text, code): autoregressive. Continuous high-dimensional data (images, audio, physical fields): diffusion or flow matching, usually in the latent space of an autoencoder, which makes each call much cheaper. Sampling speed first (large ensembles, real time): a distilled or reflowed model, or a GAN, and check that the diversity survives. An exact density (anomaly scores, likelihood-based inference): autoregressive or a normalizing flow.
Which of these models gives an exact log-likelihood of a sample in one forward pass?
An autoregressive model computes exactly, with one causal forward pass over the whole sequence. A VAE gives only a lower bound (the ELBO); a diffusion model gives a bound, or an exact value only by integrating the probability-flow ODE with many calls; a GAN gives no likelihood at all.
3.8 Debugging a training run #
Two checks before any long run:
- The first loss. A fresh classifier over classes is close to uniform, so its cross-entropy loss is about (2.30 for 10 classes, 6.91 for 1,000).
- Overfit one small batch to a loss near 0. If this fails, there is a bug, not a tuning problem.
| Symptom | Common causes | First checks and fixes |
|---|---|---|
| first loss far from | last layer too large at init, unnormalized inputs, wrong loss reduction, wrong labels | small init of the last layer; check the inputs, the reduction and the label alignment |
| cannot overfit one batch | inputs and targets misaligned, zero_grad missing, frozen or detached parameters, softmax applied before CrossEntropyLoss |
print shapes and a few labels; check requires_grad |
| loss becomes NaN or inf | learning rate too high, fp16 overflow, or a division by 0, a bad sample | find the first non-finite tensor; lower ; bf16 or loss scaling; add a small constant |
| loss flat from the start | learning rate far off, dead ReLUs, bad init, unnormalized inputs | learning-rate range test; activation statistics per layer |
| spike in mid-training | a bad batch, too high for the current curvature, an outdated Adam , growing attention or output logits | gradient-norm history; rewind and skip the batch; clipping; ; qk-norm; z-loss |
| training loss falls, validation loss rises | overfitting | regularize, augment, stop early, get more data |
| validation loss below training loss | dropout and augmentation act only in training; an easier validation set | evaluate the training set in eval mode |
| good in training, bad in serving | model.eval() forgotten (BatchNorm, dropout), different preprocessing |
run both pipelines on the same input |
Read the loss curve and pick the most likely cause before the figure explains it. Go through all six cases. The blue curve is the training loss and the orange curve is the validation loss.
A new 10-class classifier shows a cross-entropy loss of 46 at step 0. What should you check first?
A freshly initialized classifier should predict nearly uniform probabilities, so its loss is about . A loss of 46 means very confident wrong logits: a last layer initialized too large, inputs that are not normalized (for example pixel values 0–255), or a loss summed instead of averaged. Fix it before tuning anything else.
Answers to section 1. (1) : much smaller. Each layer has , but each ReLU halves the second moment. The RMS of the signal falls by , and the backward pass shrinks the gradients in the same way. He initialization, , keeps the second moment at its starting value. (2) Every sample lands on 0, the mean of the data, and none on . At the position says nothing about which data point its line goes to, so , and one step gives .
4. Worked example #
A. Adam + L2 vs AdamW on two weights. Both weights start at . Their gradients are pure noise with mean 0 and RMS 10 ("noisy") or RMS 0.01 ("quiet"). Take and .
- Adam + L2 adds to each gradient. The decay part of the step is about , with .
- Noisy weight: , so the decay is per step: about after 1,000 steps.
- Quiet weight: , so the decay is about per step, 100 times more. The simulation in section 5 gives after 1,000 steps.
- AdamW: both shrink by per step, so , whatever their gradient scale (the simulation gives 0.904, because the noisy gradient steps add a small random walk).
B. Flow matching on two points. Data with probability each, noise , path .
- Given , . Bayes' rule gives the posterior mean .
- From : .
- One Euler step from : , so .
- Two Euler steps of size 0.5: first at . There and , so .
- The exact ODE sends every to and every to .
The last Euler step to always lands on , the posterior mean at the current point. Few steps give averages (blurry samples); more steps commit to one mode.
C. One DDIM step by hand. A DDPM model at a step with sees and predicts . So .
- Clean estimate: .
- Score: .
- Deterministic DDIM step to : keep and and mix them again, .
5. In code #
NumPy and SciPy check the claims of sections 3 and 4. The notebook has these cells and the exercises.
import numpy as np
from scipy.integrate import solve_ivp
# (A) Adam + L2 vs AdamW on two groups of 1,000 weights (gradients are pure noise)
def run(decoupled, steps=1000, lr=1e-3, wd=0.1, b1=0.9, b2=0.999, eps=1e-8):
rng = np.random.default_rng(0)
w = np.ones((2, 1000)) # row 0: noisy weights, row 1: quiet weights
scale = np.array([[10.0], [0.01]]) # RMS of the gradient noise per row
m, v = np.zeros_like(w), np.zeros_like(w)
for t in range(1, steps + 1):
g = scale * rng.standard_normal(w.shape)
if decoupled:
w = w * (1 - lr * wd) # AdamW: decay outside the adaptive step
else:
g = g + wd * w # Adam + L2: decay inside the gradient
m = b1 * m + (1 - b1) * g
v = b2 * v + (1 - b2) * g * g
mh, vh = m / (1 - b1**t), v / (1 - b2**t)
w = w - lr * mh / (np.sqrt(vh) + eps)
return w.mean(axis=1)
print("Adam + L2:", run(False).round(3)) # [0.99 0.262]
print("AdamW :", run(True).round(3)) # [0.904 0.904]
# Predict 1: 12 ReLU layers of width 512, averaged over 30 random networks
x = np.random.default_rng(0).standard_normal((128, 512))
for name, var in [("1/n", 1 / 512), ("2/n (He)", 2 / 512)]:
ms = []
for seed in range(30):
r = np.random.default_rng(seed)
h = x
for _ in range(12):
h = np.maximum(h @ (np.sqrt(var) * r.standard_normal((512, 512))), 0)
ms.append(np.mean(h ** 2))
print(name, f"{np.mean(ms):.2e}") # 1/n 2.41e-04 (2^-12 = 2.44e-04); 2/n (He) 9.88e-01
# (B) flow matching on data {-1, +1}: one Euler step, two steps, and the exact ODE
def velocity(y, t):
"""Exact field E[x - eps | x_t = y]; E[x | x_t = y] = tanh(t y / (1 - t)^2)."""
return (np.tanh(t * y / (1 - t) ** 2) - y) / (1 - t)
eps = np.array([-1.3, -0.2, 0.05, 0.5, 2.0]) # five noise samples
print(eps + 1.0 * velocity(eps, 0.0)) # one step: [0. 0. 0. 0. 0.]
y_half = 0.5 + 0.5 * velocity(0.5, 0.0) # two steps from eps = 0.5
print(round(y_half, 3), round(y_half + 0.5 * velocity(y_half, 0.5), 3)) # 0.25 0.462
sol = solve_ivp(lambda t, y: velocity(y, t), (0.0, 0.999), eps, rtol=1e-10, atol=1e-12)
print(sol.y[:, -1].round(3)) # [-1. -0.998 0.997 0.999 1.001]
The ODE stops at because is singular at . There the state still holds a small share of noise (), so the values sit within about 0.003 of . Every negative goes to and every positive goes to .
6. Where it shows up #
- ML practice. A standard transformer recipe is sections 3.1–3.5 together: AdamW, warmup and a cosine or WSD decay, clipping at 1.0, bf16 with fp32 master weights, pre-LN with RMSNorm. When a run fails, the table of section 3.8 is the first pass. In ML-coding rounds (lessons 07–08) these are the follow-up questions.
- Generative AI. Text and code models are autoregressive. Image and video models (Stable Diffusion 3, FLUX, video diffusion models) use diffusion or flow matching in a latent space, with classifier-free guidance and few-step samplers.
- ML for science. Many weather and Earth-system models are transformers on patches of gridded fields; others, such as GraphCast, are GNNs on a mesh. Small batches per GPU rule out BatchNorm. Probabilistic forecasts need generative models: GenCast samples weather ensembles with a diffusion model. Ensemble size times calls per sample decides whether you need few-step sampling. Inductive bias decides the backbone: CNNs and neural operators for regular grids, GNNs for meshes and sensor networks, equivariant networks for molecules.
7. Common mistakes #
- "AdamW is Adam with L2." In Adam, the L2 gradient is divided by ; AdamW decouples the decay so that every weight shrinks by .
- "BatchNorm works by removing internal covariate shift." Say what it does: it normalizes each channel, smooths the optimization and allows larger learning rates.
- Forgetting
model.eval()(BatchNorm, dropout), or scaling again at test time with inverted dropout, which already scales in training. - Xavier or LeCun initialization for a deep ReLU network (each layer halves the second moment; use He), or zero initialization of all weights (no symmetry breaking).
- "Flow-matching paths are straight, so one step is enough." Only each training line is straight; the learned field curves, and one step gives the data mean.
- "Diffusion and flow matching are different model classes." With Gaussian paths they are one family. Also watch the time convention: is data in DDPM and noise in rectified flow.
8. Check yourself #
- Why do LLM recipes use instead of Adam's default 0.999?
Answer
averages over about steps: 20 steps for 0.95, 1,000 for 0.999. With 0.999, a parameter whose gradients were tiny for a long time has a tiny . When its gradient suddenly grows, follows within about 10 steps but lags, so the update is too large for many steps, often in many parameters at once: a loss spike. A lower lets follow the gradient scale faster. - Estimate the parameters of GPT-2 medium: 24 blocks, , vocabulary 50,257, context 1,024.
Answer
Blocks: $12 \cdot 24 \cdot 1024^2 = 302$M. Token embeddings $50{,}257 \cdot 1024 = 51.5$M, position embeddings $1.0$M. Total about $355$M (biases and norms add less than 0.1%). - Why are attention scores divided by ? What goes wrong without it for ?
Answer
With unit-variance, independent entries, has variance . Without the scaling its standard deviation is , so the softmax is close to one-hot at initialization, and its gradients are close to 0 for most entries. Dividing by gives scores of variance 1. - A flow-matching network outputs . How do you get its estimate of the clean
sample?
Answer
, from . A single Euler step from to computes exactly this at , where says nothing about the data, so : the mean of the data, an average of all modes. - Inverted dropout with : an activation is 3.0. What values can it take in training, and
what is its expected value?
Answer
0 with probability 0.2, and with probability 0.8. The expected value is , the same as without dropout, so nothing changes at eval. - What is the output size of a convolution with input 64, kernel 5, stride 2, padding 2? And the
receptive field of three stacked convolutions with stride 1?
Answer
. Receptive field , so .
What weight variance does He initialization use, and why the factor 2?
. , and ReLU keeps only half of the second moment, so keeps it constant.
12 ReLU layers with and . What is the second moment of the last layer?
: each layer halves it.
How does BatchNorm differ between training and evaluation?
Training: normalize with the mean and variance of the current batch (and update running averages). Eval: normalize with the running averages, so one sample's output no longer depends on the batch.
Write pre-LN and post-LN for one transformer sub-layer.
Post-LN: . Pre-LN: ; the residual path stays a clean identity and training is stable without warmup.
In inverted dropout with drop probability , what happens to the kept activations in training and at eval?
In training they are multiplied by , so the expected value is unchanged; at eval nothing is done.
Why does AdamW decay weights outside the adaptive step?
An L2 term inside Adam is divided by , so weights with large gradients are barely decayed. AdamW shrinks every weight by , independent of its gradient scale.
How does the cost of a transformer layer grow with the sequence length , and why?
for attention, because every token attends to every other token (plus for the projections and the MLP).
What is the training loss of a DDPM diffusion model?
with : predict the added noise (a reweighted ELBO).
What does a flow-matching network learn, and what does one Euler step from noise give?
The conditional mean velocity . One Euler step from gives , the mean of the data.
What should the first loss of a fresh -class classifier be?
About (2.30 for ), because the initial predictions are nearly uniform.
9. Interview angle #
Recognize the question from the wording.
| The question says | Start with |
|---|---|
| "how do you initialize a deep network?" | the variance theorem, ReLU halves, He , symmetry breaking |
| "why residual connections?", "why can ResNets be deep?" | the Jacobian ; the identity path for the gradient |
| "BatchNorm vs LayerNorm", "what changes at inference?" | the axis of the statistics; running averages; small batches; why transformers use LN/RMSNorm |
| "SGD vs Adam", "why AdamW?" | per-coordinate steps, bias correction, the decoupling proposition, , |
| "why warmup?", "loss spikes" | curvature at init, Adam's young , post-LN; clipping, , qk-norm |
| "CNN or ViT?", "why ?" | inductive bias vs data; variance of |
| "diffusion vs flow matching vs autoregressive" | what is learned, the loss, the calls, the likelihood, when to use; "one family" |
| "my training does not work" | first loss , overfit one batch, then the symptom table |
Typical questions and short model answers.
- "How do you initialize a deep ReLU network, and why?" — "I keep the variance of the activations constant from layer to layer. Each pre-activation is a sum of terms, so its variance is times the second moment of the input. ReLU zeroes half of the values, so it halves the second moment. So I use , He initialization. With , a 12-layer network shrinks the signal to , and the gradients shrink the same way."
- "BatchNorm vs LayerNorm?" — "BatchNorm normalizes each channel over the batch; in training it uses the batch statistics and in eval running averages. That makes it depend on the batch size and makes training and eval different functions. LayerNorm normalizes over the features of one sample, so it is the same in training and eval and works with batch size 1 and with autoregressive decoding. Transformers use LayerNorm or RMSNorm, which drops the mean. BatchNorm still works well in CNNs with large batches."
- "Why AdamW and not Adam with L2?" — "For SGD they are the same. In Adam the L2 gradient goes into and and is divided by , so weights with large gradients are barely decayed. AdamW applies directly, so every weight shrinks at the same rate. Typical LLM values: , , warmup, then cosine decay."
- "Explain diffusion vs flow matching vs autoregressive." — "Autoregressive models predict the next token with cross-entropy, give an exact likelihood, and need one call per token. Diffusion adds Gaussian noise and trains a network to predict it; sampling removes noise in 10–50 ODE steps, or 1–4 after distillation. Flow matching joins noise and data by straight lines and regresses the velocity; the network learns the average velocity, so the paths curve and one step gives the data mean. With Gaussian paths, diffusion and flow matching are the same family with different schedules, outputs and loss weights. Text: autoregressive; images and other continuous data: diffusion or flow matching in a latent space."
- "Why residual connections?" — "The block computes , so its Jacobian is . The product over many blocks contains the identity, so the gradient reaches early layers even when the 's are small. Without it the product of Jacobians vanishes or explodes. In transformers, pre-LN keeps this identity path free of normalization, which is why it trains without warmup."
- "The loss is NaN after 300 steps. What do you do?" — "Find the first non-finite tensor, then check the usual causes in order: a learning rate too high (try 3× smaller), fp16 overflow (bf16 or loss scaling), a or a division by 0 in my code, a bad sample. I log the gradient norm and use clipping. Before that, I check that the first loss was and that the model can overfit one batch."
Typical follow-ups. "What happens with batch size 1 in BatchNorm during training?" (in a conv layer the statistics come only from the spatial positions of one image, so they are very noisy; without spatial positions every value equals the batch mean, the normalized output is 0, and PyTorch raises an error). "Why does post-LN need warmup and pre-LN not?" (post-LN has large gradients near the output at initialization; pre-LN keeps a clean identity path). "What is classifier-free guidance, and what does a large do?" (the formula of section 3.7; more fidelity to the prompt, less diversity). "How many parameters per transformer block?" ().
Mock prompt (debug this training run). "A 1.3B-parameter pre-LN transformer trains in bf16 with AdamW (, , 2,000 warmup steps, clipping at 1.0). At step 41,000 the loss jumps from 2.4 to 6.8 and the gradient norm from 0.3 to 30; it recovers to 2.9 after 2,000 steps. What do you do?" A strong answer contains: rewind to a checkpoint a few hundred steps before the spike; inspect or skip the batches around step 41,000, and replay the same data order to test whether the data caused it; per-layer gradient norms, the largest attention logit, the output logits and the Adam update size; mitigations ordered by cost (lower peak or longer warmup, , qk-norm, z-loss, fp32 for softmax, norms and loss); a cheaper reproduction on a small model at a higher learning rate; an alert on the gradient norm.
10. Practice #
The notebook for this lesson runs in Colab, in NumPy. Each exercise has a check cell and a folded solution:
forward_variance: the second moment per layer of a deep ReLU MLP for several initialization scales; check the factor and the flat line for He.batchnorm_forward: BatchNorm in training and eval mode with running statistics; check against a direct computation and the batch-size-1 failure.inverted_dropout: dropout with the scaling; check that the expected value is preserved and eval is the identity.fm_velocityandeuler_sample: the exact flow-matching velocity for two-point data and Euler sampling with steps; check that one step gives the mean and many steps give the two points.first_loss: the cross-entropy of a randomly initialized softmax classifier; check that it is close to with a small last layer and far from it with a large one.
Timed practice (25 minutes each, talking aloud): "derive He initialization"; "implement LayerNorm and BatchNorm forward, and say what changes at eval"; "explain diffusion vs flow matching on a whiteboard"; "the loss spikes at step 41,000: debug it"; "count the parameters of a transformer block"; the questions on initialization, normalization and optimization in Kashani and Ivry, Deep Learning Interviews (see below).
Say it aloud drill. Start a 2-minute timer for each question of section 9. Answer with the four parts (definition, mechanism, trade-off, number), record yourself, and compare with section 3.
11. Watch and read #
- Simon J. D. Prince, Understanding Deep Learning (MIT Press, 2023, free PDF): §6.3–6.4 (momentum, Adam), §7.5 (initialization), §11.2–11.4 (residual blocks, batch normalization), chapter 12 (transformers), chapter 18 (diffusion models).
- Ruiqi Gao, Emiel Hoogeboom, Jonathan Heek, Valentin De Bortoli, Kevin Murphy and Tim Salimans (2024), Diffusion Meets Flow Matching: Two Sides of the Same Coin: DDIM as the Euler sampler of flow matching, and why the paths are not straight.
- Loshchilov and Hutter (2019), Decoupled Weight Decay Regularization: §2 (Adam + L2 vs AdamW).
- He, Zhang, Ren and Sun (2015), Delving Deep into Rectifiers: §2.2 (the derivation of He initialization).
- Xiong et al. (2020), On Layer Normalization in the Transformer Architecture: pre-LN vs post-LN and warmup.
- Santurkar, Tsipras, Ilyas and Madry (2018), How Does Batch Normalization Help Optimization?.
- Lipman et al. (2023), Flow Matching for Generative Modeling, and Liu, Gong and Liu (2022), Flow Straight and Fast: rectified flow.
- Andrej Karpathy, A Recipe for Training Neural Networks: the debugging habits of section 3.8.
- Shlomo Kashani and Amir Ivry, Deep Learning Interviews (free): chapter 8 (layers, training, optimization) with solutions.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.