Back to Foundation Models Index | Previous: (y-01) Introduction | Next: (y-03) From Counting to Predicting
Mental Model First
- Training changes parameters; inference only uses the learned function. Everything in the course (pretraining, attention, diffusion) comes back to the same four choices: which targets, which loss, which parameters get updated, and which test distribution you evaluate on.
- The loss defines the learning problem. Squared error fits numbers, negative log-likelihood fits probabilities, and binary or multiclass cross-entropy is just the negative log-likelihood of the observed label. The language-model head is a softmax over the vocabulary trained with exactly this loss.
- Low training loss says little about generalization. What you care about is the population risk on new data, which you estimate with a held-out test set that must be free of leakage and representative of deployment. Validation data picks the checkpoint and hyperparameters.
- Gradient descent moves parameters against the gradient, scaled by the learning rate. Backpropagation computes that gradient by multiplying local derivatives along each path through the computation graph and adding contributions where paths meet.
- Architectures are made of linear maps, nonlinearities and shared weights. CNNs build in locality and weight sharing for images; residual connections and layer normalization keep deep stacks trainable; embeddings and self-attention are the same familiar operations rearranged to mix information across token positions.
1. Today’s Lecture
The session covers the tools behind pretraining, attention and generative models in four blocks:
- Learning and evaluation: define a learning problem and distinguish training fit from generalization.
- Optimization and probability: follow a gradient update and connect predictions to likelihood and loss.
- Neural networks: track tensor dimensions and explain the chain rule through a network.
- Architectures and reuse: recognize these ingredients in CNNs, transformers and diffusion.
The transformer architecture diagram from Attention Is All You Need appears throughout as a reminder of where each ingredient ends up later.
2. Training and Inference

Training updates θ from examples and a loss. Inference only applies the learned function to a new input.
During training, examples go into the model , the loss compares prediction and target, and a gradient update changes θ. During inference, a new input goes through the trained model to produce a prediction. Learning changes parameters; inference uses the learned function.
3. Where Does the Learning Signal Come From?

Where the learning signal comes from: supervised, self-supervised, unsupervised and reinforcement learning.
| Paradigm | Learning signal |
|---|---|
| Supervised | Human or measured targets: image → class, molecule → property |
| Self-supervised | Targets derived from the data: context → next token, masked input → hidden content |
| Unsupervised | Structure without supplied targets: clusters or a learned data distribution |
| Reinforcement | Actions affect future observations; learn from rewards over a trajectory |
Foundation-model pretraining is mostly self-supervised: the data supplies its own targets.
4. Data Become Vectors, Matrices, and Tensors

A tensor's shape says what each axis means: d features, B×d mini-batches, B×C×H×W images and B×T×d sequences.
A tensor’s shape states what each axis represents:
- one example: , with features for one observation,
- a mini-batch: , with examples arranged as rows,
- images: (batch, channels, height, width),
- sequences: (batch, tokens, features).
5. The Supervised Learning Problem

A supervised learning problem: a dataset, a model class, parameters θ and a loss.
Given a dataset , a supervised learning problem has three parts:
- Model class: the functions the learner can represent.
- Parameters θ: weights and biases fitted to the training data.
- Loss : how costly a prediction is for the observed target .
6. The Loss Must Match the Prediction Task

Squared error for numerical prediction and log loss for probabilistic prediction. Both return later in diffusion and language models.
- Numerical prediction: squared error . Predicting 3 instead of 1 gives loss 2, and large residuals get a larger penalty.
- Probabilistic prediction: log loss . Assigning probability 0.9 to the observed class costs less than assigning 0.1.
Both come back later: squared error for the noise target in diffusion, and log loss for the next token in a language model.
7. Population Risk and Empirical Risk

Population risk is the expected loss on new data from P. Empirical risk is the average loss on a finite dataset.
The distribution we care about is not available in full.
- Population risk is the expected loss on new examples from : .
- Empirical risk is the average loss on a finite dataset: . On the training set this is the training loss.
8. Training, Validation, and Test Sets

Training fits parameters, validation chooses hyperparameters and checkpoints, and the test set evaluates once all decisions are fixed.
| Set | Used for |
|---|---|
| Training set | Fit the parameters θ |
| Validation set | Choose architecture, learning rate, regularization and checkpoint |
| Test set | Evaluate the selected procedure after all decisions are fixed |
Parameters belong to the fitted model. Hyperparameters configure learning.
A Useful Test Set Must Avoid Leakage

