# Autoencoders and the VAE, from the ELBO: speaker notes

Planned main route: 85 minutes. Timing includes student responses and the specified short demonstrations. Optional extensions are outside this budget.

## Pacing

| Episode | Minutes |
|---|---:|
| Lecture map | 1 |
| Part 1 · Why generate? | 13 |
| Part 2 · Autoencoders: squeeze, then rebuild | 18 |
| Part 3 · Can an autoencoder generate? | 10 |
| Part 4 · From an autoencoder to a VAE: three fixes | 12 |
| Part 5 · Why this loss: Lecture 1’s ELBO, one image at a time | 26 |
| Part 6 · Putting it together | 5 |

## contents: Lecture 5 at a glance: six parts, twenty-five sections

**Build 1, ask:** Which part leans most on Lecture 1?

**Expected:** Part 5: the VAE’s loss is Lecture 1’s ELBO with a code per image. Part 6 traces every term back to it.

**Point here:** A 60-minute cut: in Part 1 skip gen-disc; in Part 2 skip ae-untrained, ae-step, code-size and ae-overfit; in Part 3 skip ae-grid and ae-empirical; keep all of Part 4; in Part 5 skip vae-code and beta-what. The optional slides carry the detours, and Lecture 2 has the full two-session version.

**Transition:** Part 1: why generate?

## part-1: Part 1 · Why generate?

**Build 1, ask:** What do a chatbot, an image generator and a weather model have in common?

**Expected:** Each turns random numbers into a new sample, through a network fitted to data.

**Transition:** Section 1.1.

## faces: Who are these people?

**Build 1, ask:** Who are these people? Would you have known?

**Expected:** Students guess celebrities or stock photos. None exist.

**Build 2, ask:** What did the network need, to make these?

**Expected:** Many real photographs to learn from, and a way to turn random numbers into new ones. That is today’s subject.

**Transition:** A smaller test, on the digits we will use all lecture.

**Source / evidence:** Faces generated by StyleGAN: Karras, Laine and Aila, “A Style-Based Generator Architecture for GANs”, CVPR 2019. NVIDIA, CC BY-NC 4.0.

## realfake: Real or generated? Six of these twelve digits are fake

**Build 1, ask:** Which six are fake? Write the positions.

**Expected:** Answers vary; take a quick show of hands for two or three digits.

**Build 2, ask:** Which fakes gave themselves away, and how?

**Expected:** Broken or doubled strokes and blurry edges give some away; the cleanest fakes are hard to tell.

**Point here:** Real digits: six random MNIST test images. Fakes: the first six draws z ~ N(0, I) through Lecture 2’s 16-number VAE, not chosen by hand.

**Transition:** Generative models are everywhere now: a quick tour, then the common idea.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## llm: A chatbot is a generative model: one prompt, three different answers

**Build 1, ask:** If we send the same prompt again, do we get the same sentence?

**Expected:** No: the model samples, so each run differs.

**Build 2, ask:** Why would we want different answers each time?

**Expected:** Variety: one prompt has many good answers. A model that always gave the single most likely sentence would be repetitive.

**Transition:** Pictures: one prompt, many images.

**Source / evidence:** Generated for Lecture 2 on 21 October 2026 with Gemini 3.5 Flash, temperature 1 (<code>lecture2/assets/examples/provenance.json</code>).

## t2i: Text to image: one prompt, four samples

**Build 1, ask:** What stayed the same across the four, and what changed?

**Expected:** Same: camel, salt flat, sunrise, watercolour. Changed: rider, framing, sky.

**Build 2, ask:** Where does the variety come from?

**Expected:** From random numbers fed into the model; the prompt only narrows what is plausible.

**Transition:** A model of what, exactly? First, the letters.

**Source / evidence:** Generated for Lecture 2 on 21 October 2026 with Gemini 3 Pro Image (<code>lecture2/assets/examples/provenance.json</code>).

## xy: First, the names: x is the data, y is a label

**Build 1, ask:** What is x for a chatbot? For a spam filter, what are x and y?

**Expected:** A chatbot: x is a sentence. Spam filter: x is the email, y is spam or not.

**Build 2, ask:** Read p(y | x) aloud. What do its ten numbers add up to?

**Expected:** “p of y given x”: one probability per label for this image; they add up to 1.

**Build 3, ask:** What should p(x) be for random static?

**Expected:** Almost 0: nobody writes static. That is how p(x) spots odd inputs.

**Build 4, ask:** Which probability does a text-to-image model learn?

**Expected:** p(image | prompt): a conditional generative model, with the prompt in the place of y.

**Point here:** The classifier is a softmax regression (784 numbers in, 10 out) on the 60,000 training digits: 92.2% of test digits right. Its least sure display digit, a 5, gets 9: 27%, 5: 24%, 4: 21%: p(y | x) is a distribution, not just a label.

**Transition:** Draw all of these in one picture.

**Source / evidence:** Classifier and numbers: <code>lecture5/scripts/xy.py</code>. Digits from Lecture 2’s data; the new x is a draw from its 16-number VAE.

## gen-disc: Generative or discriminative, in one picture

**Build 1, ask:** Where is p(x) high? Where is it near 0?

**Expected:** High near ink 60 and 136, where most images are; near 0 above 230: almost no digit has that much ink.

**Build 2, ask:** Why is the 1s’ hump taller and narrower?

**Expected:** The 1s all use about the same ink, so their hump is narrow; and they are a little more common: 53%.

**Build 3, ask:** Can you get the top picture back from the bottom curve alone?

**Expected:** No. p(y | x) says nothing about where the data are, so it cannot score or draw an x. The top gives the bottom, never the other way.

**Point here:** This is Bayes’ rule, as in Lecture 1, with the label y as the unknown: p(y | x) = p(x | y) p(y) / p(x). Humps: Gaussian kernel densities (bandwidths 6.2 and 3.1) of the 5,923 training 0s and 6,742 1s.

**Transition:** What is a model of p(x) good for?

**Source / evidence:** Numbers: <code>lecture5/scripts/xy.py</code> (MNIST training set).

## uses: What a model of p(x) is good for

**Build 1, ask:** Which of these needs only samples? Which needs a score p(x)?

**Expected:** Create, fill in, simulate and make more data: samples. The odd one out and compression: a score.

