Your technical library
Deep Learning
24 modules · 133 topics
About this book
Deep Learning
This course teaches neural networks end to end: how to design the computation, derive the path the gradient takes back through it, keep training stable at depth, and reason about compute, memory and data at scale — up to how today's language models are pretrained, served, adapted and evaluated. Depth is the point: attention, mixture of experts, the evidence lower bound, diffusion's training objective and the memory cost of the key–value cache are derived step by step, not summarised. It builds on Mathematics and Machine Learning and teaches none of its own mathematics.
It is a chain of problems. A linear model cannot learn its own features (neural networks as functions); a network's gradient must be computed (computing gradients); deep networks do not train until the signal is kept alive through them (training deep networks stably, optimisers for networks); and huge networks should overfit but do not (generalisation in over-parameterised networks). Convolutional networks, representation learning and sequence models before attention give images and sequences structure, and the transformer replaces recurrence with attention.
Then the cost of scale: compute and number formats, efficient attention, state-space and recurrent alternatives and mixture of experts. The language-model pipeline follows — pretraining language models, distributed training, inference, serving systems, model compression, adapting and grounding pretrained models with fine-tuning and retrieval, and inference-time reasoning. Generative models of continuous data and multimodal models go beyond text, evaluation and failure measures models honestly, and case studies close the course. A reader who wants only language models can skip most of the convolution module, continuous generative models and multimodal models.
133 topics across 24 modules, in dependency order.
This course teaches none of its own mathematics. Calculus, linear algebra, probability, optimisation and information theory live in Mathematics, and every lesson names the topics it needs under “Before this topic”. Reinforcement learning for language models — RLHF, DPO, GRPO, RLVR — belongs to the Reinforcement Learning course and is deliberately not covered here.
133 of 133 topics are authored; the rest are labelled planned and excluded from progress. Glossary and decision-guide entries cover the authored material and grow with the course.
Read at your own pace. Each topic is one continuous page; mark it done as you finish.
Start with 01.1 · The multilayer perceptron: learning the features instead of fixing themReview what you have finished↷ 0 skipped topics- 03.1Vanishing and exploding gradients: a product of many Jacobians
- 03.2Activation functions: the derivative decides whether signal survives
- 03.3Initialisation: choose weight variance so signal neither grows nor shrinks
- 03.4Gradient clipping: cap the step, keep the direction
- 03.5Residual connections: an identity path for the gradient
- 03.6Batch normalisation: standardise each feature over the batch
- 03.7Layer norm and RMSNorm: normalise each example on its own
- 04.1Network loss surfaces: non-convex, but not the way you fear
- 04.2Momentum: average the gradient to cross a ravine
- 04.3Adaptive learning rates: scale each parameter's step by its gradient history
- 04.4Adam: momentum and adaptive scaling, bias-corrected
- 04.5AdamW: weight decay is not an L2 penalty under Adam
- 04.6Learning-rate schedules: warm up, then decay
- 04.7Batch size: the linear scaling rule and where it stops
- 05.1Double descent: test error falls again past the interpolation threshold
- 05.2Implicit bias: which of many perfect fits gradient descent finds
- 05.3Dropout: train a random sub-network each step
- 05.4Data augmentation: teach invariances by transforming the data
- 05.5Label smoothing: stop pushing logits to infinity
- 05.6Early stopping: training time as a regulariser
- 05.7Reading a training run: curves, norms and the fix each symptom calls for
- 06.1The convolution: locality and weight sharing
- 06.2Pooling, stride and receptive fields: trading resolution for context
- 06.3CNN architectures: LeNet, AlexNet and VGG as a story of depth and compute
- 06.4ResNets: residual connections as an architecture
- 06.5Transfer learning: reuse features learned on a large dataset
- 07.1Embedding layers: a lookup table is a linear layer on one-hot input
- 07.2Word embeddings: meaning from the company a word keeps
- 07.3Autoencoders: learn a code by reconstructing the input
- 07.4Self-supervised learning: the data supplies the label
- 07.5Contrastive learning: pull views together, push others apart
- 09.1Self-attention: every token queries every token
- 09.2Causal masking: every next-token prediction in one pass
- 09.3Multi-head attention: several attention patterns in parallel
- 09.4Feed-forward sublayers: where most parameters live
- 09.5The transformer block: attention and MLP on a residual stream
- 09.6Absolute position encodings: tell attention where each token is
- 09.7RoPE: relative position from rotating queries and keys
- 09.8Relative position biases: T5 buckets and ALiBi
- 09.9Pre-norm and post-norm: keeping deep transformers trainable
- 09.10Encoder, decoder, encoder–decoder: the mask decides the model
- 09.11Vision transformers: image patches as tokens
- 14.1Tokenisation: byte-pair encoding from a corpus
- 14.2Tokenisation artefacts: digits, spelling and languages
- 14.3Web text filtering: from crawl to training text
- 14.4Deduplication: exact and near-duplicate removal at scale
- 14.5Data mixtures: how much of each domain
- 14.6Neural scaling laws: loss as a power law in size, data and compute
- 14.7Compute-optimal training: the Chinchilla allocation
- 14.8Beyond compute-optimal: inference cost and finite data
- 15.1Training memory: 16 bytes per parameter plus activations
- 15.2Collective communication: all-reduce and its cost
- 15.3Data parallelism: replicate the model, all-reduce the gradients
- 15.4ZeRO and FSDP: shard optimiser state, gradients and weights
- 15.5Tensor parallelism: split each matmul across devices
- 15.6Pipeline parallelism: layers on different devices
- 15.7Expert parallelism: all-to-all token dispatch
- 15.8Choosing a parallelism layout
- 16.1Autoregressive decoding: sampling one token at a time
- 16.2Beam search: approximate the most likely sequence
- 16.3The KV cache: store keys and values instead of recomputing
- 16.4MQA and GQA: share keys and values across heads
- 16.5Multi-head latent attention: cache a low-rank latent
- 16.6Prefill and decode: two phases, two bottlenecks
- 19.1In-context learning: a task specified in the prompt
- 19.2Supervised fine-tuning: from base model to assistant
- 19.3Catastrophic forgetting: what fine-tuning overwrites
- 19.4LoRA: learn a low-rank weight update
- 19.5QLoRA: LoRA on a 4-bit base
- 19.6Extending context: rescaling RoPE
- 19.7Dense retrieval: find passages by embedding similarity
- 19.8Retrieval-augmented generation: ground the answer in documents
- 19.9Long context or retrieval
- 21.1VAEs: an autoencoder you can sample
- 21.2The reparameterisation trick: sample noise, not parameters
- 21.3GANs: a generator trained against a discriminator
- 21.4GAN training dynamics: saturation and mode collapse
- 21.5Normalizing flows: exact likelihood by invertible maps
- 21.6Denoising diffusion: learn to reverse gradual noising
- 21.7Score matching: learn the gradient of log-density
- 21.8Fast diffusion sampling: DDIM and ODE solvers
- 21.9Classifier-free guidance: trade diversity for adherence
- 21.10Latent diffusion: diffuse in an autoencoder's latent space
- 21.11Flow matching: regress a velocity along straight paths
- 23.1Perplexity and bits per byte
- 23.2Benchmarks: accuracy with error bars
- 23.3Contamination: when the test set was in training
- 23.4LLM-as-judge: graders and their biases
- 23.5Arena rankings: Bradley–Terry from pairwise votes
- 23.6Emergent abilities: real jumps or metric artefacts
- 23.7Hallucination: why next-token training produces plausible falsehoods
- 23.8Calibration: do probabilities mean what they say
- 23.9Prompt injection: untrusted text as instructions
01.2Universal approximation: one hidden layer is enough, in principle
01.3Depth efficiency: why deep networks beat wide ones
01.4Output layers and losses: pair the last activation with the likelihood
02.1Backpropagation: the chain rule, cached
02.2Automatic differentiation: backpropagation for any program
02.3Gradient checkpointing: recompute instead of remember
03.1Vanishing and exploding gradients: a product of many Jacobians
03.2Activation functions: the derivative decides whether signal survives
03.3Initialisation: choose weight variance so signal neither grows nor shrinks
03.4Gradient clipping: cap the step, keep the direction
03.5Residual connections: an identity path for the gradient
03.6Batch normalisation: standardise each feature over the batch
03.7Layer norm and RMSNorm: normalise each example on its own
04.1Network loss surfaces: non-convex, but not the way you fear
04.2Momentum: average the gradient to cross a ravine
04.3Adaptive learning rates: scale each parameter's step by its gradient history
04.4Adam: momentum and adaptive scaling, bias-corrected
04.5AdamW: weight decay is not an L2 penalty under Adam
04.6Learning-rate schedules: warm up, then decay
04.7Batch size: the linear scaling rule and where it stops
05.1Double descent: test error falls again past the interpolation threshold
05.2Implicit bias: which of many perfect fits gradient descent finds
05.3Dropout: train a random sub-network each step
05.4Data augmentation: teach invariances by transforming the data
05.5Label smoothing: stop pushing logits to infinity
05.6Early stopping: training time as a regulariser
05.7Reading a training run: curves, norms and the fix each symptom calls for
06.1The convolution: locality and weight sharing
06.2Pooling, stride and receptive fields: trading resolution for context
06.3CNN architectures: LeNet, AlexNet and VGG as a story of depth and compute
06.4ResNets: residual connections as an architecture
06.5Transfer learning: reuse features learned on a large dataset
07.1Embedding layers: a lookup table is a linear layer on one-hot input
07.2Word embeddings: meaning from the company a word keeps
07.3Autoencoders: learn a code by reconstructing the input
07.4Self-supervised learning: the data supplies the label
07.5Contrastive learning: pull views together, push others apart
08.1Recurrent networks: one set of weights applied through time
08.2LSTM and GRU: gated additive state
08.3Language models: predict the next token
08.4Sequence-to-sequence: encoder, decoder and the bottleneck
08.5Attention as alignment: let the decoder look back
09.1Self-attention: every token queries every token
09.2Causal masking: every next-token prediction in one pass
09.3Multi-head attention: several attention patterns in parallel
09.4Feed-forward sublayers: where most parameters live
09.5The transformer block: attention and MLP on a residual stream
09.6Absolute position encodings: tell attention where each token is
09.7RoPE: relative position from rotating queries and keys
09.8Relative position biases: T5 buckets and ALiBi
09.9Pre-norm and post-norm: keeping deep transformers trainable
09.10Encoder, decoder, encoder–decoder: the mask decides the model
09.11Vision transformers: image patches as tokens
10.1FLOP accounting: about 6N per token to train
10.2Memory bandwidth and the roofline: compute-bound or memory-bound
10.3Number formats: fp32, fp16, bf16 and fp8
10.4Mixed-precision training: half-precision compute, full-precision updates
11.1FlashAttention: exact attention without the T×T matrix
11.2Sliding-window and sparse attention: attend to fewer positions
11.3Linear attention: replace softmax with a kernel feature map
12.1State-space models: a sequence as a discretised linear system
12.2Mamba: input-dependent state updates and the parallel scan
12.3Delta-rule recurrences: overwrite associations in a matrix state
12.4Hybrid architectures: mixing attention with fixed-state layers
13.1Sparse mixture of experts: more parameters, same FLOPs per token
13.2Load balancing: keep the router from collapsing
14.1Tokenisation: byte-pair encoding from a corpus
14.2Tokenisation artefacts: digits, spelling and languages
14.3Web text filtering: from crawl to training text
14.4Deduplication: exact and near-duplicate removal at scale
14.5Data mixtures: how much of each domain
14.6Neural scaling laws: loss as a power law in size, data and compute
14.7Compute-optimal training: the Chinchilla allocation
14.8Beyond compute-optimal: inference cost and finite data
15.1Training memory: 16 bytes per parameter plus activations
15.2Collective communication: all-reduce and its cost
15.3Data parallelism: replicate the model, all-reduce the gradients
15.4ZeRO and FSDP: shard optimiser state, gradients and weights
15.5Tensor parallelism: split each matmul across devices
15.6Pipeline parallelism: layers on different devices
15.7Expert parallelism: all-to-all token dispatch
15.8Choosing a parallelism layout
16.1Autoregressive decoding: sampling one token at a time
16.2Beam search: approximate the most likely sequence
16.3The KV cache: store keys and values instead of recomputing
16.4MQA and GQA: share keys and values across heads
16.5Multi-head latent attention: cache a low-rank latent
16.6Prefill and decode: two phases, two bottlenecks
17.1Continuous batching: schedule at the iteration, not the request
17.2PagedAttention: KV cache in fixed-size blocks
17.3Speculative decoding: draft cheaply, verify in parallel
18.1Quantization: integers plus a scale
18.2Activation outliers: why LLMs resist int8
18.3GPTQ and AWQ: use calibration data to place the error
18.4Knowledge distillation: train a small model on a large one's distribution
18.5Pruning: remove weights, keep the function
19.1In-context learning: a task specified in the prompt
19.2Supervised fine-tuning: from base model to assistant
19.3Catastrophic forgetting: what fine-tuning overwrites
19.4LoRA: learn a low-rank weight update
19.5QLoRA: LoRA on a 4-bit base
19.6Extending context: rescaling RoPE
19.7Dense retrieval: find passages by embedding similarity
19.8Retrieval-augmented generation: ground the answer in documents
19.9Long context or retrieval
20.1Chain of thought: intermediate tokens as computation
20.2Repeated sampling: majority vote, best-of-N and pass@k
20.3Test-time compute versus model size
21.1VAEs: an autoencoder you can sample
21.2The reparameterisation trick: sample noise, not parameters
21.3GANs: a generator trained against a discriminator
21.4GAN training dynamics: saturation and mode collapse
21.5Normalizing flows: exact likelihood by invertible maps
21.6Denoising diffusion: learn to reverse gradual noising
21.7Score matching: learn the gradient of log-density
21.8Fast diffusion sampling: DDIM and ODE solvers
21.9Classifier-free guidance: trade diversity for adherence
21.10Latent diffusion: diffuse in an autoencoder's latent space
21.11Flow matching: regress a velocity along straight paths
22.1CLIP: one embedding space for images and text
22.2Vision–language models: image tokens into an LLM
23.1Perplexity and bits per byte
23.2Benchmarks: accuracy with error bars
23.3Contamination: when the test set was in training
23.4LLM-as-judge: graders and their biases
23.5Arena rankings: Bradley–Terry from pairwise votes
23.6Emergent abilities: real jumps or metric artefacts
23.7Hallucination: why next-token training produces plausible falsehoods
23.8Calibration: do probabilities mean what they say
23.9Prompt injection: untrusted text as instructions
24.1Case study: train a small language model end to end
24.2Case study: verify a frontier technical report
Skipped topics
Moved past without finishing. A skipped topic still closes its module, and Continue goes on without it — open one to read it or mark it understood.
Glossary
The vocabulary of the authored lessons, grouped by subject and linked to the topic that derives each idea.
Multilayer perceptron
A stack of learned linear maps interleaved with fixed nonlinearities — a model that learns its own features.
More detail
Each layer applies an affine map followed by a nonlinear activation, so the network composes functions rather than choosing from a hand-built basis. Without the nonlinearity the whole stack collapses back into one linear map.
Hidden layer
Any layer between input and output; its coordinates are features the network invents, not measurements it was given.
More detail
Calling it 'hidden' only means unobserved: the layer's values are intermediate computations. Each coordinate is a learned feature detector, which is precisely what distinguishes an MLP from basis expansion.
Activation function
The fixed nonlinearity applied elementwise after each affine map — the piece that keeps the stack from collapsing.
More detail
Without it, composing linear maps yields one linear map. Which activation to pick is a gradient question — the derivative decides whether signal survives a deep stack — so the choice is argued in the training-stability module, not here.
ReLU
max(0, z): the simplest nonlinearity that works, and the default for understanding what depth buys.
More detail
Piecewise linear with two pieces, so a ReLU network is a piecewise-linear function — which is what lets region counting measure expressiveness. Its derivative is exactly one on the active side and zero on the dead side.
Universal approximation
One hidden layer of sufficient width approximates any continuous function on a compact set to uniform error ε.
More detail
An existence theorem, not a recipe: it says nothing about the width required, whether gradient descent finds the approximant, or whether it generalises. The constructive intuition is that sums of ramps make any piecewise-linear interpolant.
Linear region
A connected region of input space on which a ReLU network is exactly affine — the unit of its expressiveness count.
More detail
Each ReLU unit carves space with a hyperplane; regions are the pieces of the resulting arrangement. Counting regions turns 'what can this network express' into combinatorics, which is what makes depth-versus-width comparisons provable.
Depth efficiency
The exponential advantage of composition: deep networks express functions that shallow ones need exponential width for.
More detail
One hidden layer's region count grows polynomially in width, while composing layers folds space so counts multiply — exponential in depth. Telgarsky's sawtooth gives an explicit function separating the regimes.
Canonical link pairing
Choose the output activation to be the likelihood's canonical link and the loss gradient collapses to prediction minus target.
More detail
Identity for a Gaussian mean, sigmoid for Bernoulli, softmax for categorical. The paired gradient with respect to the pre-activation never carries a saturating activation derivative, so the last layer cannot kill its own training signal.
Multiclass versus multilabel
Softmax when exactly one class is true; independent sigmoids when several labels can hold at once.
More detail
Softmax couples the logits into a distribution over mutually exclusive classes. A multilabel problem is a stack of independent Bernoulli decisions — one sigmoid each — because 'cat' and 'indoors' are not competitors.
Saturating output layer
Pairing a bounded activation with a mismatched loss lets the output layer extinguish its own gradient.
More detail
Sigmoid with squared error is the canonical mistake: the gradient carries a σ'(z) factor that vanishes when the unit saturates, so a confidently wrong prediction barely moves the weights.
Backpropagation
The chain rule with caching: one backward sweep computes every parameter's gradient at the cost of one forward pass.
More detail
Each layer stores its forward output and multiplies the incoming adjoint by its local Jacobian. The naive version recomputes shared suffixes exponentially often; caching them is the entire trick.
Automatic differentiation
Backpropagation generalised to any program: decompose into primitives, apply the chain rule mechanically, exact to float precision.
More detail
Not numerical differentiation (finite differences, O(√ε) error) and not symbolic differentiation (expression swell). Reverse mode accumulates gradients backward through a tape; it is what every deep-learning framework implements.
Gradient checkpointing
Discard intermediate activations at forward time and recompute them during the backward pass — memory traded for compute.
More detail
Keeping only boundary activations between segments drops activation memory from O(L) to O(√L) at the price of roughly one extra forward pass. Standard on any run where the activation ledger is the binding constraint.
Vanishing and exploding gradients
The backward pass multiplies many Jacobians; if their norms drift below or above one, the gradient dies or blows up with depth.
More detail
A product of L matrices scales like σ^L: below 1 it vanishes exponentially, above 1 it explodes. Fixes attack the multiplier — activation choice, initialisation scale, clipping, residual paths, normalisation.
Variance-preserving initialisation
Scale each layer's weights by fan-in so activations keep unit variance through the stack — Xavier for symmetric activations, He for ReLU.
More detail
He initialisation draws weights with variance 2/d_in; Xavier uses 1/d_in (or 2/(d_in+d_out)). The wrong constant compounds by depth — too large explodes, too small vanishes — before learning even starts.
Gradient clipping
Rescale the gradient when its global norm exceeds a threshold — direction kept, length capped.
More detail
Norm clipping projects onto the Euclidean ball ‖g‖ ≤ c; per-value clipping onto the cube, which rotates the direction and leaks a √N factor. The threshold is read off the run's own norm histogram, not theory.
Residual connection
x + f(x): an identity path that lets the gradient skip every layer it crosses.
More detail
The Jacobian of a residual block is I + J', so the backward pass keeps a term of norm one no matter how deep the stack. The network learns the perturbation to add rather than the whole map — the difference between fitting and re-representing.
Batch normalisation
Standardise each feature across the minibatch, then re-scale with learned γ, β — but the statistics belong to the batch, not the example.
More detail
The same example normalises differently depending on its companions, which couples training examples, breaks at batch size 1, and forces running statistics at inference. Per-example normalisers (layer norm, RMSNorm) remove that coupling entirely.
Layer normalisation / RMSNorm
Normalise within each example's own feature vector — no batch coupling, same function in training and inference.
More detail
Layer norm subtracts the mean and divides by the per-example standard deviation; RMSNorm skips the mean entirely and divides by the root mean square. Both keep activations on a fixed-radius sphere; modern transformers overwhelmingly run RMSNorm.
Pre-norm versus post-norm
Where the normaliser sits in a residual block decides whether a deep transformer trains at all.
More detail
Post-norm wraps the residual (Norm(x + Sublayer(x))) and needs warmup plus careful init; pre-norm puts the norm inside the branch (x + Sublayer(Norm(x))) so the trunk stays a bare sum that gradients cross unscaled — at the price of a residual stream whose variance grows with depth.
Saddle point
A critical point with both positive and negative curvature — the landscape's dominant obstacle, not the local minimum.
More detail
In high dimension, most critical points of a random-function landscape are saddles: the chance that all d eigenvalues of the Hessian come out positive shrinks exponentially in d. The optimiser's real work is escaping plateaus, not rolling downhill.
Momentum
Keep a running average of past gradients so the step follows the consistent direction and cancels the noise.
More detail
Heavy-ball momentum accumulates v ← βv + g and steps along −ηv; Nesterov evaluates the gradient at the lookahead point. Along a valley it accelerates descent by roughly 1/(1−β); across it, perpendicular wiggles average out.
Adam
Per-coordinate step sizes from running first and second moment estimates — momentum divided by root-mean-square gradient.
More detail
m tracks the mean gradient, v the uncentred second moment; the update m̂/(√v̂ + ε) makes each parameter's step scale-free. The default optimiser for transformers, at the cost of 2 extra floats per parameter of optimiser state.
Decoupled weight decay (AdamW)
Apply weight decay directly to the parameters instead of folding it into the adaptive gradient — L2 in disguise only under plain SGD.
More detail
Adding λθ to the gradient makes Adam's per-coordinate scaling shrink the decay too, so effective regularisation varied with gradient scale. AdamW decays θ by ηλθ outside the adaptive term, which is why it generalises better at the same training loss.
Warmup
Ramp the learning rate from zero over the first few hundred steps so the optimiser does not lurch on untrusted statistics.
More detail
At initialisation the adaptive denominators and post-norm residual stacks are both unreliable; a linear warmup smuggles the model past the phase where one bad step can bias the whole trajectory.
Double descent
Test error falls, rises through the interpolation threshold, then falls again — the capacity curve has two regimes, not one.
More detail
Past the point where the model just fits the training set, adding parameters finds smoother interpolants, and generalisation recovers. It reframes 'bigger overfits' as a statement that only holds on the under-parameterised side.
Implicit bias of gradient descent
Among the many minima that fit the data, gradient descent systematically lands on the flat, simple ones — regularisation the objective never wrote down.
More detail
The classical example is separable logistic regression, where SGD diverges toward the max-margin separator. In deep nets the bias shows up as a preference for low-curvature solutions, which is part of why over-parameterised nets generalise at all.
Dropout
Zero each activation with probability p during training so the network cannot co-adapt features to a fixed companion.
More detail
At inference the layer keeps all units but scales them (or divides at train time) so expectations match. The regularisation is architectural: it forbids any feature from leaning on the exact value of another.
Label smoothing
Train against a softened target — ε spread over wrong classes — so the model stops driving logits to infinity.
More detail
The cross-entropy minimum is unbounded for a hard one-hot target; smoothing caps the achievable confidence, which regularises the logit scale and usually improves calibration — while also changing what a distilled student can learn from the softened teacher.
Early stopping
Stop training at the validation minimum — training longer keeps fitting noise, not signal.
More detail
The stopped step count plays the role of a capacity knob: parameters see only as much data-fitting as the stopped trajectory reached. It doubles as the implicit prior that later steps are less trustworthy than earlier ones.
Data augmentation
Apply label-preserving transformations — crops, flips, mixes — so each epoch trains on a dataset that never repeats.
More detail
The augmentations encode the domain's known invariances, which is cheaper than learning them. Mixup and CutMix go further: they interpolate inputs and labels, changing the objective itself rather than just expanding the support.
Convolution
One small kernel applied at every position: locality plus weight sharing, baked into the architecture.
More detail
The layer's output is a sliding dot product — the same template matched everywhere — so a shift in the input produces a shifted copy of the feature map (equivariance), and the parameter count no longer scales with image size.
Receptive field
The input region that can influence one activation — how far the stack can see.
More detail
Each layer widens the field by roughly the kernel size times the running stride product. A classification head needs a field at least the object's size; dilated kernels grow the field without paying resolution.
Pooling
Subsample a feature map by a local reduction (max, mean) — shrinking resolution while buying a little shift-invariance.
More detail
Max pooling keeps the strongest response in each window; strided convolution achieves the same downsampling with learned filters. Modern architectures mostly prefer the latter, since the stride buys invariance without throwing away magnitudes.
Transfer learning
Reuse a network trained on a large dataset as a feature extractor or initialisation for a small one.
More detail
Early layers learn general detectors — edges, textures — that transfer across tasks. Freezing the trunk and training a linear probe is the cheap end; full fine-tuning the expensive end. The whole lesson is deciding where between them to land.
Embedding layer
A lookup table mapping discrete ids to learned vectors — the same object as a linear layer over one-hot inputs, without the pointless matmul.
More detail
Semantically it is E^T t; computationally it is a gather. The gradient touches only the rows that were looked up, which is why the layer is cheap while a dense equivalent would stream the whole table per token.
Autoencoder
An encoder that compresses x into a bottleneck z and a decoder that reconstructs it — representation learning by reconstruction.
More detail
The bottleneck forces the network to keep what the reconstruction needs. As a generator it fails — nothing makes the latent space samplable — which is exactly the gap the VAE fills with a prior and a variational posterior.
Self-supervised learning
The data supplies its own label: mask a token, rotate an image, predict the next item — pretext tasks that build features without annotators.
More detail
A pretext task is useful only if solving it requires real structure. Masked prediction (BERT, MAE) forces the model to learn syntax and semantics; trivial pretexts collapse to shortcuts that transfer nowhere.
Contrastive learning / InfoNCE
Pull two views of the same input together, push all other inputs apart — a classification problem where the classes are the batch's own examples.
More detail
InfoNCE is softmax cross-entropy over one positive and N−1 negatives; its optimum lower-bounds mutual information between the views. Temperature controls how sharp the softmax is, and batch size controls how many negatives push back.
Recurrent network
Fold a sequence by reusing one function: h_t = f(h_{t−1}, x_t) — a loop with memory, not a feed-forward map.
More detail
The same weights apply at every step, so the model handles any length — but the gradient must cross every step (BPTT), the hidden state is a bottleneck the whole history compresses into, and the loop is sequential: no parallelism across time.
LSTM / GRU
Gated recurrence: learned sigmoid gates decide what to forget, write and read, giving the state an additive path gradients survive.
More detail
The LSTM's cell update is a sum controlled by gates rather than a repeated product, which is what lets credit cross hundreds of steps. The GRU merges the gates to three and drops the separate cell — usually equivalent in practice.
Teacher forcing / exposure bias
Train the decoder on gold prefixes, then run it on its own outputs at inference — the train/test mismatch that makes small errors compound.
More detail
Under teacher forcing the model never sees a prefix containing its own mistake; at generation, one wrong token shifts the input off the training distribution and distributions after that are guesses. Scheduled sampling mixes the two during training.
Beam search
Keep k candidate prefixes, extend all of them, prune to the k highest joint scores — greedy decoding with a wider net.
More detail
Beam search finds higher-probability sequences than greedy decoding but still approximates the mode, and it trends toward short, generic output. For open-ended text it lost to sampling; it survives where there is a right answer (translation, speech).
Scaled dot-product attention
softmax(QK^⊤/√d_k)V — every position reads a weighted average of every other's value, weights set by query–key agreement.
More detail
The 1/√d_k scaling keeps logits out of softmax's saturating tails as dimension grows. One step of attention does what a recurrent layer takes T steps to do — read distant context — at the price of a T×T score matrix.
Causal mask
Set future attention logits to −∞ before the softmax so position t can only read positions ≤ t — the trick that makes next-token training parallel.
More detail
With a mask, one forward pass computes the prediction for every position simultaneously; without it the model would need a pass per token or peek at the answer. At inference the mask is inherent — the future simply does not exist yet.
Multi-head attention
Run attention h times in parallel on d/h-dimensional slices — different heads learn different relations (syntax, position, semantics).
More detail
Heads are not redundancy: a single softmax per position can express only one attention pattern, and h smaller heads cost the same FLOPs as one big one. Empirically heads specialise — some track position, some content, many are prunable.
Rotary position embedding (RoPE)
Rotate each query/key pair by an angle proportional to its position — relative offsets appear as relative rotations in the score.
More detail
The score depends on i−j automatically because rotations compose: R_i R_j^⊤ = R_{i−j}. Frequencies span geometric scales so some dimensions track local position and others long range; extrapolating past the trained length needs the rope-extension tricks the serving module covers.
ALiBi
A fixed linear bias −m_h|i−j| added to attention scores — position enters as a penalty on distance, learned for nothing.
More detail
Each head gets a different slope m_h from a geometric sequence, so short-range heads stay local and long-range heads barely decay. Because the bias is a function of offset rather than of absolute position, ALiBi extrapolates to longer contexts than it trained on.
KV cache
Store each layer's computed keys and values so decoding reuses them instead of recomputing the whole prefix per token.
More detail
Per token the cache reads T·d·layers·2 values — decode is memory-bandwidth-bound on the cache, not compute-bound. Its size grows linearly in context length and batch, which is why paging, quantisation and head-sharing (GQA/MLA) exist.
Grouped-query / multi-head-latent attention
Shrink the KV cache by sharing keys and values across query heads (GQA) or compressing them into a low-rank latent (MLA).
More detail
GQA gives each group of query heads one shared K,V pair — the cache divides by the group size. MLA goes further: it stores a down-projected latent per position and re-expands on read, the DeepSeek trick that cuts the cache by an order of magnitude.
FLOP accounting
≈2N FLOPs per token forward, ≈6N per token trained — the ledger that turns a parameter count into a compute bill.
More detail
Each multiply-add counts twice (multiply, then add) once per parameter per token; the backward pass costs two forwards. Attention adds a term ∝ L·T·d that matters at long context. FLOPs are what the hardware sells; wall-clock is what memory traffic charges.
Roofline model
Peak FLOP/s and memory bandwidth bound any kernel; the ridge point's arithmetic intensity decides which side you are on.
More detail
FLOPs per byte read decides the regime: below the ridge the kernel waits on memory, above it the ALUs saturate. Decode-time attention is famously bandwidth-bound — one token, a whole cache read — which is why batching helps it so much.
bf16 / fp8
Half the bytes, tiny exponent range (bf16) or tiny mantissa (fp8) — the number formats that make large-scale training fit bandwidth.
More detail
bf16 keeps fp32's 8 exponent bits and sacrifices mantissa — safe for activations and weights, bad for accumulators. fp8 halves again and works only with per-tensor scaling plus an fp32 master path, since its range saturates at ±448.
FlashAttention
Exact attention computed in tiles so the T×T score matrix never materialises — an IO-aware reorganization, not an approximation.
More detail
The kernel keeps running softmax statistics (max and normaliser) per tile and rescales on the fly, reading K,V once instead of writing and re-reading the full attention matrix. Same math, an order of magnitude less memory traffic — the reason it replaced every other 'efficient attention' in practice.
Linear attention
Reorder (QK^⊤)V as Q(K^⊤V) so attention becomes a running state update — O(T) but a lossy fixed-size memory.
More detail
Dropping the softmax lets the K^⊤V outer products accumulate into a d×d matrix state updated recurrently. Exact at prediction but weak at exact recall: the state must compress all history into a fixed matrix, which is why hybrids keep a few full-attention layers.
State-space model / Mamba
A continuous-time linear recurrence discretised for sequences; Mamba makes its transition input-dependent — a fixed-size state that still reads selectively.
More detail
h'(t) = Ah(t) + Bx(t) becomes a scan h_t = Ā_t h_{t−1} + B̄_t x_t. Mamba's selection makes Ā,B̄ functions of the input, so the state can gate what to keep — expressiveness where plain linear recurrence fails, at O(1) memory per step.
Mixture of experts
Route each token to a few of many parallel feed-forward blocks — parameters grow without per-token compute growing with them.
More detail
A softmax router picks top-k experts per token; the model's capacity lives in total parameters while its cost lives in active parameters. The catch is load balancing — a router that favours a few experts wastes the rest, so auxiliary losses or balancing terms keep the routing even.
Byte-pair encoding (tokenisation)
Merge the most frequent adjacent token pair repeatedly — a vocabulary grown from data, trading length for breadth.
More detail
BPE starts from characters and merges greedily until the vocabulary is full. The result decides what the model can say cheaply: rare words split into many tokens, unseen scripts may split into bytes, and token boundaries leave artefacts the model has to unlearn.
Neural scaling laws
Loss falls as a power law in parameters, data and compute — predictable enough to extrapolate a small sweep into a large run's design.
More detail
L(N, D) ≈ E + A/N^α + B/D^β fits the training loss across orders of magnitude. Chinchilla's version says optimal training allocates parameters and tokens in a fixed ratio — which is why 'compute-optimal' pins a tokens-per-parameter constant rather than a size.
Data / tensor / pipeline parallelism
Three orthogonal cuts of the same network: split the batch, split each layer's weights, split the stack itself.
More detail
Data parallelism replicates the model and syncs gradients; tensor parallelism shards matmuls inside a layer across fast interconnects; pipeline parallelism assigns layer ranges to stages and streams microbatches through them. Real runs compose all three — the lesson is which constraint each one relieves.
ZeRO / sharded data parallelism
Partition optimiser state, gradients and parameters across data-parallel ranks and gather them on demand — replication's memory paid only once.
More detail
Plain data parallelism keeps a full copy of everything on every device; ZeRO's three stages shard the optimiser states, then gradients, then weights themselves, gathering each shard only during its use. Communication rises modestly while per-device memory collapses.
Temperature
Divide the logits by T before softmax — T<1 sharpens toward the argmax, T>1 flattens toward uniform.
More detail
Sampling with temperature 0 is greedy decoding; T=1 draws the model's own distribution. The knob trades reliability for variety, and it is load-bearing in distillation, where the same T>1 reveals the teacher's dark knowledge in its softened classes.
Top-k / nucleus (top-p) sampling
Truncate the softmax tail before sampling — k most likely tokens, or the smallest set covering probability mass p.
More detail
Top-k truncates at a fixed count, which either prunes the tail too early or admits junk when the distribution is flat. Top-p adapts: the set grows or shrinks with the distribution's shape, keeping the nucleus at roughly fixed quality.
Prefill versus decode
Two phases with opposite bottlenecks: prefill processes the prompt in parallel (compute-bound), decode emits one token at a time (bandwidth-bound).
More detail
Prefill runs a full self-attention over the prompt at once; decode appends tokens serially, each reading the whole KV cache. Serving systems split them onto different hardware or batch decode aggressively — a mixed batch serves neither phase well.
Continuous batching
Batch at token granularity, not request granularity — slots reassign every step so a finished sequence never holds a batch position hostage.
More detail
Static batching wastes the whole batch's tail while the longest sequence finishes. Continuous batching evicts completed sequences and admits waiting ones every step, which is the main throughput lever of modern serving stacks.
Paged attention
Store KV cache in fixed-size blocks addressed through a page table — near-zero fragmentation, and prefixes can be shared by reference.
More detail
Virtual-memory for the KV cache: instead of reserving max-length contiguous space per sequence, blocks are allocated on demand and shared between sequences with common prefixes. The trick that made long contexts servable at scale.
Speculative decoding
Draft k tokens with a cheap model, verify all k against the big model in one parallel pass — accepted tokens come free.
More detail
Verification is a single forward over the drafted tokens, so a match costs the same as one normal token and acceptance rates determine the speedup. The output distribution is unchanged — it is exact acceleration, not an approximation.
Post-training quantization
Round trained weights to int8/int4 — fewer bytes, faster reads, a small accuracy tax that the rounding scheme sets.
More detail
Per-channel scales keep each output channel's error independent; the hard part is activation outliers, which is why the course separates weight-only quantization from the harder W×A schemes and from calibration methods that re-fit the rounding.
Knowledge distillation
Train a small student to match a large teacher's softened output distribution — the dark knowledge lives in the probabilities, not the argmax.
More detail
Soft targets at temperature T>1 expose the teacher's class relationships (cat resembles dog more than car); the student trained on them beats the same student trained on hard labels, even on classes the teacher demonstrably got wrong.
Weight pruning
Delete weights to shrink the checkpoint — but a sparsity percentage is only a storage number until the structure is named.
More detail
Unstructured magnitude pruning gives zeros a dense kernel cannot skip; 2:4 semi-structured patterns pay only on sparse tensor cores; structured channel removal shrinks the dense matmul itself. Prune, retrain with the mask frozen, measure realised — not nominal — speedup.
In-context learning
Condition on examples in the prompt instead of updating weights — the model infers the task from the context at inference time.
More detail
A few labelled examples in-context steer behaviour with no gradient update at all. The mechanism is induction over the prefix — the model reads its own demonstrations as evidence — and it is brittle in ways fine-tuning is not.
Supervised fine-tuning
Continue training the pretrained model on curated input–output pairs — behaviour taught by demonstration rather than by the raw-text prior.
More detail
SFT is where style, refusal and format come from; small high-quality sets outperform large noisy ones (LIMA's claim). The price is catastrophic forgetting — weight updates that fix the behaviour can erode the pretrained capabilities underneath.
Catastrophic forgetting
Fine-tuning on a new distribution quietly erases abilities the old one taught — the weights move where the new loss wants, regardless of what they encoded.
More detail
The fixes trade memory for stability: replay buffers mix old data back in, EWC penalises moving weights that mattered for the old task, adapters keep the pretrained weights frozen entirely. Continued pretraining shows the same failure at scale.
LoRA / QLoRA
Fine-tune a low-rank update ΔW = BA instead of W — the pretrained matrix stays frozen and the adapter is a few percent of the parameters.
More detail
The frozen base means no optimiser state on the bulk of the model and adapters that swap at inference. QLoRA pushes further: 4-bit-quantized base weights plus a bf16 adapter, fitting large-model fine-tuning onto a single GPU.
Retrieval-augmented generation
Retrieve passages at inference and prepend them to the prompt — knowledge injected without touching the weights.
More detail
A dense retriever scores the query against an indexed corpus; the top passages land in the context as evidence the model conditions on. RAG trades context length for currency — but retrieval failure and context-fitting limits are the lesson's honest caveats.
Chain-of-thought
Let the model write intermediate reasoning before answering — accuracy bought with output tokens, not parameters.
More detail
A prompted scaffold ('think step by step') or a few worked rationales changes what the model computes: intermediate tokens act as working memory. The gains concentrate on tasks with real intermediate structure — arithmetic, symbolic — and shrink on recall tasks.
Test-time compute
Spend more inference tokens per answer — longer reasoning, more samples, verification — as an axis orthogonal to training compute.
More detail
Self-consistency samples several chains and votes; verifiers rank candidates; reasoning models stretch a single chain. The trade-off the lesson quantifies: when extra tokens beat extra parameters, and when they just buy noise.
Variational autoencoder
An autoencoder whose latent is a distribution: encode to (μ, σ), sample z, decode — trained on reconstruction plus KL to a prior.
More detail
Maximising the ELBO teaches the encoder to produce posteriors and the decoder to invert them; the KL term pulls posteriors toward N(0,I) so the latent space becomes samplable — the property a plain autoencoder lacks and GANs get by other means.
Reparameterisation trick
Write z = μ + σε with ε ~ N(0,I) so the randomness bypasses the mean — the sampler stops being a gradient barrier.
More detail
Sampling from N(μ,σ) has no gradient with respect to μ,σ; moving ε outside the parameters turns the node into a deterministic transform of a fixed random input. Without it, backpropagating through the VAE's latent is a REINFORCE problem instead of a derivative.
GAN
A generator and a discriminator trained adversarially — G learns to fool D, D learns to tell real from fake; the samples come from the equilibrium.
More detail
The minimax objective is beautiful and brittle: saturating losses starve G, unbalanced training oscillates, and mode collapse lets G win by memorising a few outputs. Most practical tricks — Wasserstein distances, feature matching — patch the game's dynamics rather than its goal.
Diffusion model
Destroy data with a fixed noise schedule, then train a network ε_θ to invert each step — generation as learned denoising.
More detail
The forward process adds Gaussian noise t times until x_t ≈ ε; the model is trained to predict the noise that was added, so sampling runs the chain backward step by step. Slow but stable — the mode-collapse failure GANs live with is absent.
Score matching / Langevin sampling
Learn the score ∇_x log p(x) of the data distribution — then climb it with noise: Langevin dynamics turn an unnormalised gradient into a sampler.
More detail
Estimating the score avoids the partition function entirely; denoising score matching does it by predicting noise at multiple scales. The connection runs both ways: diffusion training is score matching, and DDPM sampling is Langevin by another name.
Classifier-free guidance
Train one model conditioned and unconditioned; at sampling, extrapolate away from the unconditional direction — ε̂ = ε_u + s(ε_c − ε_u).
More detail
The scale s trades fidelity for diversity: s>1 pushes samples toward the condition and away from the model's generic prior. No separate classifier is needed — the model supplies both endpoints — which is why every modern image model uses it.
Latent diffusion
Run the diffusion chain in a pretrained autoencoder's latent space — same model, a fraction of the pixels' compute.
More detail
The VAE compresses an image into a small latent grid; the denoiser works there and the decoder maps the result back to pixels. Perceptually near-lossless, computationally transformative — the trick that put image generation on a single GPU.
Flow matching / rectified flow
Learn the vector field that transports noise to data along a chosen path — a continuous-time generalisation that subsumes diffusion.
More detail
Rather than learning to denoise each step, the model regresses the straight-line velocity field between noise and data; sampling integrates the ODE. Rectified flow's linear interpolation makes near-straight paths, which is why few-step samplers work at all.
CLIP
Contrastive image–text training: two encoders, one shared embedding space, aligned by InfoNCE over a batch of pairs.
More detail
Each image and its caption are pulled together while mismatched pairs are pushed apart. The result is zero-shot classification ('a photo of a {class}' competes for the image's embedding) and the text encoder every image generator steers by.
Perplexity
e^(mean NLL per token) — the model's effective vocabulary size at each step; lower is better, and comparable only within one tokenisation.
More detail
It is the exponentiated average cross-entropy, so it measures next-token fit, not quality — a model can memorise a benchmark and look brilliant. Tokenisation changes the denominator, which is why bits-per-byte exists as the comparable alternative.
Benchmark contamination
The test set leaked into the training crawl — scores then measure memorisation, not capability.
More detail
Detection runs from n-gram overlap checks to probing whether the model can reproduce held-out examples verbatim. The deeper version is near-duplicates and paraphrases that exact matching misses; contamination-aware reporting is now part of an honest eval.
LLM-as-judge
Grade model outputs with another model — scalable, but biased toward its own family, verbosity and position.
More detail
Judges inherit systematic preferences: longer answers score higher, a model prefers outputs resembling its own style, and order effects flip pairwise outcomes. The defence is protocol — position swaps, rubric anchoring, and human calibration on a sample.
Hallucination
Fluent output that is wrong — a consequence of next-token training grading plausibility, not truth.
More detail
The mechanism is statistical: training rewards confident completions and benchmarks reward guesses over abstention, so the model has no channel for 'I don't know'. Retrieval and calibrated sampling mitigate; the failure is structural, not a bug version-by-version.
Calibration
Do stated confidences match empirical accuracy? A model that says '80% sure' should be right 80% of the time.
More detail
Expected calibration error bins predictions by confidence and compares to hit rate; modern LLMs are overconfident in ways RLHF made worse. Post-hoc fixes — temperature scaling on held-out data — repair the probabilities without touching the ranking.
Prompt injection
Hostile text inside the model's input that overrides the intended instructions — the injection is content, not code, so there is no patch.
More detail
Any retrieved or pasted text can carry instructions the model will follow; grounding expands the attack surface rather than removing it. Defences are architectural — least privilege, separation of trusted instructions from data — not prompt engineering.
Which method do I reach for?
A decision the reader faces, the recommendation, and the topic that derives the trade-off. Model families and serving choices appear as their lessons are written.
Need features a linear model cannot name
Replace hand-built basis functions with learned layers: a multilayer perceptron.
More detail
Basis expansion fixes the features before seeing data; an MLP parameterises the features themselves and lets gradient descent shape them. XOR is the two-point proof that no fixed linear boundary suffices.
Choose the output activation
Pair it with the loss's canonical link — identity for regression, sigmoid for binary, softmax for multiclass — so the output gradient is prediction minus target.
More detail
The pair is chosen so the last layer cannot saturate its own signal. Deliberately mismatched pairs (sigmoid with squared error) produce a σ'(z) factor that goes to zero exactly when the prediction is most wrong.
Several labels at once, or exactly one class
Multilabel means independent sigmoids per label; multiclass means one softmax over mutually exclusive classes.
More detail
Softmax forces the logits to compete — right when one answer exists, wrong when 'cat' and 'indoors' are both true. The choice is about the semantics of the label space, not the loss's convenience.
Spend parameters on width or on depth
Depth buys expressiveness exponentially where width buys it polynomially — prefer depth for compositional functions.
More detail
Universal approximation already lets one wide layer represent anything; the argument for depth is efficiency, not possibility. Telgarsky's sawtooth is the explicit witness: 2^L linear pieces from L layers versus exponential width for a shallow copy.
Trust a universal-approximation guarantee
Only as an existence proof — it says nothing about the width needed, whether gradient descent finds the weights, or whether the fit generalises.
More detail
Read it as 'the model class is not the bottleneck', then look to optimisation and sample complexity for the guarantees actually doing work.
A deep network diverges or stalls at step zero
Check the initialisation against the activation's gain before touching the optimiser — variance must be preserved layer to layer.
More detail
Gradients vanish or explode multiplicatively with depth. Variance-preserving init (He for ReLU, Xavier for tanh) keeps forward activations and backward gradients at unit scale; everything downstream assumes it.
Loss spikes on a single bad batch
Clip the gradient norm — rescale only when the update would exceed a threshold, leaving direction and typical steps untouched.
More detail
Clipping by norm caps the worst-case step without re-scaling every batch the way clipping by value does. The threshold sits just above the healthy median norm, read off a training curve.
Make a hundred-layer network trainable at all
Residual connections first: the identity path keeps gradient and signal flowing when the residual branch contributes nothing.
More detail
Skip connections turn a depth-L product of Jacobians into a sum of near-identity terms, so the loss surface stays connected and early layers keep receiving gradient even at init.
BatchNorm or LayerNorm
BatchNorm for convnets on large batches; LayerNorm/RMSNorm for transformers and anything where batch statistics are unreliable.
More detail
BatchNorm borrows statistics across the batch — which couples examples at train time and breaks under small or distributed batches. LayerNorm normalises within one example, so it behaves identically in training and inference.
Pre-norm or post-norm transformer
Pre-norm for depth you don't want to warm up forever; post-norm for slightly better final quality when you can afford careful schedules.
More detail
Pre-norm keeps an identity gradient highway and trains stably at depth but can under-represent late layers; post-norm recovers the sharper fit at the cost of warmup and fragility.
Pick a default optimiser
AdamW: Adam's per-coordinate adaptivity with weight decay decoupled from the gradient.
More detail
SGD+momentum still wins where you can afford to tune it, but Adam-family defaults dominate because they rescale coordinates automatically. Coupling decay to the adaptive gradient silently shrinks weights more where gradients are large — decoupling is the fix.
Choose a learning-rate schedule
Warmup then decay — cosine or linear to a small fraction of peak; the peak and the warmup, not the shape, carry the result.
More detail
Early steps need a small LR while second-moment estimates and representations settle; late training needs decay to land in a wide basin. Constant-high LR is the schedule that fails for a measurable reason.
Raise the batch size
Scale the learning rate with it — linearly up to the regime where gradient noise is already small; beyond that, batch buys nothing.
More detail
The gradient-noise scale marks where extra samples stop adding information per step. Small-batch noise is itself a regulariser, so very large batches can need retuning of decay and epochs, not just LR.
Read a training curve that looks wrong
Match the shape before reaching for fixes: plateau-at-init, late overfit, loss spikes and dead-axis each name a different mechanism.
More detail
A curve is a diagnosis, not a score — train-vs-val divergence, update-to-parameter ratio, and gradient-norm spikes each point at a different knob (regularisation, LR, clipping, init).
Get more generalisation from fixed data
Data augmentation first, then explicit regularisers — dropout, label smoothing, weight decay — before shrinking the model.
More detail
Augmentation encodes invariances the model would otherwise spend parameters learning. Over-parameterised nets can still interpolate and generalise (double descent), so capacity is rarely the first thing to cut.
Grid-structured or spatial data
Convolution — parameter sharing plus locality builds translation-equivariant features at a fraction of dense cost.
More detail
A dense layer relearns every pattern at every position; a kernel shares it. Pooling and stride then buy receptive field cheaply.
Limited labelled data on a standard task
Transfer from a pretrained model — freeze early features, finetune the head, unfreeze progressively.
More detail
Pretrained features are generic near the input and task-specific near the output; the lower the target task's data, the more of the network stays frozen.
No labels at all
Self-supervised learning — build a pretext task from structure in the data itself, or contrast pairs of augmented views.
More detail
The pretext's job is to make representation quality, not the invented task, the bottleneck. Contrastive objectives pull augmentations together and push other examples apart; masked reconstruction learns from what was removed.
Token or categorical inputs
An embedding layer — a lookup table that is just a linear layer over one-hot inputs, trained end to end.
More detail
Embeddings turn a discrete index into a learned geometry: distances and directions become trainable. The table scales with vocabulary, not with input length.
Map a variable-length sequence to a different-length one
Encoder–decoder with attention — the decoder queries a per-timestep context rather than trusting a single bottleneck vector.
More detail
Compressing the whole input into one state is what fails as inputs lengthen; attention-as-alignment lets each output step read the relevant source positions directly.
Attention's quadratic cost on long sequences
Exact first: FlashAttention's tiling removes the memory wall without changing the math. Only then approximate — sliding-window, sparse, or linear attention.
More detail
Attention is memory-bandwidth-bound, not FLOP-bound: materialising the N×N matrix is the real cost. When approximation is needed, sliding-window preserves local structure while linear attention trades the softmax kernel for a recurrent form.
Sequences far longer than attention can reach
State-space models / Mamba — linear-time recurrence with a learned input-dependent scan — or a hybrid that keeps some attention layers.
More detail
SSMs compress the past into a fixed state like an RNN but train like a convnet; the selection mechanism restores content-based routing. Hybrids get most of the efficiency while keeping exact-retrieval paths.
Grow parameters without growing compute per token
Sparse mixture of experts — route each token to a few experts; capacity scales with expert count while FLOPs stay at the activated few.
More detail
The cost moves to routing: load balancing is an auxiliary-loss problem, and expert parallelism adds all-to-all communication. MoE is a systems trade as much as an architecture one.
Size a pretraining run
Scaling laws first — pick parameters and tokens together on the compute-optimal frontier, roughly 20 tokens per parameter.
More detail
Loss falls as a power law in compute, data and parameters; Chinchilla's point is that models were under-trained, not under-sized. Beyond the frontier the trade-offs shift to data quality and inference cost.
Turn the raw web into pretraining data
Filter, deduplicate, decontaminate — data curation moves loss more than most architecture changes at fixed compute.
More detail
Deduplication removes memorised boilerplate, quality filters pass classifiers over documents, and decontamination strips benchmark overlap so evals keep meaning something.
A model that does not fit on one GPU
Pick the axis that removes the bottleneck: tensor parallelism splits layers, pipeline splits depth, FSDP/ZeRO shards the optimizer and parameters, data parallelism only scales when the model already fits.
More detail
The decision is driven by the memory budget — parameters, gradients, optimizer states, activations — then by interconnect: tensor parallelism wants fast intra-node links, pipeline tolerates slower ones at the price of bubbles.
Fit training in memory
Mixed precision for bandwidth, then activation checkpointing — recompute activations in backward instead of storing them.
More detail
bf16 halves the activations and weights traffic at a small quality cost managed by loss scaling or master weights. Checkpointing trades ~30% more compute for an order less activation memory.
Token-by-token generation is slow
Speculative decoding — draft cheap tokens, verify them all in one teacher pass; accepted tokens cost the same forward as one.
More detail
Autoregressive decode is memory-bound, so a small drafter's tokens verified in parallel against the target model give the same output distribution at a fraction of the latency. The KV cache is the prerequisite: no recompute of the prefix.
Serve many concurrent generations
Continuous batching plus paged KV — schedule per iteration and allocate the cache in blocks so memory waste stops capping batch size.
More detail
Request-level batching strands the GPU on the longest sequence; iteration-level scheduling admits new requests mid-flight. Paging removes the contiguous-allocation waste that limited batch occupancy.
Shrink a trained model for deployment
Quantize weights for bytes, distill for capability, prune for structure — in that order of effort and risk to accuracy.
More detail
Per-channel weight-only PTQ is nearly free at int8; lower bits need calibration to place rounding error where it is cheap. Distillation transfers the function to a smaller student via soft targets; pruning removes weights that saliency says do not matter.
Adapt a pretrained model per task or per user
LoRA — freeze the base, train low-rank residual adapters on each weight matrix; merge or swap adapters at serve time.
More detail
Full fine-tuning costs a full copy of optimizer state and risks forgetting; a rank-r update (r ≈ 8–64) captures most of the task delta at a fraction of trainable parameters. QLoRA quantizes the frozen base further.
Fine-tuning erases earlier skills
Catastrophic forgetting — mitigate with replay, adapters, or slower drift, because the loss landscape of the new task does not preserve the old one.
More detail
Gradient descent optimises the current distribution only; earlier-task performance drops as weights move. Replay mixes old data back in; parameter-efficient methods bound the drift by construction.
Answer from private or fresh knowledge
Retrieval-augmented generation — retrieve passages into the context instead of retraining; reach for long-context-only when recall over the corpus is the bottleneck.
More detail
RAG keeps the knowledge editable and attributable; the trade is retrieval quality and context budget. Long context can subsume small corpora but pays latency per query and still degrades in the middle.
Long context or retrieval
Retrieval when the corpus is large or changing; long context when the task needs dense joint reasoning over everything at once.
More detail
Needle tests flatter long context — real multi-hop use degrades with distance and cost grows quadratically. RAG's failure mode is recall; long context's is price and mid-context dilution.
Harder problems without a better model
Spend test-time compute — chain-of-thought, then self-consistency / verification, then search — each rung costs tokens for reliability.
More detail
CoT externalises intermediate state the forward pass would have to hold implicitly; sampling-and-verifying buys majority reliability where a verifier exists. The trade is monotone in cost, so the question is where the extra tokens pay.
Generate continuous data (images, audio)
Diffusion — learn to reverse a fixed noising process; run it in latent space when pixels are too expensive.
More detail
Score matching trains the denoiser by regression against the noised sample — stable where GANs oscillate. Latent diffusion moves the iterative loop to a compressed space, buying quality per step.
Steer a diffusion model harder toward the prompt
Classifier-free guidance — extrapolate between conditional and unconditional scores instead of training a separate critic.
More detail
Two forward passes (prompted and un) define a direction; scaling it trades diversity for prompt adherence. The same trick replaces the discriminator that guided diffusion once needed.
Joint image-and-text representations
Contrastive image–text pretraining (CLIP) — align paired embeddings on a batch of negatives; no generative model needed.
More detail
The InfoNCE objective turns caption pairing into classification over the batch. The resulting shared space gives zero-shot classification, retrieval, and the text encoder most VLMs start from.
Rank models or systems on real tasks
Benchmarks for breadth, arena pairwise rankings for open-ended preference — and decontaminate first, or you are measuring memorisation.
More detail
A static suite drifts toward the training corpus and saturates; pairwise human/LLM preference tracks perceived quality but rewards style. Report contamination handling before comparing numbers.
Judge open-ended outputs automatically
LLM-as-judge — with rubrics, position-swap controls and a stated bias audit, since the judge inherits the model's own preferences.
More detail
Position bias, verbosity bias and self-preference are measurable, not hypothetical. The judge is a metric to be validated against humans on a sample, not a ground truth.
A model asserts wrong things confidently
Hallucination is partly a scoring problem: standard metrics pay for confident guessing. Fix the eval's incentive, then tune the model's abstention threshold.
More detail
If 'I don't know' scores zero and a guess scores nonzero, the optimum is to bluff. Calibration and selective abstention are the measurable handles — perplexity and RLHF shape the rest.
Untrusted text inside a trusted prompt
Prompt injection has no complete fix — it is a channel-confusion problem; mitigate with instruction/data separation, least-privilege tools, and output filters, and treat it as a risk to manage.
More detail
The model cannot reliably rank instructions from a data channel it was trained to obey. Defences reduce attack surface — they do not restore a security boundary that never existed in the weights.
Compress or clone a model's behaviour
Knowledge distillation — train the student on the teacher's softened outputs, where the wrong-class ratios carry the transferable structure.
More detail
A soft target carries a whole distribution per example instead of one index; temperature lifts the tail into gradient range and the T² factor keeps the soft loss's contribution stable across temperatures.