Leakage (the same patient or document on both sides of the split) and distribution shift make a test set misleading.
- Leakage: near-duplicates, the same patient or the same document appear on both sides of the split. The model can then exploit information that will not be available on a truly new case.
- Distribution shift: training and deployment differ in time, language, institution or image conditions. Choose time-based or group-based splits when the intended use requires them.
9. Underfitting and Overfitting

Underfitting and overfitting on synthetic data: too restrictive, a useful fit, and a fit that follows the noise.
On synthetic data with a known true mean, three fits show the spectrum: a restrictive model (a straight line) misses the structure, a suitable model captures the trend, and a very flexible model fits the sampling noise.
Bias, Variance, and Irreducible Noise

Repeated datasets separate bias (restricted class) from variance (flexible class). Expected test error = bias² + variance + noise.
Fitting the same model class to many repeated datasets separates the error sources. A restricted model class gives fits that agree with each other but miss the true mean (high bias). A flexible class gives fits that follow each dataset’s noise and disagree with each other (high variance).
Model size alone does not determine generalization. Data, regularization and optimization also matter.
10. Regularization

Regularization adds a penalty λΩ(θ): L2 shrinks weights, L1 can produce exact zeros, plus early stopping, augmentation and dropout.
Among models that fit the training data, regularization prefers some solutions over others:
Penalties on the weights: with shrinks weights, and with can produce exact zeros. Other controls: early stopping limits training time, data augmentation expresses useful invariances, and dropout perturbs hidden activations during training.
11. Linear Regression

Linear regression fits a weighted sum. Residuals (red) are the gaps between prediction and target.
Linear regression fits a weighted sum to a numerical target:
The residual is . The weight vector controls the sensitivity to each feature, and shifts the prediction.
Vectorized Regression and Dimensions

Vectorized regression: one matrix multiplication handles a whole mini-batch, the same pattern as the Q, K and V projections later.
One matrix multiplication evaluates a whole mini-batch. With , and a scalar :
The same pattern returns in attention: , and are learned linear projections.
12. Gradient Descent

Gradient descent steps against the gradient. The learning rate η sets the step size.
Gradient descent moves the parameters opposite to the local gradient:
The gradient points toward the steepest local increase, and the learning rate η controls the step size. Least squares has a closed-form solution, but deep networks require iterative optimization.
One Gradient Update by Hand

One update by hand on (1, 2) and (2, 4): the loss drops from 5 to 2.1825 after a single step with η = 0.1.
Two data points, and , with . Start with , , :
- Predictions , residuals , loss .
- and .
- Update: and .
- New predictions and new loss .
The Learning Rate Changes the Behavior

On J(w) = ½w², η = 0.1 is slow, η = 0.8 converges quickly, and η = 2.1 diverges. Convergence needs 0 < η < 2.
For , starting at , the gradient is , so the exact update is . With the steps are small and convergence is slow, converges quickly, and overshoots with growing oscillations. For this example, convergence requires .
Mini-batches and Optimizers

Full-batch descent, mini-batch SGD, and momentum and Adam, which use the gradient history.
The mini-batch gradient is .
- Full-batch descent uses all training examples for each update.
- Mini-batch SGD uses a sampled subset; updates are faster but carry sampling noise.
- Momentum and Adam use the gradient history. Adam also rescales updates by estimated second moments.
Learning Curves Guide Model Selection

Training loss keeps falling while validation loss turns up. Select the checkpoint at the validation minimum.
Training loss alone does not select the best checkpoint. In the example, training loss keeps falling while validation loss reaches its minimum around epoch 18 and then rises again. Inspect training and validation loss, the task metric, and performance across relevant groups. Restore the checkpoint selected on validation data, then evaluate on the test set.
13. Linear Classification

Linear classification: the boundary is where z = x₁ − x₂ + 0.5 is zero, and points below it are class 1.
The decision boundary is where the score is zero:
Example: . The boundary is , and points below it have class 1.
Logistic Regression

Logistic regression squashes the linear score with a sigmoid. Thresholding at 0.5 still gives a linear boundary.
A sigmoid turns the linear score into a probability:
The sigmoid is nonlinear, but thresholding at 0.5 still gives a linear decision boundary. (The MPL course works through logistic regression on the Iris data in MPL L01.)
Binary Cross-Entropy

Binary cross-entropy is maximum likelihood for a Bernoulli target. Its gradient with respect to the score is p − y.
Binary cross-entropy is maximum likelihood for a Bernoulli target:
For : gives loss ≈ 0.105, and gives loss ≈ 2.303.
Softmax and Multiclass Cross-Entropy