**Build 2, ask:** Which use connects to Lecture 1?

**Expected:** Compression: an event with probability p costs log₂(1/p) bits, Lecture 1’s codes.

**Transition:** What do all these models have in common?

## recipe: What they share: random numbers in, a learned network, a sample out

**Build 1, ask:** What plays the role of z in the chatbot?

**Expected:** The random choices made when sampling each next word.

**Build 2, ask:** What is the condition for the camel pictures?

**Expected:** The text prompt.

**Transition:** Two jobs such a model can do.

## two-jobs: A model of p(x) can do two jobs: score and sample

**Build 1, ask:** Which job does the chatbot do when it writes?

**Expected:** Sample.

**Build 2, ask:** Which job does anomaly detection need?

**Expected:** Score: flag inputs with low p(x).

**Transition:** Why not just output the average example?

## why-not-mean: Why not just output the average?

**Build 1, ask:** Would you accept the average as a new handwritten 3?

**Expected:** No: it is a ghost of many 3s.

**Build 2, ask:** When is the average still useful?

**Expected:** As a summary, or as a prediction scored by squared error, but not as a sample.

**Transition:** Today’s route.

## today: Today: two networks, then Lecture 1’s objective

**Build 1, ask:** What will the autoencoder’s 2 numbers have to keep?

**Expected:** Whatever is needed to rebuild the digit: which digit, its slant, its thickness.

**Build 2, ask:** What would “generate” mean for the second network?

**Expected:** Turn numbers we invent into a new, convincing digit.

**Build 3, ask:** Which piece of this loss have you seen before?

**Expected:** The KL to N(0, I): Lecture 1’s KL to the prior. The squared error turns out to be the likelihood term.

**Point here:** The loss on this slide drops a constant (784 log(σ√2π)); Sections 5.5 and 6.1 show where every term comes from.

**Transition:** Part 2: autoencoders.

## part-2: Part 2 · Autoencoders: squeeze, then rebuild

**Build 1, ask:** Why would squeezing a digit into 2 numbers be useful?

**Expected:** The 2 numbers must keep what matters about the digit. Later we will try inventing them.

**Transition:** Section 2.1.

## mnist: MNIST: 70,000 handwritten digits, 28 × 28 pixels each

**Build 1, ask:** How many pixels does each image have?

**Expected:** 28 × 28 = 784.

**Build 2, ask:** Why keep one running example?

**Expected:** Every model can be checked on the same 3: its code, its reconstruction and its loss.

**Transition:** Squeeze those 784 numbers into 2.

**Source / evidence:** MNIST (LeCun, Cortes and Burges), grey levels scaled to [0, 1].

## ae-arch: An autoencoder: encoder, short code, decoder

**Build 1, ask:** Why squeeze through so few numbers?

**Expected:** To force it to keep only what matters about the digit.

**Build 2, ask:** What would happen with a 784-number code?

**Expected:** It could copy the input and learn nothing useful.

**Build 3, ask:** What is the target output?

**Expected:** The input itself: the network is trained to rebuild x.

**Point here:** Hinton and Salakhutdinov (Science, 2006) made deep autoencoders work; the idea goes back to the 1980s. One hidden layer of 400 units follows Kingma and Welling (2014).

**Transition:** The same in PyTorch.

## ae-code: Two small networks in PyTorch

**Build 1, ask:** How many weights does the encoder have?

**Expected:** 784 × 400 + 400 + 400 × 2 + 2 ≈ 315,000.

**Build 2, ask:** Why no activation after the encoder’s last layer?

**Expected:** The code can be any real number; a ReLU would forbid negative codes.

**Transition:** What does it minimise?

## ae-loss: The loss: how far each rebuilt pixel is from the real one

**Build 1, ask:** Which weights does the loss depend on?

**Expected:** Both φ (encoder) and θ (decoder).

**Build 2, ask:** Where are the large errors?

**Expected:** Along the strokes: the rebuilt 3 is blurrier and thinner than the real one.

**Build 3, ask:** Why sum over pixels but average over images?

**Expected:** The sum is the error of one image; averaging over images keeps the loss independent of the batch size.

**Point here:** Teal = target, purple = prediction, red = loss, as in every loss slide of the series.

**Transition:** Before training: what comes out?

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## ae-untrained: Before training: always look at what the network outputs

**Build 1, ask:** Why is every output close to 0.5?

**Expected:** Small random weights make the pre-sigmoid values near 0, and sigmoid(0) = 0.5.

**Build 2, ask:** What would it mean if training ended near 185?

**Expected:** The network learned nothing: a bug, or a learning rate that is far off.

**Transition:** Train it.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## ae-step: One training step: forward, loss, backward, update

**Build 1, ask:** How many updates in total?

**Expected:** 14,070.

**Build 2, ask:** Does the encoder get a gradient even though the loss compares only images?

**Expected:** Yes: the reconstruction depends on the code, which depends on the encoder’s weights.

**Transition:** Watch the reconstructions form.

## ae-train: Press play: reconstructions sharpen, then stop improving

**Build 1, ask:** What does the network learn first?

**Expected:** The average digit: a blurry blob that lowers the error everywhere.

**Build 2, ask:** Is it worth training for 1,000 epochs?

**Expected:** Not here: the training digits keep improving, the test digits do not. To rebuild better we need a bigger code (next slide).

**Point here:** Frames to epoch 30: Lecture 2’s run. Later frames: the same run replayed step for step and continued by lecture5/scripts/epochs.py (its epoch-30 frame matches Lecture 2’s).

**Transition:** How much does the code size matter?

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## code-size: More numbers in the code, sharper rebuilds

**Build 1, ask:** What does the 2-number code lose?

**Expected:** Stroke thickness, slant and small details.

**Build 2, ask:** Which of these would you pick?

**Expected:** For rebuilding, the widest. For generating, wait for Part 3.

**Transition:** Where do the 2-number codes land?

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## ae-scatter: Where the codes land: 1,000 test digits at their 2 numbers

**Build 1, ask:** Which digits are still mixed?

**Expected:** 4 and 9; some 3, 5 and 8.

**Build 2, ask:** The codes run from about −5 to 22. Is that a problem?

**Expected:** Not for rebuilding. For generating, Part 3 will show it is.

**Transition:** How did the codes get there? Watch them during training.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## ae-epochs: During training: clusters form, then the codes drift out

**Build 1, ask:** What stops the codes from drifting further out?

**Expected:** Nothing in the loss: it scores only the rebuild, so any position and any scale of the codes is equally good.

**Build 2, ask:** Is this autoencoder overfitting?

**Expected:** A little, and late: the test error is lowest at epoch 65 (30.5) and creeps up to 32.4 while the training error keeps falling. With only 200 digits it is far worse: next slide.

**Point here:** Lecture 2’s training of this exact network, replayed step for step (same seed and batches), then continued from epoch 30 to 1,000. “Same axes throughout” uses the epoch-1,000 window.

**Transition:** Now give it far too little data, and train for far too long.

**Source / evidence:** Lecture 2’s network and training, replayed and extended by <code>lecture5/scripts/epochs.py</code>.

## ae-overfit: Overfitting: too few digits, and the codes fly apart

**Build 1, ask:** Why does the training error keep falling while the test error rises?

**Expected:** The network memorises its 200 digits: it pushes their codes apart, so each gets a private spot the decoder can draw exactly. New digits were never part of that.

**Build 2, ask:** Why does our 3 come back as a 2?

**Expected:** The decoder only learned to draw its 200 training digits. Our 3’s code lands near a training 2’s, so the rebuild is closer to that 2 (error 33.7) than to our 3 (65.6).

**Point here:** Every step uses all 200 digits (no batches), Adam with step size 0.001, on the CPU. “Zoom to fit” rescales each epoch, so you can see the shape; “same axes” shows the drift.

**Transition:** Part 3: can the decoder generate?

**Source / evidence:** <code>lecture5/scripts/epochs.py</code> (MNIST, fixed seeds).

## part-3: Part 3 · Can an autoencoder generate?

**Build 1, ask:** What would a good random code have to look like?

**Expected:** Like the codes real digits get, so the decoder knows what to draw.

**Transition:** Section 3.1.

## gen-question: Keep the decoder, feed it random numbers

**Build 1, ask:** What should a random code look like, to give a good digit?

**Expected:** Like the codes real digits get.

**Build 2, ask:** Why might N(0, I) be a poor choice?

**Expected:** Nothing in training told the codes to look like N(0, I): they run from −5 to 22.

**Transition:** Feed such draws to three decoders.

## ae-random: Random codes through three autoencoders

**Build 1, ask:** Which row looks most like digits?

**Expected:** The 2-number one.

**Build 2, ask:** The 128-number model rebuilt best. Why does it generate worst?

**Expected:** Its codes for real digits are nowhere near where N(0, I) puts its draws.

**Build 3, ask:** What would you check to find out?

**Expected:** Plot where real codes are, next to the random codes.

**Transition:** Plot where the codes are.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## overlay: Put the random codes on top of the real ones

**Build 1, ask:** Hover a red dot near the origin, then one in an empty area. What does the decoder draw?

**Expected:** Near real codes: a digit; in empty places: blurs or odd strokes.

**Build 2, ask:** For the 128-number model, where would the red points fall?

**Expected:** Even further from the real codes: in 128 numbers the space is mostly empty.

**Point here:** The decoder runs in the browser from lecture2/data/nets.json.

**Transition:** Try choosing codes yourself.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## explore-ae: Your turn: three ways to choose a code

**Build 1, ask:** Which of the three ways gives the best digits?

**Expected:** Encoding a real digit. Random codes and clicks far from the dots mostly give smudges.

**Transition:** Decode a whole grid of codes at once.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## ae-grid: Decode a whole grid of codes

**Build 1, ask:** Which parts of the grid are useful for generation?

**Expected:** Those over the clusters of real codes.

**Build 2, ask:** What does the decoder do far from any real code?

**Expected:** It extrapolates from the nearest digits: exaggerated or broken shapes.

**Transition:** Why not sample from the real codes, then?

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## ae-empirical: Why not sample from the real codes instead of N(0, I)?

**Build 1, ask:** What do we get if we decode a real code exactly?

**Expected:** The training digit it came from, blurred by the 2-number code: a copy, not a new digit.

**Build 2, ask:** Where can the jittered codes go wrong?

**Expected:** Between two clusters: the decoder never trained on codes there, so it blends two digits.

**Build 3, ask:** Why does this beat N(0, I) for the plain autoencoder?

**Expected:** It follows where the real codes are, so every digit type is covered, not just the corner N(0, I) reaches.

**Build 4, ask:** What does the VAE give that this two-step recipe does not?

**Expected:** One model and one objective: codes that fill N(0, I) by design, and a lower bound on log p(x) to score an image.

**Point here:** “In a gap”: the nearest training code is further than 0.26, the 99th percentile of that distance for the 10,000 test digits. Copies: 0%; jitter: 2.3%; 10 Gaussians: 1.4%; N(0, I): 0.7% (10,000 draws each). With 60,000 codes in 2 numbers the plane is crowded; the real cost of N(0, I) is the digits it misses, not gaps.

**Transition:** What we want instead.

**Source / evidence:** Lecture 2’s 2-number autoencoder and its 10-Gaussian fit to the training codes; draws and decodes: <code>lecture5/scripts/empirical.py</code>.

## wishes: What we saw, and what we want instead

**Build 1, ask:** How could we push codes towards N(0, I)?

**Expected:** Penalise codes that stray from it, for example with a KL to N(0, I).

**Build 2, ask:** How could each image own a cloud instead of a point?

**Expected:** Let the encoder output a mean and a spread, and draw the code from them.

**Build 3, ask:** Which tool from Lecture 1 will we need?

**Expected:** Variational inference and the ELBO (Part 5), with its reparameterisation trick and Gaussian KL (Part 4).

**Transition:** Part 4: three fixes, one at a time.

## part-4: Part 4 · From an autoencoder to a VAE: three fixes

**Build 1, ask:** Which problem from Part 3 would you fix first?

**Expected:** Where the codes live: random codes from N(0, I) missed the real codes.

**Transition:** Section 4.1.

## fix-prior: Fix 1: choose where the codes live, before training

**Build 1, ask:** Why not let the network choose the code distribution itself?

**Expected:** Then we would not know how to sample from it: that was the autoencoder’s problem.

**Build 2, ask:** Why N(0, I) and not, say, a uniform square?