Softmax turns scores (2, 1, 0) into probabilities (0.665, 0.245, 0.090). With target B the loss is −log 0.245 ≈ 1.408.
Softmax converts scores into a categorical distribution:
Example: scores for classes A, B, C give probabilities . If the target is B, the loss is . Later, the language-model output head predicts exactly such a distribution over vocabulary tokens.
Entropy, Cross-Entropy, and Likelihood

Entropy measures uncertainty in p, and cross-entropy H(p, q) = H(p) + KL(p‖q) measures predicting p with q.
These related quantities answer different questions:
- Entropy, the uncertainty in : . For a binary variable it peaks at .
- Cross-entropy, predicting using : .
- They are linked by .
For one-hot labels, cross-entropy equals the negative log-probability of the target.
14. Check Your Understanding
The lecture’s mid-session questions (answers in the Self-Check below):
- Training loss falls while validation loss rises. Which checkpoint would you select?
- The correct class has probability 0.2. What is its cross-entropy loss?
- Why does the learning rate belong to the hyperparameters rather than the fitted weights?
- An LLM predicts the next token. What supplies the target during pretraining?
15. Neural Networks Learn Intermediate Representations

A multilayer perceptron learns intermediate representations through affine maps and activations.
A multilayer perceptron applies a learned affine map and an activation in each layer:
The hidden features can make the final prediction easier.
Nonlinearity Makes the Model Class Richer

Without activations, stacked affine layers collapse into one. For XOR, two hidden features make the classes separable.
Without activations, stacked affine layers collapse into one affine map:
For XOR, one line is insufficient. Two useful hidden features detect whether exceeds 0.5 or 1.5, and the classes become separable from those features.
Activation Functions and Their Gradients

Sigmoid saturates, ReLU gives zero gradient to inactive units, and GELU is smooth and used in transformer feed-forward layers.
- Sigmoid can saturate and produce small gradients.
- ReLU is piecewise linear; inactive units receive zero gradient.
- GELU is smooth and appears in transformer feed-forward layers.
Dimensions through an MLP

Tracking dimensions through an MLP. With d = 4, h = 8 and K = 3 the network has 67 parameters.
With the row-batch convention (one example per row of ):
Example: , , gives parameters.
16. A Computation Graph Makes Dependencies Explicit

A computation graph for one ReLU unit: x = 2 gives z = 1, h = 1, ŷ = 3 and a loss of 2 against target 1.
One input, one hidden ReLU and a squared-error loss. With , , and :
- , , .
- With target : .
The forward pass stores the intermediate values needed for differentiation.
Backpropagation Applies the Chain Rule

Backpropagation on the same graph: multiply local derivatives along paths to get ∂ℓ/∂v = 2, ∂ℓ/∂z = 6, ∂ℓ/∂w = 12 and ∂ℓ/∂b = 6.
The same example, evaluated backward:
- Output weight:
- Hidden pre-activation:
- and
Multiply local derivatives along a path, and add the contributions where paths meet.
The Training Loop
Automatic differentiation computes derivatives of the recorded operations:
repeat over mini-batches (X, y):
clear stored gradients
predictions = model(X; θ)
loss = objective(predictions, y)
gradients = backward(loss)
θ = optimizer_step(θ, gradients)The loss defines the learning problem; the optimizer uses its gradients.
17. Depth, Gradients, and Residual Connections

Repeated factors make gradients vanish (0.5¹⁰) or explode (2¹⁰). A residual block adds the input back, x + F(x).
Backpropagation multiplies local Jacobians. Repeated small or large factors make gradients vanish or explode: and . A residual block computes , so the identity path carries the signal and its gradient past . Transformer blocks later combine residual paths, normalization, attention and MLPs.
Layer Normalization

Layer normalization computes mean and variance over the d features of each token, with learned γ and β per feature.
Layer normalization normalizes the feature coordinates of each example or token:
γ and β are learned per feature, and ε is a small numerical constant. For a sequence tensor, each token gets its own statistics over .
18. Images Have Spatial Structure

Flattening an image keeps the values but loses neighborhoods. A fully connected layer has no locality or weight sharing built in.
Flattening an image keeps the pixel values but removes the explicit neighborhood structure. A fully connected layer can learn from flattened pixels, but it uses separate weights for different pixel positions and does not build local connectivity or weight sharing into the architecture. CNNs encode locality and shared filters; image transformers use patch embeddings. (For the full CNN treatment see MPL L02: CNNs.)
Convolution: One Local Computation

A convolution is a dot product between a local patch and a shared filter, here giving 1 − 3 + 2 = 0.
A filter uses the same weights at every spatial position. Each output is the dot product between a local input patch and the filter, plus a bias. With the patch and a vertical edge filter whose rows are all , the entrywise products sum to , and with the output is 0.
CNN Architecture