**Expected:** Any simple, known distribution would do. N(0, I) is smooth, has no edges, and its KL has a formula (Fix 3).

**Build 3, ask:** What must training now achieve?

**Expected:** The codes of real images must spread over N(0, I), with no large holes.

**Point here:** In Part 5 this choice becomes the prior p(z), and it keeps the green colour of Lecture 1’s prior.

**Transition:** Fix 2: fill the gaps.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## fix-cloud: Fix 2: send each image to a small cloud of codes, not a point

**Build 1, ask:** Which parts of the code plane does an autoencoder’s decoder see in training?

**Expected:** Only the exact codes of training images.

**Build 2, ask:** What does the decoder learn when clouds overlap?

**Expected:** To draw something sensible everywhere the clouds reach, including between images.

**Point here:** A sketch, not data. Lecture 2, Section 6.2 calls Part 4 “Road 1” to the VAE.

**Transition:** How a network outputs a cloud.

## fix-net: How a network outputs a cloud: a mean, a spread and a random draw

**Build 1, ask:** Why output log σ² instead of σ?

**Expected:** Any real number is a valid log variance; σ = exp(½ log σ²) is then positive.

**Build 2, ask:** Why reparameterise instead of sampling z directly?

**Expected:** sample() blocks the gradient path from the loss to μ and σ.

**Build 3, ask:** At test time, which code do we use to rebuild?

**Expected:** Usually the mean μ.

**Transition:** Fix 3: what stops the clouds drifting apart?

## fix-kl: Fix 3: a penalty that pulls every cloud towards N(0, I)

**Build 1, ask:** What would the encoder do without this penalty?

**Expected:** Make clouds tiny and far apart: reconstruction is easiest that way.

**Build 2, ask:** Why a KL and not just μ²?

**Expected:** μ² would pull clouds to the centre but let σ shrink to 0. The KL stops both, and Part 5 shows it is exactly what Lecture 1’s ELBO asks for.

**Build 3, ask:** Why does a cloud shrunk to a point cost anything?

**Expected:** The KL averages log q − log N(0, 1) over the cloud. A narrow cloud’s density is huge where it sits, while N(0, 1) stays below 0.4, so the gap grows without limit as σ → 0.

**Point here:** Tool ② has a closed form for the KL between two Gaussians; the appendix slide “Minus the ELBO is Part 4’s loss” and the notebook (4.3) write it out.

**Transition:** Put the three fixes together.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## fix-loss: The three fixes give a loss: reconstruction plus KL

**Build 1, ask:** Which fixes act only in training?

**Expected:** Fixes 2 and 3. Fix 1 is also where we draw codes to generate, and it is the KL’s target in training.

**Build 2, ask:** Which term is the autoencoder’s loss?

**Expected:** The reconstruction term, with a random draw from the cloud in place of a fixed code.

**Build 3, ask:** What would a weight of 0 on the KL give?

**Expected:** An autoencoder with noisy codes; in practice the clouds shrink to points (Section 5.8, β = 0).

**Build 4, ask:** What would a probability model add?

**Expected:** A reason for the loss and its weights, and a score for images: a lower bound on log p(x).

**Point here:** Papers and code call the two terms the reconstruction loss and the KL (or regularisation) term.

**Transition:** The two terms pull against each other.

## vae-tug: Two terms pull in opposite directions

**Build 1, ask:** What does the reconstruction term want the clouds to do?

**Expected:** Shrink (less noise in z) and spread apart (no confusion between images).

**Build 2, ask:** What does the KL term want?

**Expected:** Move to the centre and widen to σ = 1.

**Build 3, ask:** Where does the balance land?

**Expected:** Clouds near the centre, small but not tiny, slightly overlapping.

**Build 4, ask:** Why does sampling now work?

**Expected:** The codes fill the region N(0, I) samples from, and the decoder was trained across it.

**Point here:** A sketch, not data. Section 5.6 is the real version for our 3, and Section 5.8 shows β = 0 (panel one) and β = 256 (panel two).

**Transition:** Part 5: why this loss is the right one.

## part-5: Part 5 · Why this loss: Lecture 1’s ELBO, one image at a time

**Build 1, ask:** Which wall did Lecture 1 hit?

**Expected:** The evidence p(𝒟): an integral with no formula, so the posterior was out of reach.

**Transition:** Section 5.1.

## same-problem: Same problem as Lecture 1: the same picture, new names

**Build 1, ask:** Why could Lecture 1 not compute the posterior?

**Expected:** The evidence p(𝒟): an integral over all seven weights, with no formula.

**Build 2, ask:** What plays the role of θ today, and what plays 𝒟?

**Expected:** The code z is the unknown with a prior (θ’s role); the image x is what we observe (𝒟’s role).

**Build 3, ask:** Why not fit 60,000 separate q’s, as Lecture 1 fitted one?

**Expected:** It would take an optimisation per image, and again for every new image. One pass of the encoder is instant: amortised inference.

**Point here:** Careful with θ: in Lecture 1 it was the unknown; today it names the decoder’s weights, learned as ordinary parameters. The unknown with a prior is z. Colours as in Lecture 1: prior green, likelihood orange, evidence blue, posterior teal, q purple, KL to the posterior red.

**Transition:** Lecture 1 wanted the posterior for predictions. What does a VAE want it for?

## why-post: Why does a VAE need the posterior at all?

**Build 1, ask:** What did Lecture 1 use the posterior for?

**Expected:** Predictions: the posterior predictive averages every network’s prediction, weighted by the posterior.

**Build 2, ask:** Which parts of the VAE does generating use?

**Expected:** Only the prior and the decoder.

**Build 3, ask:** Which part of the VAE takes an image and returns codes?

**Expected:** The encoder: image in, a small cloud of codes out.

**Build 4, ask:** Why is the encoder only a guess at the posterior?

**Expected:** The exact posterior needs p(x), an integral with no formula (Section 5.3). The encoder gives a Gaussian guess, as Lecture 1’s q did.

**Point here:** Lecture 1, Section 1.5 built the posterior predictive. Why training needs the posterior, exactly: the gradient of log p_θ(x) is an average over it, ∇θ log p_θ(x) = E over p(z | x) of ∇θ log p_θ(x, z). Section 5.3 tells the same thing with codes A, B and C. After training the encoder is useful on its own: it gives any image its code. The cloud is the encoder’s real output for our 3, drawn larger than its true width of about 0.01.

**Transition:** Start with the model’s story, from z.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## vae-draw: The model’s story: first a code from the prior, then an image

**Build 1, ask:** What does the prior describe?

**Expected:** Where codes come from before any image is seen: N(0, I), chosen by us.

**Build 2, ask:** Why is this code a 9?

**Expected:** Because of where z sits: the decoder learned which region of codes draws which digit.

**Build 3, ask:** Does generating need the encoder?

**Expected:** No: only the prior and the decoder.

**Point here:** We usually display the mean image: the pixel noise is independent speckle and says nothing about the digit. Colours as in Lecture 1: prior green, likelihood orange.

**Transition:** The likelihood, in numbers.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## sigma: The likelihood scores a code: how well does it draw our 3?

**Build 1, ask:** Why does code A score so much higher than the others?

**Expected:** Its drawing matches our 3 almost pixel for pixel.

**Build 2, ask:** What does a score of 252 against −360 mean?

**Expected:** Code A is e to the 612 times more likely than B to draw exactly our 3.

**Build 3, ask:** How much of the plane draws our 3 well?

**Expected:** Very little: about 0.3% of the grid comes within 100 of the best score.

**Point here:** Gaussian pixels with σ = 0.2 make the score minus the squared error over 2σ², plus a constant: squared errors 23.1, 72.1, 83.7 give 252, −360, −505. The optional slide “The likelihood, written out” has the formula. Map: an 81 × 81 grid of codes (scripts/lik.py).

**Transition:** Why would we want to run the story backwards?

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## why-back: Why run the story backwards? Images come without codes

**Build 1, ask:** If we knew each image’s code, how would we train the decoder?

**Expected:** As regression: code in, image out, squared error.

**Build 2, ask:** Why make p(x) large?

**Expected:** A good model gives its training images high probability: maximum likelihood, as for any model in this course.

**Build 3, ask:** Which codes carry the average for our 3?

**Expected:** Codes in the tiny patch that draws a 3, like code A.

**Point here:** The average is of the likelihood itself, p(x | z), not of its log. Lecture 1, Section 1.1 asked the same question of the weights: which θ explain the data?

**Transition:** Bayes’ rule answers which codes made our 3.

## vae-wall: Run the story backwards: which codes made our 3?

**Build 1, ask:** Why does the prior barely matter for these three codes?

**Expected:** The log priors differ by about 5; the log-likelihoods differ by hundreds. 784 pixels outvote 2 numbers.

**Build 2, ask:** Why is the patch so small?

**Expected:** 784 pixels with σ = 0.2 pin the code down very precisely.

**Build 3, ask:** Why can we not compute p(x) in general?

**Expected:** The integral through a network has no formula, and with 16 code numbers a grid of 100 points per number needs 100¹⁶ points.

**Point here:** log prior = −log 2π − ‖z‖²/2 for N(0, I). Colours as in Lecture 1: posterior teal, likelihood orange, prior green, evidence blue.

**Transition:** Lecture 1’s way past the wall: a guide q, as close to the posterior as we can make it.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## vi-kl: Variational inference: a guide q close to the posterior

**Build 1, ask:** Why not compute the posterior directly?

**Expected:** It needs p(x), an integral over every code with no formula (last slide).

**Build 2, ask:** When is this KL zero?

**Expected:** Only when q is exactly the posterior.

**Build 3, ask:** Which of the three pieces can we compute?

**Expected:** The log-likelihood (decode z and compare with x) and the log prior. The log evidence is the wall.

**Build 4, ask:** Where does KL(q ‖ p(z)) come from?

**Expected:** log q minus log prior, averaged over codes from q, is the KL from q to the prior.

**Build 5, ask:** If log p(x) is unknown, how can we still find the best q?

**Expected:** It is the same for every q, so minimising the other two terms minimises the KL to the posterior. For our 3 with the encoder’s q: −251.31 + 7.94 + 244.07 = 0.70.

**Point here:** Lecture 1, Section 1.5 did the same for the weights θ. Minus the first two terms is the ELBO, so the last line says log p(x) = ELBO + KL(q ‖ p(z | x)). A KL is never negative, so the ELBO is a lower bound on log p(x), and raising it over the decoder’s weights pushes p(x) up as well. Our 3 with the encoder’s q: E_q[log p(x | z)] = 251.31 (positive, because a density over 784 pixels with noise 0.2 is large), KL to the prior 7.94, log p(x) = 244.07 from the grid, so the KL to the posterior is 0.70. The optional slides “Put a guide q” and “Lecture 1’s VI on one image” score four guides and fit one by VI.

**Transition:** Fitting a guide for every image by VI would be slow. Who makes them?

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## encoder-q: The guide is a neural network: the encoder

**Build 1, ask:** Why not fit a separate guide for each image?

**Expected:** An optimisation per image, and again for every new image. One pass of the encoder is instant: amortised inference.

**Build 2, ask:** What does the encoder output for one image?

**Expected:** Two means and two log variances: q_φ(z | x) = N(μ, σ²).

**Build 3, ask:** What is variational about the VAE?

**Expected:** q comes from a simple family (diagonal Gaussians) and is pushed towards the posterior by minimising the KL, which is the same as maximising the ELBO: Lecture 1’s variational inference.

**Point here:** Kingma and Welling (2014), figure 1: solid arrow = generative model p_θ, dashed = variational approximation q_φ.

**Transition:** Put the model’s choices into the loss.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## vae-loss: Put in the model’s choices: the loss is reconstruction + KL

**Build 1, ask:** Which term needs the decoder?

**Expected:** The log-likelihood: decode z, then score x against it.

**Build 2, ask:** Where have you seen squared error come from a Gaussian likelihood?

**Expected:** Least squares in linear regression: maximum likelihood with Gaussian noise.

**Build 3, ask:** Which Lecture 1 tool gives the KL?

**Expected:** Tool ②: a formula for the KL between two Gaussians.

**Build 4, ask:** What did Part 4 guess that this derivation decides?

**Expected:** The weight between the terms, 1/(2 · 0.2²) from the pixel noise, and the reason the KL is there at all.