One filter turns an input digit into a response map.

A CNN stacks convolution and pooling layers for feature learning, then flattens into an MLP for classification.
A CNN consists of convolutional layers, which learn visual patterns by adapting their parameters, followed by an MLP that predicts from the flattened output of the last convolutional layer. The visualization shows a single filter turning an input digit into a response map that highlights its edges.
Stride and Padding

Stride is the pixel distance between receptive fields. Stride 2 shrinks the output volume.

Zero padding adds a border so filters can also be applied at the corners.
- Stride is the pixel distance between neighboring receptive fields, which can overlap. Stride affects the output volume.
- Padding: filters cannot be centered on the corners of the input. If that is a problem, zeros are added at the boundary (zero padding), which again affects the output volume.
Stride and Padding Determine Output Size

Output size H_out = ⌊(H + 2p − k)/s⌋ + 1. A 3×3 kernel with s = 1 and p = 1 keeps a 7×7 input at 7×7.
with kernel size , stride and padding on each side (dilation 1; the same rule applies to the width). For and : gives ; gives ; and preserves the size.
Parameter Sharing and the Output Volume

Parameter sharing: one H_F × W_F × D_F filter has H_F · W_F · D_F + 1 parameters, whatever the image size.

Each filter yields one output channel. Stacking D_O filters gives an H_O × W_O × D_O output tensor.
The same filter is applied to every receptive field, which reduces the number of parameters and allows generalization. An filter has parameters (the is the bias). The input to a convolutional layer is an tensor; every filter yields an output, and stacking the outputs of filters yields an tensor.
Equivariance, Invariance, and Pooling

Convolution is translation equivariant. Pooling summarizes a region (max 3, mean 1.5) and reduces, but does not remove, position sensitivity.
Parameter sharing causes translation equivariance: , so a shifted input (the cat moved in the image) produces a correspondingly shifted feature map. Convolution has this property ideally; boundaries and striding can break it.
Pooling summarizes a region: for the values , max pooling gives 3 and average pooling 1.5. Each neuron only sees a small receptive field, and often we care about the presence of a feature, not its exact location. Invariance means the output stays the same under a shift; pooling can reduce sensitivity to position but does not guarantee invariance.
Down-Sampling

Stride and pooling both down-sample, which can avoid overfitting or cause underfitting.
Stride and pooling both down-sample: stride skips regions, pooling summarizes them. The trade-off is that down-sampling can avoid overfitting (dropping irrelevant details) but can also cause underfitting (dropping relevant details).
Receptive Fields Grow with Depth

Receptive fields grow with depth: two 3×3 layers see a 5×5 region, and local patterns combine into parts.
Successive layers combine information from progressively larger input regions: two layers with stride 1 give a receptive field. Local edge and corner patterns combine into parts, and parts into a “cat”. Visual encoders and convolutional denoisers later rely on such learned spatial representations.
19. Embeddings Put Tokens into a Vector Space

Embeddings: a token id becomes a row of the embedding matrix E, and an image patch goes through a shared linear projection.
- Text tokens: token id , a row lookup in a learned embedding matrix . One token becomes one -dimensional vector.
- Image patches: patch vector . Each patch is flattened and passed through a shared learned projection.
Position information identifies where the tokens occur. A sequence of embeddings then becomes the input to a transformer.
20. A First Look at Self-Attention

Self-attention: dot products compare queries with keys, softmax turns each row into weights, and weighted sums combine values.
Self-attention combines familiar operations to mix information across token positions:
- Dot products: compares each query with each key.
- Softmax: each row becomes weights that sum to one.
- Weighted sums: those weights combine the value vectors.
(The full transformer is covered in MPL L05: Transformers.)
21. Self-Supervision Creates Prediction Targets

Self-supervision builds the targets from the data. The autoregressive loss sums −log p(xₜ | x<ₜ) over the sequence.
The optimizer can stay the same while the target construction changes. An autoregressive language model turns “The sky is” into the target “blue” and minimizes
Other self-supervised tasks: masked prediction recovers hidden content, and contrastive learning scores a matched image-text pair above mismatched pairs.
22. Pretraining and Adaptation Reuse Learned Parameters