**Point here:** The constant: log p(x | z) carries +541.4 = −784 log(0.2 √(2π)); it changes no gradient. E_q is estimated with one draw z = μ + σ ⊙ ε per image per step (tool ①). The notebook (5.5) computes the ELBO from its definition, using torch.distributions densities instead of the formulas, and gets Part 4’s loss minus 541.4.

**Transition:** The whole thing in PyTorch.

## vae-code: The VAE in PyTorch: three changes to the autoencoder

**Build 1, ask:** What are the three changes?

**Expected:** Two outputs per code number, a random draw of z, and the KL term.

**Build 2, ask:** How many lines of the training loop change?

**Expected:** None: only the model and the loss.

**Transition:** Both terms on the real model, live.

## elbo-explorer: Your turn: choose q for our 3, and watch both terms

**Build 1, ask:** What happens to each term as σ grows?

**Expected:** Reconstruction rises as the draws turn into other digits; the KL to the prior falls until σ reaches 1.

**Build 2, ask:** Can any q push the ELBO above log p(x)?

**Expected:** No: the gap is a KL, never negative. The encoder’s q comes within about 0.7.

**Point here:** The decoder is Lecture 2’s 2-number VAE, run in the browser. Averages over ε use 8 × 8 Gauss–Hermite quadrature, so the numbers match the notebook to about 0.01. q has one σ for both code numbers here.

**Transition:** What the trained VAE does.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## vae-samples: Now sample: z ~ N(0, I), then decode

**Build 1, ask:** What changed between the first two rows?

**Expected:** Training made the codes fill N(0, I), so random codes land on digits.

**Build 2, ask:** Why are the VAE samples still a little blurry?

**Expected:** Each pixel is an independent Gaussian around a mean image; the mean of plausible strokes is soft.

**Build 3, ask:** Which digits are missing from the autoencoder row?

**Expected:** Most of them: random codes reach only the digits whose codes sit near the origin.

**Transition:** Where the codes are now.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## vae-scatter: The codes now fill N(0, I)

**Build 1, ask:** Compare with the autoencoder’s map. What changed?

**Expected:** Codes fill a round region around the origin with no large gaps; the scale is about 1, not 20.

**Build 2, ask:** Is the cloud exactly N(0, I)?

**Expected:** Not quite: a little wider (spread 1.7) and slightly off-centre, since the KL only pulls codes towards N(0, I).

**Transition:** Decode a grid, and walk between two digits.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## vae-grid: Decode a grid of codes: digits everywhere

**Build 1, ask:** Compare with the autoencoder’s grid. What is different?

**Expected:** No junk: the whole region N(0, I) samples from is used.

**Build 2, ask:** Why are the in-between images plausible now?

**Expected:** During training each image owned a small cloud of codes, so the decoder learned to draw something sensible everywhere in between.

**Transition:** One knob: the weight on the KL.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## beta-what: Put a weight on the KL: β

**Build 1, ask:** Which value of β gives back the real ELBO?

**Expected:** β = 1.

**Build 2, ask:** What do you predict at the two extremes?

**Expected:** β = 0: codes spread out like an autoencoder’s. Huge β: codes collapse onto the prior and stop carrying information.

**Transition:** Seven trained VAEs.

## beta: Seven VAEs, β from 0 to 256: try them

**Build 1, ask:** At which β do samples look best? When do reconstructions start to blur?

**Expected:** Around β = 1 to 4. By β = 64 reconstructions blur; at 256 the KL is 0.00, every code decodes to the same blob (posterior collapse).

**Point here:** KL per image: β = 0 gives 68.3, β = 1 gives 9.0, β = 256 gives 0.00. The optional slides take the two extremes apart.

**Transition:** Wrap-up.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## part-6: Part 6 · Putting it together

**Build 1, ask:** Which Lecture 1 ideas does the VAE’s loss use?

**Expected:** The ELBO, the KL between two Gaussians, and the reparameterisation trick.

**Transition:** Section 6.1.

## maths-chain: The whole lecture in five lines of maths

**Build 1, ask:** Why is the KL never negative?

**Expected:** The right code is never beaten on average: Lecture 1, 2.4.

**Build 2, ask:** Why does ② make the ELBO a lower bound?

**Expected:** The KL on the right is ≥ 0, so the ELBO is at most log p(x).

**Build 3, ask:** Which term would an autoencoder keep?

**Expected:** The first, the reconstruction term.

**Build 4, ask:** Where does the 1/2σ² come from?

**Expected:** The Gaussian density of each pixel around the decoder’s output, with σ = 0.2.

**Build 5, ask:** Which of the two terms needs sampling?

**Expected:** Only the reconstruction term, through z = μ + σ ⊙ ε. The KL has a formula.

**Transition:** The same five lines as one picture.

## maths-map: Where each term of the VAE’s loss comes from

**Build 1, ask:** Which term is the autoencoder’s loss?

**Expected:** The reconstruction term, divided by 2σ².

**Build 2, ask:** Why is the draw of z written as μ + σ ⊙ ε?

**Expected:** So the gradient reaches μ and σ: Lecture 1’s reparameterisation trick.

**Build 3, ask:** What would happen without the KL term?

**Expected:** The clouds shrink to points and spread out: an autoencoder again, which cannot generate (Part 3).

**Build 4, ask:** Why does a smaller loss help log p(x)?

**Expected:** The loss is minus the ELBO, a lower bound on log p(x): raising the bound raises what it can certify, and the gap is the KL to the posterior.

**Transition:** Wrap-up.

## summary: Autoencoder and VAE, side by side

**Build 1, ask:** Which row explains why sampling works?

**Expected:** The loss row: the KL pulls codes into N(0, I), where random draws land.

**Build 2, ask:** Which Lecture 1 ideas did the VAE use?

**Expected:** Variational inference and the ELBO, reparameterisation, and the closed-form KL between Gaussians.

**Transition:** End of the main route. Optional slides follow.

## recap-elbo: From Lecture 1: one objective we can compute (optional)

**Build 1, ask:** Which part of log p(𝒟) could we compute?

**Expected:** The ELBO. The KL to the posterior needs p(𝒟), which we cannot compute.

**Build 2, ask:** What does each ELBO term ask of q?

**Expected:** The first: put q on θ values that explain the data. The second: do not stray far from the prior.

**Build 3, ask:** What did gradient descent change in Lecture 1?

**Expected:** ψ: the means and log-widths of q, one bell per weight of the tiny network.

**Point here:** Colours follow Lecture 1’s Part 4: q purple, likelihood orange, prior green, evidence blue, the KL to the posterior red.

**Transition:** A model with a hidden code.

## vae-pgm: The VAE as a graphical model: a hidden code (optional)

**Build 1, ask:** Which circle is observed?

**Expected:** x, the image (shaded). z is never observed.

**Build 2, ask:** What does the arrow mean?

**Expected:** x is drawn given z: through the decoder, then pixel noise.

**Build 3, ask:** How many sets of decoder weights are there?

**Expected:** One, shared by all 60,000 images.

**Point here:** Graphical-model notation (Bishop, PRML chapter 8): shaded = observed, box = repeated for each example, a dot outside = a parameter. Prior green, likelihood orange, as in Lecture 1.

## cast: Same problem as Lecture 1, new names (optional)

**Build 1, ask:** Which row changed the most?

**Expected:** The approximation: one q became a q for every image, produced by a network.

**Build 2, ask:** Why not fit 60,000 separate q’s, as Lecture 1 fitted one?

**Expected:** It would take a separate optimisation for every image, and again for every new image. One encoder pass is instant.

**Point here:** Fitting one network that outputs q for any input is called amortised inference.

**Transition:** Lecture 1’s way past the wall: a simple q, as close to the posterior as possible.

## lik-formula: The likelihood, written out: Gaussian pixels (optional)

**Build 1, ask:** Where have you seen squared error = Gaussian likelihood before?

**Expected:** Linear regression: least squares is maximum likelihood with Gaussian noise.

**Build 2, ask:** Why are the three scores so far apart?

**Expected:** Every unit of squared error costs 1/2σ² = 12.5 nats, summed over 784 pixels.

**Build 3, ask:** Is σ learned here?

**Expected:** No, fixed at 0.2. It can be learned; we keep it fixed for clarity.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## evidence: The evidence p(x): average the likelihood over the prior (optional)

**Build 1, ask:** Why is the estimate so poor with few draws?

**Expected:** Nearly every draw explains the 3 badly; the few that matter are rarely drawn.

**Build 2, ask:** Where should we draw codes from instead?

**Expected:** From near the posterior: that is the job q will do.

**Point here:** Naive Monte Carlo, 30 repeats for each S; log of the average computed stably (log-sum-exp).

**Transition:** Lecture 1’s way past the wall: a guide q that knows where to look.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## var-approx: Put a guide q: a Gaussian guess of where the codes are (optional)

**Build 1, ask:** Why is the prior a poor guide?

**Expected:** It spreads over the whole plane, while the posterior is a tiny patch.

**Build 2, ask:** Which guide is closest?

**Expected:** The VI fit, then the encoder’s q: both on the patch.

**Build 3, ask:** What do the ELBO’s two terms ask of a guide?

**Expected:** Its codes should draw our 3 (first term), and it should stay near the prior N(0, I) (second term).

**Build 4, ask:** How can you tell which guide is closest without the posterior?

**Expected:** The highest ELBO has the smallest gap, and the gap is the KL to the posterior.

**Point here:** Gaps are log p(x) − ELBO, with log p(x) = 244.07 from the grid. Each ELBO is an 8 × 8 Gauss–Hermite average, as in the ELBO explorer (5.6); the notebook computes the same numbers. Why Gaussians: easy to sample (tool ①), and their KL to N(0, I) is exact (tool ②). Pyro calls q the guide. Lecture 1, Section 1.5 introduced the idea: approximate the posterior with a simple q.

**Transition:** One guide for each of 60,000 images: who makes them?

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## vae-elbo: Lecture 1’s ELBO, for one image (optional)

**Build 1, ask:** Which term is new compared with Lecture 1?

**Expected:** None: every term has a counterpart. Only the names changed.

**Build 2, ask:** Which term rewards a good reconstruction?

**Expected:** The first: the expected log-likelihood of the image.

**Build 3, ask:** What does maximising the ELBO do to θ, and to φ?

**Expected:** θ: the images become more probable under the model. φ: q moves towards the true posterior.

**Point here:** The same derivation as Lecture 1, Section 4.1, with θ → z and 𝒟 → x; Lecture 2, Section 6.3 writes it out for one image.

**Transition:** Who computes q for each image?

## elbo-read: Read the ELBO term by term: it is Part 4’s three fixes (optional)

**Build 1, ask:** Which fix does the average over q correspond to?

**Expected:** Fix 2: drawing z from the image’s cloud, q_φ(z | x).

**Build 2, ask:** Which term was the autoencoder’s whole loss?

**Expected:** log p(x | z): the reconstruction, up to the 1/2σ² weight.

**Build 3, ask:** Where did Fix 1 go?

**Expected:** Into the prior p(z) = N(0, I), inside the KL.

**Transition:** Fitting q for one image, as Lecture 1 did.

## vi3: Lecture 1’s VI on one image: fit q for our 3, press play (optional)

**Build 1, ask:** What happens to the ELBO at first? Why?

**Expected:** It wobbles and dips: q is still huge, and most codes it draws explain the 3 badly.

**Build 2, ask:** How big is the final gap?

**Expected:** About 0.02 nats: q is nearly the exact posterior.

**Point here:** Adam, step size 0.05 then 0.01, 64 reparameterised draws per step, 1,200 steps (seed 23). The ELBO plotted is the noisy estimate at each step. Left: all codes, prior circles at radius 1 and 2; middle: zoomed on the posterior.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## vae-loss-terms: Minus the ELBO is Part 4’s loss, with its weight decided (optional)

**Build 1, ask:** Which term pulls the codes towards N(0, I)?

**Expected:** The KL term.

**Build 2, ask:** Why is one draw enough?

**Expected:** Over many steps and images the noise averages out; the estimate is unbiased.

**Build 3, ask:** What does the KL do to a code with μ = 5?

**Expected:** Adds about ½ × 25 = 12.5 per number: strong pressure back towards the origin.

**Point here:** The constant is 784 log(σ√2π) = −541.4 for σ = 0.2. Shape of the loss: data fit + penalty, like ridge regression, but here the penalty comes out of the ELBO.

**Transition:** Put in the numbers for our 3.

## opt-ae-test: Did the autoencoder memorise? Training against test error (optional)