Pretraining gives θ_pre as a starting point, and adaptation adds Δθ using task data.
- Pretraining optimizes a broadly useful objective on a large and varied dataset; the result is a learned starting point.
- Adaptation uses new task data to update all parameters or a chosen subset: .
The same questions return each time: which targets, which loss, which parameters, and which test distribution?
23. Reading and Connections to Later Lectures
- ML and neural networks: Russell and Norvig, Artificial Intelligence: A Modern Approach (4th Global ed.), chapters 19 and 22.
- Attention and transformers: Vaswani et al. (2017), Attention Is All You Need.
- Residuals and normalization: He et al. (2016), Deep Residual Learning; Ba et al. (2016), Layer Normalization.
- Optimization: Loshchilov and Hutter (2019), Decoupled Weight Decay Regularization.
- Diffusion: Ho, Jain and Abbeel (2020), Denoising Diffusion Probabilistic Models.
Summary
- A learning problem is a model class, parameters and a loss. The loss must fit the task: squared error for numbers, negative log-likelihood (cross-entropy) for probabilities.
- Generalization is about population risk. Training, validation and test sets have separate jobs, and leakage or distribution shift make a test set useless. Expected test error = bias² + variance + noise.
- Regularization (, , early stopping, augmentation, dropout) prefers some solutions among those that fit.
- Gradient descent with learning rate η (stable only in a range, here ), mini-batch SGD, momentum and Adam; select checkpoints on validation loss.
- Logistic regression, binary cross-entropy with gradient , softmax cross-entropy with gradient , and .
- MLPs need nonlinearities; backpropagation multiplies local derivatives along paths; residual connections and layer norm keep deep networks trainable.
- CNNs: local filters, parameter sharing, stride and padding (), equivariance, pooling, growing receptive fields.
- Embeddings, self-attention and self-supervised targets connect all of this to foundation models.
Self-Check
- Training loss falls while validation loss rises. Which checkpoint do you select, and why?
Answer
The checkpoint with the lowest validation loss, at the point where validation loss starts to rise. After that the model fits noise in the training data and generalizes worse. Restore that checkpoint and only then evaluate it once on the test set.
- The correct class has probability 0.2. What is its cross-entropy loss?
Answer
(natural log). For one-hot labels, cross-entropy is the negative log-probability of the target class.
- Why is the learning rate a hyperparameter and not a fitted weight?
Answer
It configures how learning happens (the step size of the optimizer) instead of being part of the fitted function . Hyperparameters like the learning rate, architecture and regularization are chosen with the validation set; parameters are fitted on the training set.
- An LLM predicts the next token. What supplies the target during pretraining?
Answer
The data itself. In self-supervised pretraining, the next token of the training text is the target for the context before it, so no human labels are needed. The loss is .
- What is the difference between population risk and empirical risk?
Answer
Population risk is the expected loss on new examples drawn from the distribution we care about, which we cannot compute because is not available in full. Empirical risk is the average loss on a finite dataset; on the training set it is the training loss, and on a held-out test set it estimates the population risk.
- Give two ways a test set can fail to measure generalization.
Answer
Leakage: near-duplicates, the same patient or the same document end up on both sides of the split, so the model exploits information a truly new case would not have. Distribution shift: training and deployment differ in time, language, institution or image conditions, which calls for time-based or group-based splits.
- Compute one gradient step for on the points (1, 2) and (2, 4), starting from with and .
Answer
Residuals are (−2, −4), so . and . The update gives and , the new predictions are (0.8, 1.3), and the new loss is 2.1825.
- For , which learning rates converge, and why?
Answer
The update is , which shrinks only if , so . Small η (0.1) converges slowly, η around 0.8 converges fast, and η = 2.1 overshoots with oscillations that grow.
- Why do stacked linear layers need activation functions?
Answer
Without them, collapses into a single affine map , so depth adds nothing. Nonlinear activations let hidden features (like detecting whether exceeds 0.5 or 1.5 for XOR) make problems separable that a single line cannot solve.
- In the computation graph with , , , and , what are and ?
Answer
The forward pass gives , , and . Backward: , , so and .
- A 7 × 7 input goes through a 3 × 3 convolution with stride 2 and no padding. What is the output size? What padding keeps 7 × 7 with stride 1?
Answer
, so 3 × 3. With stride 1, padding gives and preserves the 7 × 7 size.
- What is the difference between translation equivariance and invariance, and which one does pooling give?
Answer
Equivariance means a shifted input gives a correspondingly shifted output, , which convolution has ideally thanks to parameter sharing. Invariance means the output stays the same under the shift. Pooling reduces sensitivity to position but does not guarantee invariance.
- Final check from the lecture: what changes between token prediction and noise prediction?
Answer
The target construction and the loss, while the optimizer and the reuse of learned parameters stay the same. Token prediction uses the next token as a categorical target with a log loss (cross-entropy over the vocabulary). Noise prediction in diffusion regresses the added noise with a squared error loss.
Back to Foundation Models Index | Previous: (y-01) Introduction | Next: (y-03) From Counting to Predicting