**Build 1, ask:** What would memorising look like in these numbers?

**Expected:** Very low training error and much higher test error.

**Build 2, ask:** Why is the test error a little higher?

**Expected:** The weights were tuned to the training digits; new digits fit a little less well.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## opt-linear-ae: Without the ReLUs and the sigmoid, an autoencoder rediscovers PCA (optional)

**Build 1, ask:** Why does a linear autoencoder end up like PCA?

**Expected:** PCA is the best linear encoder–decoder pair under squared error; training finds it, up to a rotation within the plane.

**Build 2, ask:** What do the ReLUs buy?

**Expected:** Curved maps: a better reconstruction from the same few numbers.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## opt-ae-interp: The autoencoder: walk in a straight line from a 1 to a 0 (optional)

**Build 1, ask:** Why might the 16-number path cross empty space?

**Expected:** The straight line between two codes need not stay where real codes are; in 16 dimensions most of the space between them is empty.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## opt-q3: Check the encoder: its q for our 3, against the true posterior (optional)

**Build 1, ask:** Which q is better, and by how much?

**Expected:** The per-image fit, by 0.68 nats.

**Build 2, ask:** Why is the encoder’s q not perfect?

**Expected:** One network must serve every image; it cannot be exactly right for each.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## opt-vae-curves: While training: reconstruction falls, the KL settles (optional)

**Build 1, ask:** What would a KL of zero mean?

**Expected:** q equals the prior for every image: the code ignores the image. That is the β = 256 collapse.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## opt-beta-zero: β = 0: is it just an autoencoder? (optional)

**Build 1, ask:** Is a VAE with β = 0 the same as an autoencoder?

**Expected:** Different by construction, but in practice it learns σ ≈ 0 and becomes one.

**Build 2, ask:** What does the KL term do to σ?

**Expected:** It stops σ shrinking: −log σ² grows as σ → 0.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## opt-beta-collapse: β = 256: every code decodes to the same blur (optional)

**Build 1, ask:** Why is KL = 0 the cheapest solution here?

**Expected:** β × KL dominates the loss; reconstruction error is worth less than any information in the code.

**Build 2, ask:** How would you spot collapse during training?

**Expected:** The KL term falls to about 0 and samples all look the same.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## next-word: Under the hood: a probability for every possible next word (optional)

**Build 1, ask:** Which word would the model pick if it always took the most likely one?

**Expected:** “wet”: 17%, but 83% of the time something else is sampled.

**Build 2, ask:** What is the model a distribution over?

**Expected:** The next word given the words so far. Chaining them gives a distribution over whole sentences.

**Point here:** Probabilities are real: SmolLM2-360M-Instruct, computed locally for Lecture 2. The point is only that generation = repeated sampling.

**Transition:** Pictures: one prompt, many images.

**Source / evidence:** SmolLM2-360M-Instruct (Hugging Face), next-token probabilities and three samples at temperature 1, computed for Lecture 2.

## img2img: Image in, image out (optional)

**Build 1, ask:** Is there one right answer for “photo of this sketch”?

**Expected:** No: colour, texture and lighting are not in the sketch.

**Build 2, ask:** So what is the model a distribution over?

**Expected:** Over images, given the input image: p(photo | sketch).

**Transition:** Sound works the same way.

**Source / evidence:** Isola et al., pix2pix (CVPR 2017); Park et al., SPADE (CVPR 2019); Zhu et al., CycleGAN (ICCV 2017). Attributed teaching excerpts; copyright with the authors.

## speech: Sound: text in, 24,000 numbers per second out (optional)

**Build 1, ask:** What exactly does the model output?

**Expected:** About 191,000 numbers: a waveform sampled 24,000 times a second.

**Build 2, ask:** Is there one right way to say this sentence?

**Expected:** No: speed, pitch, pauses and voice all vary. Another sample would sound different.

**Transition:** Before more examples: a model of what, exactly? First, the letters.

**Source / evidence:** Generated for Lecture 2 on 21 October 2026 with Gemini 3.8 Flash TTS, voice “Kore”.

## science: Beyond pictures: generative models in science (optional)

**Build 1, ask:** Why would a forecaster want 50 samples instead of one best forecast?

**Expected:** The samples show the range of possible futures: if they disagree, the forecast is uncertain.

**Build 2, ask:** Why not fill a gap in a sensor record with the average value?

**Expected:** The average is smooth and typical-looking but may never happen, and it hides the uncertainty. A sample looks like real data.

**Transition:** Collect the uses.

**Source / evidence:** Price et al., “Probabilistic weather forecasting with machine learning” (GenCast), Nature 2025; Watson et al., “De novo design of protein structure and function with RFdiffusion”, Nature 2023; Zeni et al., “A generative model for inorganic materials design” (MatterGen), Nature 2025.

## vae-worked: One step for our 3, with numbers (optional)

**Build 1, ask:** Why is z so close to μ?

**Expected:** σ is tiny (about 0.01): the code of this 3 is pinned down precisely.

**Build 2, ask:** Which term is larger, and what does that say?

**Expected:** Reconstruction, by far: fitting the pixels dominates this model.

**Build 3, ask:** What does backward() update?

**Expected:** The decoder’s θ through the reconstruction; the encoder’s φ through both μ, σ (via z) and the KL.

**Point here:** Check: L − 541.4 = −243.7, close to −ELBO = −243.4. The loss drops the constant, and one draw is noisy.

**Transition:** The whole thing in PyTorch.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## explore-vae: Your turn again: choose a code for the VAE (optional)

**Build 1, ask:** Click in the gaps between digit groups. What do you see now?

**Expected:** Plausible in-between shapes: the space between digits is filled.

**Transition:** One knob: the weight on the KL.

**Source / evidence:** Networks and numbers from Lecture 2: <code>lecture2/scripts/train.py</code> and <code>science.py</code> (MNIST, fixed seeds).

## next: Next: can we drop the pixel likelihood altogether? (optional)

**Build 1, ask:** Why does a pixel-wise Gaussian encourage soft images?

**Expected:** Squared error favours the mean of plausible images, which is blurry.

**Build 2, ask:** What else could tell a generator its images are wrong?

**Expected:** A classifier trained to tell real from generated: a learned critic.

**Transition:** End of the main route. Optional slides follow.
