-
\(\displaystyle J(\theta)=\mathbb E_{\tau\sim p_\theta}[R(\tau)]=\int_\tau p_\theta(\tau)R(\tau)\,d\tau\)The objective. The difficulty: \(\theta\) appears in the distribution being integrated against, not in the integrand \(R(\tau)\). You cannot differentiate \(R\) — it may be a black-box human preference score with no gradient at all.
-
\(\displaystyle \nabla_\theta J(\theta)=\int_\tau \nabla_\theta\big[p_\theta(\tau)\big]R(\tau)\,d\tau\)Push the gradient inside the integral (dominated convergence) and note \(R(\tau)\) is \(\theta\)-free, so it is untouched. This is why the reward need not be differentiable — a fact worth stating explicitly, since it is the whole reason RL can optimise human preference.
-
\(\displaystyle \nabla_\theta p_\theta(\tau)=p_\theta(\tau)\,\nabla_\theta\log p_\theta(\tau)\)The log-derivative trick, from \(\nabla\log f=\nabla f/f\). Trivial as identity, decisive in effect: it restores a factor of \(p_\theta(\tau)\), turning the integral back into an expectation you can sample.
-
\(\displaystyle \nabla_\theta J(\theta)=\int_\tau p_\theta(\tau)\,\nabla_\theta\log p_\theta(\tau)\,R(\tau)\,d\tau=\mathbb E_{\tau\sim p_\theta}\big[\nabla_\theta\log p_\theta(\tau)\,R(\tau)\big]\)An integral against a density is an expectation. Estimate it by drawing roll-outs from the current policy — which is exactly why the estimator is on-policy, and hence why §15 needs importance sampling.
-
\(\displaystyle \log p_\theta(\tau)=\log\rho(s_0)+\sum_t\log\pi_\theta(a_t|s_t)+\sum_t\log p(s_{t+1}|s_t,a_t)\)Expand the trajectory density and take logs, turning the product into a sum. Only the middle term carries \(\theta\).
-
\(\displaystyle \nabla_\theta\log p_\theta(\tau)=\sum_t\nabla_\theta\log\pi_\theta(a_t|s_t)\)The initial-state distribution and the transition kernel vanish. This is the step that makes policy gradient model-free — you never need to know or estimate the environment dynamics. For an LM the dynamics are string concatenation, so this is doubly free.
-
\(\displaystyle \nabla_\theta J(\theta)=\mathbb E\Big[\textstyle\sum_t\nabla_\theta\log\pi_\theta(a_t|s_t)\,R_t\Big],\qquad R_t=\sum_{k\ge0}\gamma^kr(s_{t+k},a_{t+k})\)Replace \(R(\tau)\) by the reward-to-go. Legal because rewards collected before \(t\) are independent of \(a_t\), so their contribution to the expectation is zero — and dropping them removes variance for free.
-
\(\displaystyle \mathbb E_{a\sim\pi}\big[\nabla_\theta\log\pi_\theta(a|s)\,b(s)\big]=b(s)\,\nabla_\theta\sum_a\pi_\theta(a|s)=b(s)\,\nabla_\theta 1=0\)Any state-only baseline may be subtracted without biasing the gradient. The mechanism: \(b(s)\) is constant in \(a\) so it factors out, the log-derivative trick runs in reverse to give \(\nabla\sum_a\pi_\theta\), and the probabilities sum to 1. A baseline depending on \(a\) would not factor out and would bias the estimate.
-
\(\displaystyle \nabla_\theta J(\theta)=\mathbb E\Big[\textstyle\sum_t\nabla_\theta\log\pi_\theta(a_t|s_t)\big[R_t-V^\pi(s_t)\big]\Big]\)
\(\displaystyle \approx\mathbb E\Big[\textstyle\sum_t\nabla_\theta\log\pi_\theta(a_t|s_t)\,A^{\pi_\theta}(s_t,a_t)\Big]\)Choose \(b(s_t)=V^\pi(s_t)\). Then \(\mathbb E[R_t-V^\pi(s_t)|s_t,a_t]=Q^\pi(s_t,a_t)-V^\pi(s_t)=A^\pi(s_t,a_t)\), so the bracket is a one-sample unbiased estimator of the advantage. This final line is the formula every exam cluster computes: fill in \(R_t\), subtract the given \(V^\pi(s_t)\), multiply by the given \(g_t\), sum. And \(V_\theta\) is learned by the squared-error term of the full PPO loss, which is where the baseline actually comes from in practice.
The End Term: from pixels to preferences.
Weeks 9–12 close out diffusion and then change subject entirely — from images to sequences, and from likelihood to human preference. Across four past end-term papers, three quarters of the marks sit in just two places: the arithmetic of an attention block, and the arithmetic of a policy-gradient update. This guide walks the whole road, then drills those two engines until they are muscle memory.
Exam intel — where the marks actually are
Four papers, 200 marks, and a very lopsided distribution. There is also a format split between the two terms that changes what you should practise. Read this section before anything else.
Topic frequency across the 4 end-term papers
All 200 scored marks from 2025 T3 FN + 2025 T3 AN + 2026 T1 FN + 2026 T1 AN, binned by theme. Longer bar = more marks = more of your revision time.
Attention arithmetic (78 marks) + policy-gradient arithmetic (54 marks) = 132 of 200 marks, or 66%. Both are pure computation with no conceptual trickery: a matrix product, a softmax, a weighted sum. If you can execute those two pipelines cleanly under time pressure, you have already passed. Everything else in this guide is upside.
The two paper archetypes — and why you must prepare for both
The two terms in the bank are shaped very differently. Neither is "the" format, so prepare for the union.
| 2025 T3 (both slots) | 2026 T1 (both slots) | |
|---|---|---|
| Shape | 17 standalone questions, 3–4 marks each | 22–23 questions, mostly in comprehension clusters of 2–5 sub-questions off one shared setup |
| Weeks 1–8 | None. Pure Weeks 9–12 | 13 marks every time — KL, GAN, GMM, \(\beta\)-VAE, ELBO |
| Week 9 diffusion | 9 marks — score vector, CFG, DDIM | Zero. Dropped entirely |
| RLHF / DPO / SSM | 12 marks — BT loss, KL-penalised reward, DPO reward, ZOH | Zero. Stops at PPO |
| Style of question | Broad and shallow — one idea per question, often a single formula substitution | Narrow and deep — one matrix, then five questions that each need the previous answer |
| Chief risk | A topic you skipped entirely | One arithmetic slip cascading through a whole cluster |
In the 2026 T1 papers, a five-part PPO cluster is worth 8 marks and every part reuses the same three ratios. Compute \(r_t=\pi_\theta/\pi_{\text{old}}\) for all \(t\) once, write them down in the margin, then answer the parts. Same for attention clusters: compute \(Q,K,V\) in full before reading the sub-questions. Do not recompute per sub-question — that is where the time and the sign errors go.
If you memorise nothing else, memorise these cold:
- 1.Scaled dot-product attention: \(A=\mathrm{softmax}\!\big(\tfrac{QK^\top}{\sqrt{d_k}}\big)\), output \(Z=AV\)
- 2.Causal mask: \(M_{ij}=0\) if \(j\le i\), else \(-\infty\); then \(A_m=\mathrm{softmax}\!\big(\tfrac{QK^\top}{\sqrt{d_k}}+M\big)\)
- 3.LayerNorm: \(\gamma\odot\frac{x-\mu}{\sqrt{\sigma^2+\epsilon}}+\beta\), with \(\mu,\sigma^2\) over the feature axis and \(\sigma^2\) divided by \(d_m\)
- 4.Sinusoidal PE: \(\mathrm{PE}(j,2i)=\sin\!\big(j/10000^{2i/d_m}\big)\), \(\mathrm{PE}(j,2i{+}1)=\cos(\cdot)\)
- 5.Discounted return & reward-to-go: \(R_t=\sum_{k\ge0}\gamma^k r_{t+k}\); advantage \(\hat A_t=R_t-V^\pi(s_t)\)
- 6.PPO clipped term: \(\min\big(r_tA_t,\;\mathrm{clip}(r_t,1-\epsilon,1+\epsilon)A_t\big)\)
- 7.Bradley–Terry loss: \(\mathcal L=-\log\sigma(r_w-r_l)\); RLHF reward \(R=r_\phi-\beta\log\frac{\pi_\theta}{\pi_{\text{ref}}}\)
- 8.Score from noise: \(\nabla_{x_t}\log p(x_t)=-\frac{1}{\sqrt{1-\bar\alpha_t}}\,\epsilon_t\); CFG \(\tilde\epsilon=\epsilon_u+s(\epsilon_c-\epsilon_u)\)
- Bank first (under a minute each): masked-score-vector "which entries are \(-\infty\)", importance ratio \(r_t\), "which token gets the lowest/highest attention", ZOH \(\bar A=e^{\Delta A}\), DDIM concept MCQs. These are 1–3 marks for one line of work.
- Then the pipelines: attention output vectors and PPO clusters. Worth 3–4 marks each and safe if you set up the table first.
- Leave for last: anything asking for a norm or a ratio of softmax probabilities — correct method, long arithmetic.
- Zero negative marking. Never leave a box empty. On an MSQ, select every option you can positively justify.
You will meet these if you drill the FN paper. Both are arithmetic slips by the setter, not method errors, and the AN paper does the identical computation correctly. Trust the method.
- FN Q2 (score vector). With \(\bar\alpha_t=0.49\) and \(\epsilon_\theta=[1.2,-2.4]^\top\), the stated formula gives \(-\epsilon/\sqrt{0.51}=[-1.68,\,3.36]^\top\) — not an option. The intended setup was almost certainly \(1-\bar\alpha_t=0.49\), giving \([-1.71,\,3.43]^\top\) (option 1). The key marks \([-1.2,\,2.4]^\top\), which is just \(-\epsilon\) — i.e. dividing by 1. The AN twin uses \(\bar\alpha_t=0.36\), so \(\sqrt{1-\bar\alpha_t}=0.8\) exactly, and its key is correct.
- FN Q3 (CFG). \(s=4\), \(\epsilon_u=[-0.1,0.3]^\top\), \(\epsilon_c=[0.4,-0.5]^\top\) gives \([1.9,\,-2.9]^\top\). The keyed option reads \([1.9,\,-1.9]^\top\) — second coordinate mistyped. Exam tactic: the first coordinate alone (1.9) identifies the option uniquely. Compute one coordinate, match, move on. The AN twin is arithmetically clean.
A fifth and sixth paper exist — the 2025 T2 FN/AN sittings — but their GenAI section is a different animal: 23 questions of 2–5 marks in an older format, covering the whole course including ConvTranspose shapes and VQ-VAE code. They are excluded from the tally above so it stays comparable, but their Weeks 9–12 questions are folded into this guide wherever they add a template the recent papers do not cover — top-\(k\)/top-\(p\) renormalisation, \(W_O\) parameter counts, DDIM \(\eta\), and the DDPM posterior coefficients.
The big picture: one closing act, then a new play
Weeks 9–12 are not four more topics. They are one ending (diffusion, finished properly) followed by one new beginning (sequences, and how to make them behave). Hold the shape and everything slots in.
Quiz 1 was adversarial, Quiz 2 was variational. The end term is neither for most of its marks. Weeks 9–12 split cleanly into three arcs:
| Arc | The question it answers | The one-line answer |
|---|---|---|
| Week 9 Diffusion, finished | The DDPM objective was a plain L2 regression. What is it actually regressing? And can we make sampling fast and invertible? | It regresses the added noise, which is the score function up to a fixed negative scale. Fixing \(\sigma_t=0\) in a non-Markovian family gives DDIM: deterministic, fast, invertible. |
| Week 10 AR transformers | Images were i.i.d. vectors. What if a single data point is a sequence? | Factorise by the chain rule, \(p_\theta(x)=\prod_t p_\theta(x_t|x_{<t})\), and model each factor with a causally masked attention stack. |
| Weeks 11–12 Alignment | Maximum likelihood makes the model fluent, not useful. How do we optimise for something we can only compare, not compute? | Call the LM a policy, human preference a reward, and run policy gradient (PPO). Or skip the reward model entirely and solve for the policy in closed form (DPO). |
Quiz 2 ended with "the ELBO collapses to \(\|\epsilon_t-\hat\epsilon_\theta(x_t)\|^2\)". Week 9 says that target is the score. Week 10 changes the target to the next token. Week 11 changes it to a scalar reward. Week 12 changes it to a pairwise preference. Same machine, four targets, each one further from anything you can write down analytically — which is exactly why each step needs new mathematics.
The instructor's DDIM notes use \(\alpha_t\) for the quantity the DDPM notes call \(\bar\alpha_t=\prod_{s\le t}\alpha_s\). In DDIM formulas, \(\alpha_t\) means the cumulative product, not the per-step \(1-\beta_t\). Past papers use \(\bar\alpha_t\) and \(\eta\) instead, so read the question's own symbols and do not import the notes' convention.
Interpretation 1: DDPM as regression over the added noise
The bridge from Quiz 2. Not directly examined on its own, but every Week 9 question is downstream of this rearrangement — and the score identity in the next section is derived from it.
The one rearrangement everything rests on
\(\displaystyle \Longrightarrow\quad x_0=\frac{x_t-\sqrt{1-\bar\alpha_t}\,\epsilon_t}{\sqrt{\bar\alpha_t}}\) Call this Equation (1). It says: knowing \(x_t\) and the noise that was added is the same as knowing \(x_0\). Predicting \(\epsilon_t\) and predicting \(x_0\) are the same task in different coordinates.
Substituting it into the consistency term
Quiz 2 left the ELBO as a sum of KLs, each of which reduced to \(\frac{1}{2\sigma_q^2}\|\mu_\theta-\mu_q\|_2^2\). Write both means in terms of \((x_t,\epsilon)\) using Equation (1):
\(\displaystyle \mu_\theta(x_t)=\frac{1}{\sqrt{\alpha_t}}x_t-\frac{1-\alpha_t}{\sqrt{1-\bar\alpha_t}\sqrt{\alpha_t}}\,\hat\epsilon_\theta(x_t)\) Identical in form. The only difference is \(\epsilon_t\) (the true noise) versus \(\hat\epsilon_\theta\) (the network's guess). Subtract and the \(x_t\) terms annihilate.
A regressor on the added noise. Input \((x_t,t)\); output \(\hat\epsilon_\theta(x_t)\); loss \(\|\epsilon_t-\hat\epsilon_\theta\|_2^2\). The encoder half decreases spatial dimension, the decoder half increases it back, and \(t\) enters as an embedding so one network serves all \(T\) timesteps. There is no separate model per step.
› Reveal answer
Denominator first: \(1-\bar\alpha_t=0.09\).
\(c_2=\dfrac{\sqrt{0.9578947}\times0.05}{0.09}=\dfrac{0.978721\times0.05}{0.09}=\dfrac{0.048936}{0.09}=0.5437\)
The 2-second check that beats the arithmetic: \(\mu_q\) is a convex combination of \(x_0\) and \(x_t\), so \(c_1+c_2\) must be \(\approx1\). Only the pair \((0.456,0.544)\) and the decoy \((0.5,0.5)\) satisfy that, and \(c_1=c_2\) would need \(\bar\alpha_{t-1}=\bar\alpha_t\). Answer identified without computing either fraction.
Interpretation 2: DDPM as a score predictor
The identity \(\nabla_{x_t}\log p(x_t)=-\epsilon_t/\sqrt{1-\bar\alpha_t}\) has been asked, as a one-line numeric substitution, in three of the six papers. It is also the entire foundation of guidance. Learn it as a formula and as a sign fact.
Tweedie's formula
Applying it to the DDPM forward kernel
The DDPM forward marginal is \(q(x_t|x_0)=\mathcal N\big(x_t;\;\sqrt{\bar\alpha_t}x_0,\;(1-\bar\alpha_t)I\big)\), so \(\mu_z=\sqrt{\bar\alpha_t}x_0\) and \(\Sigma_z=(1-\bar\alpha_t)I\). Tweedie gives:
The best estimate of the mean is the true mean, \(\mathbb E[\mu|x_t]=\sqrt{\bar\alpha_t}x_0\), so \(\displaystyle \sqrt{\bar\alpha_t}\,x_0=x_t+(1-\bar\alpha_t)\nabla_{x_t}\log p(x_t)\quad\Longrightarrow\quad x_0=\frac{x_t+(1-\bar\alpha_t)\nabla_{x_t}\log p(x_t)}{\sqrt{\bar\alpha_t}}\)
The true score is the added noise, negatively scaled. So a DDPM trained to regress on \(\epsilon_t\) is implicitly a score predictor: \(s_\theta(x_t)=-\hat\epsilon_\theta(x_t)/\sqrt{1-\bar\alpha_t}\). Nothing about the training changes; only the interpretation does. Substituting the score form of \(x_0\) back into \(\mu_q\) turns the consistency term into \(\|\nabla_{x_t}\log p(x_t)-s_\theta(x_t)\|_2^2\) — regression on the score.
- Losing the minus sign. The score is minus the scaled noise. Noise points away from the data manifold; the score points toward it.
- Forgetting the square root. Divide by \(\sqrt{1-\bar\alpha_t}\), not by \(1-\bar\alpha_t\). Both appear as options every single time.
- Dividing by \(\sqrt{\bar\alpha_t}\). It is the variance \(1-\bar\alpha_t\) that enters, because Tweedie brings in \(\Sigma_z\).
- \([-1.0,\;2.0]^\top\)
- \([-1.25,\;2.5]^\top\)
- \([-0.8,\;1.6]^\top\)
- \([-0.48,\;0.96]^\top\)
› Reveal answer
\(\sqrt{1-\bar\alpha_t}=\sqrt{1-0.36}=\sqrt{0.64}=0.8\), so the score is \(-[0.8,-1.6]^\top/0.8=[-1.0,\,2.0]^\top\).
Read the distractors — they are a checklist of the three errors above. \([-0.8,1.6]^\top\) is forgetting to divide at all; \([-1.25,2.5]^\top\) is dividing by \(\sqrt{\bar\alpha_t}=0.6\); \([-0.48,0.96]^\top\) is multiplying by \(1-\bar\alpha_t=0.64\) instead of dividing by its root. Every option preserves the sign flip, so the sign is free here — but the FN twin, and the 2025 T2 version below, make you supply it.
Note on the FN twin. The same question with \(\bar\alpha_t=0.49\) has a broken key — see the flag in §00. This AN version is the one to trust; the numbers work out exactly.
- \(-\frac{1}{\sqrt{1-\bar\alpha_t}}\,\epsilon\)
- \(-\epsilon\)
- \(-\frac{1}{1-\bar\alpha_t}\,\epsilon\)
- \(\frac{x_0-x_t}{1-\bar\alpha_t}\)
› Reveal answer
Direct, without Tweedie: \(\log q(x_t|x_0)=-\frac{\|x_t-\sqrt{\bar\alpha_t}x_0\|^2}{2(1-\bar\alpha_t)}+\text{const}\), so
The numerator \(x_t-\sqrt{\bar\alpha_t}x_0\) is \(\sqrt{1-\bar\alpha_t}\,\epsilon\) by definition, and one power of the root cancels. That cancellation is precisely why the answer has \(\sqrt{1-\bar\alpha_t}\) and not \(1-\bar\alpha_t\) — option 3 is the trap for anyone who stops one line early.
Guided diffusion: classifier and classifier-free
Conditional generation, derived in three lines from Bayes' rule. The CFG formula is a guaranteed 3-mark substitution — it has appeared in both 2025 T3 papers and in 2025 T2. It is also the one place a sign error is fatal.
The data is now pairs \((x_0,y)\) with \(y\) a conditioning variable — a class label, or a text embedding. The goal is to sample from \(p(x_0|y)\). Since a DDPM is a score predictor, the question becomes: what is the conditional score?
Classifier guidance — Bayes on the score
So take an unconditional DDPM, bolt on a separately pre-trained classifier \(p(y|x_t)\), and add its input-gradient to the score at every denoising step.
The classifier must accept \(x_t\) at every noise level \(t\) — including \(t\) near \(T\), where the input is nearly pure noise. Training a classifier that is accurate across all noise levels is difficult, and you must maintain a second model. That cost is the entire motivation for CFG.
Classifier-free guidance — delete the classifier
Rearrange the same identity to isolate the classifier term, then substitute it back with a knob \(s\) on it:
\(\displaystyle \Rightarrow\;\;\nabla\log p(x_t|y)\;\approx\;\nabla\log p(x_t)+s\big(\nabla\log p(x_t|y)-\nabla\log p(x_t)\big)\) The classifier has been expressed entirely in terms of two diffusion scores. No second model.
\(\displaystyle \tilde\epsilon=\epsilon_\theta(x_t|\varnothing)+s\big(\epsilon_\theta(x_t|y)-\epsilon_\theta(x_t|\varnothing)\big)\)
These are the same equation — the second is the first rewritten in \(\epsilon\)-space, where the common factor \(-1/\sqrt{1-\bar\alpha_t}\) cancels from every term. The papers use the \(\epsilon\) form for arithmetic and the score form for concept questions. Note it is an extrapolation, not an interpolation: with \(s>1\) the weight \(1-s\) on the unconditional score is negative, so \(\tilde\epsilon\) is pushed past the conditional prediction, away from the unconditional one. Larger \(s\) = more prompt adherence, less diversity.
How one network serves both terms. A single U-Net is trained with the conditioning input randomly replaced by a null token \(y=\varnothing\) some fraction of the time. At inference it is run twice per step — once with \(y\), once with \(\varnothing\) — and the two outputs are combined by the formula above before the denoising step. Cost: two forward passes per step instead of one.
- \([3.2,\;-1.7]^\top\)
- \([2.0,\;-1.7]^\top\)
- \([2.0,\;-1.2]^\top\)
- \([1.8,\;-1.8]^\top\)
› Reveal answer
Always compute the difference vector first — it is the only step where a sign can go wrong.
\(\tilde\epsilon=[0.2,\,0.1]^\top+6[0.3,\,-0.3]^\top=[0.2+1.8,\;\,0.1-1.8]^\top=[2.0,\;-1.7]^\top\)
Distractor 1, \([3.2,-1.7]^\top\), is what you get from \(\epsilon_u+s\,\epsilon_c\) in the first coordinate — forgetting to subtract \(\epsilon_u\) inside the bracket. Distractor 4 is \(s\big(\epsilon_c-\epsilon_u\big)\) alone, dropping the leading \(\epsilon_u\). Sanity check that catches both: the guided vector must lie on the ray through \(\epsilon_u\) and \(\epsilon_c\), beyond \(\epsilon_c\). Here that ray runs down-and-right at slope \(-1\) from \([0.2,0.1]^\top\); only \([2.0,-1.7]^\top\) sits on it.
- Replacing \(\epsilon_\theta\) by \(\epsilon_u+w(\epsilon_c-\epsilon_u)\) before each DDIM step
- Training a new network
- Only working with DDPM
- Using logits instead of \(\epsilon\)
› Reveal answer
This is the conceptual pay-off of the whole section, and it is worth stating as a principle: guidance and the sampler are orthogonal concerns. Guidance only changes what number you feed in as \(\hat\epsilon\); the sampler only decides what to do with \(\hat\epsilon\). So CFG drops into DDIM, DDPM, or any other sampler with no retraining — exactly as it drops into a latent diffusion model.
Latent diffusion models
Short section, cheap marks. Not yet examined numerically, but a natural concept MCQ and the one place Quiz 2's VQ-VAE reappears.
The idea in one sentence: run the DDPM on the latent space of a different encoder–decoder model instead of on pixels.
Given data \(x_0\in\mathbb R^d\), first learn a latent representation \(z_0\in\mathbb R^K\) with \(K\ll d\) using an encoder–decoder (the course's example is a VQ-VAE, trainable on \(x_0\) or on any similar dataset). Freeze it, project the whole dataset to \(z\)-space, and build the DDPM there. At inference: sample \(z_{\text{novel}}\) by reverse diffusion in the latent space, then decode once.
- 1.Cost. Every one of the \(T\) reverse steps runs on a \(K\)-dimensional tensor instead of a \(d\)-dimensional one. With \(K\ll d\) that is the difference between a research cluster and a laptop.
- 2.Division of labour. The autoencoder handles perceptual detail (texture, sharpness); the diffusion model handles semantic structure (what is in the image). Neither has to do both.
- 3.Nothing else changes. The forward process, the ELBO, the \(\epsilon\)-regression loss, guidance, DDIM — all identical, just with \(z\) in place of \(x\). Only the space moved. This is the exam-friendly framing.
DDIM — deterministic, fast, invertible
The most-repeated Week 9 question in the bank. It is almost always conceptual, and the answer is almost always the same word: deterministic. But understand why, because the "same training, different inference" fact is the deeper examinable point.
The two problems with DDPM
- Slow sampling. \(T\approx1000\) sequential network evaluations per sample. No parallelism is possible — step \(t-1\) needs step \(t\).
- Non-unique invertibility. The forward process is stochastic: \(x_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\epsilon_t\) with a fresh \(\epsilon_t\) each run. Running it twice on the same \(x_0\) gives different \(x_T\). So there is no single latent code for a given image — and therefore no deterministic posterior inference, no clean latent-space editing.
The construction: a family of non-Markovian inference distributions
Instead of one noising chain, define a whole family indexed by a vector \(\sigma\in\mathbb R_{\ge0}^T\):
\(\displaystyle q_\sigma(x_{t-1}|x_t,x_0)=\mathcal N\!\left(\sqrt{\bar\alpha_{t-1}}\,x_0+\sqrt{1-\bar\alpha_{t-1}-\sigma_t^2}\cdot\frac{x_t-\sqrt{\bar\alpha_t}x_0}{\sqrt{1-\bar\alpha_t}},\;\;\sigma_t^2 I\right)\) Note the second term: \(\frac{x_t-\sqrt{\bar\alpha_t}x_0}{\sqrt{1-\bar\alpha_t}}\) is the noise \(\epsilon_t\). So the mean is "a bit of \(x_0\) plus a bit of the noise already present", and \(\sigma_t^2\) controls how much fresh randomness is injected. The corresponding forward process is not Markovian: \(x_t\) depends on \(x_0\) even given \(x_{t-1}\).
Every member of this family is constructed to have the same marginal as DDPM:
The ELBO in DDPM/DDIM depends only on \(q(x_t|x_0)\). So every member of the family has the same ELBO (up to an additive constant), the same optimum, and the same trained network. Hence:
Training the one regression network in DDPM implicitly trains every non-Markovian model in the family. There is no difference in training between DDPM and DDIM — the difference is entirely in inference. You train once and then choose your sampler at test time.
The sampler, and the two special values of \(\sigma_t\)
| Choice of \(\sigma_t\) | What you get | Character |
|---|---|---|
| \(\sigma_t=\sqrt{\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}}\cdot\sqrt{\frac{1-\bar\alpha_t}{\bar\alpha_{t-1}}}\) the DDPM posterior std, often written \(\tilde\beta_t\) | DDPM exactly | Stochastic, Markovian |
| \(\sigma_t=0\) for all \(t\) | DDIM | Deterministic, non-Markovian |
| \(\sigma_t=\eta\,\tilde\beta_t\), \(\eta\in[0,1]\) | The interpolation used in practice; injected variance is \(\sigma_\eta^2=\eta^2\tilde\beta_t\) | \(\eta=0\) DDIM, \(\eta=1\) DDPM |
Careful here, because the exam key is loose about it. The \(\sigma_t=0\) update never mentions \(t-1\) as "the previous integer" — it works for any earlier index. Because all members of the family share the marginals, you may run the sampler on a sub-sequence of timesteps (say 50 of the 1000) and still land in the right distribution. That is the source of the 20× speed-up. Determinism is what permits the skipping (no accumulated injected noise to account for) and is the answer the papers want; step-skipping is the mechanism.
- They remove the neural network entirely.
- They require more noise steps.
- They require additional forward passes.
- The sampling process is deterministic when \(\sigma_t=0\).
› Reveal answer
Verbatim in both 2025 T3 papers, options merely reordered. Bank it. The three distractors are all false of DDIM: the network is unchanged (option 1); DDIM uses fewer steps (option 2); and it needs the same one forward pass per step (option 3 — that is CFG, which needs two).
- Deterministic and non-Markovian but matches \(q(x_t|x_0)\) marginals
- Stochastic and Markovian
- Identical to DDPM (\(\eta=1\))
- Invalid
› Reveal answer
This option is a three-fact summary of the entire section, and it is the best single sentence to memorise about DDIM:
- Deterministic — because \(\sigma_t=0\) kills the \(\sigma_t z\) term.
- Non-Markovian — because \(q_\sigma(x_{t-1}|x_t,x_0)\) conditions on \(x_0\) as well as \(x_t\).
- Matches the marginals — which is why the DDPM-trained network is still the correct network, and why you may skip steps.
Option 3 inverts the convention and is the one to watch: \(\eta=1\) is DDPM, \(\eta=0\) is DDIM.
- \(\sigma_\eta^2=\eta^2\tilde\beta_t\)
- \(\sigma_\eta^2=\eta\,\beta_t\)
- \(\sigma_\eta^2=(1-\eta)\tilde\beta_t\)
- \(\sigma_\eta^2=\beta_t^2\)
› Reveal answer
Get here by checking the two endpoints, not by recalling the formula. The definition is \(\sigma_t=\eta\sqrt{\tilde\beta_t}\), so the variance picks up \(\eta^2\). Test it: \(\eta=0\) must give variance 0 (DDIM) and \(\eta=1\) must give \(\tilde\beta_t\), the DDPM posterior variance. Option 1 passes both. Option 3 fails at \(\eta=0\) (gives full DDPM noise — backwards). Options 2 and 4 use \(\beta_t\), the forward step variance, not the posterior variance \(\tilde\beta_t=\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\beta_t\).
Autoregressive models: the factorisation
Everything in Weeks 10–12 hangs off one product. Two minutes here makes the next six sections make sense.
The setup changes: a single data point is now a sequence, \(x=\{x_1,x_2,\dots,x_T\}\sim p_x\) — a sentence, or a multivariate time series. The goal is unchanged (estimate \(p_x\), learn to sample from it) and so is the route: parameterise with \(p_\theta\) and minimise a divergence, which as always reduces to MLE:
This is just the chain rule of probability — it is exact, not an approximation, and involves no independence assumption. Its power is that it converts one intractable joint density over a whole sequence into \(T\) ordinary classification problems over the vocabulary \(V\). Contrast with Quiz 2, where the latent had to be integrated out: here there is no latent and no ELBO, so the likelihood is exact and directly maximisable. That is the single biggest structural difference between this half of the course and the last.
The four generations of AR model
| Model | How \(p_\theta(x_t|x_{<t})\) is computed | Fatal limitation |
|---|---|---|
| Classical AR\((p)\) | \(x_t=\sum_{i=1}^{p}a_i x_{t-i}+\epsilon_i\), \(\epsilon_i\sim\mathcal N(0,\sigma^2)\); the \(a_i\) are learnable | Linear, and a fixed window of \(p\). Cannot model the complex relations in language. |
| Neural AR | \(p_\theta(x_t|x_{<t})=\text{MLP or CNN}(x_{<t})\) | Non-linear, but the input is a fixed-length window — an MLP has a fixed input size. |
| RNN / LSTM / GRU | \(h_t=f_\theta(h_{t-1},x_{t-1})\), \(x_t=g_\phi(h_t)\), with \(f_\theta,g_\phi\) shared across all \(t\) | Vanishing gradients: gradient magnitude decays with sequence length, and a fixed-size \(h_t\) cannot compress unbounded history. |
| Transformer | Attention over all previous tokens at once, with causal masking | Cost is \(O(T^2)\) in sequence length — which is the opening that state-space models (§18) exploit. |
The reason parameter sharing matters: because \(f_\theta\) is the same function at every step, an RNN imposes no constraint on sequence length. That property is what attention has to preserve — and it does, which is why \(W^Q,W^K,W^V\) are shared across positions too.
- State = token prefix, action = next token
- State = next token, action = prefix
- State = vocabulary, action = logits
- Impossible
› Reveal answer
Worth meeting now rather than in §14, because it shows the whole back half of the course in one line. The AR factorisation \(p_\theta(x_t|x_{<t})\) already is a policy \(\pi_\theta(a_t|s_t)\): the conditioning context \(x_{<t}\) is the state, the emitted token \(x_t\) is the action. No reinterpretation of the model is needed — only a change of what you optimise. The AR factorisation is the reason RLHF is possible at all.
Attention — the four steps, and how to execute them fast
Every end-term paper contains at least one attention computation, and the 2026 T1 papers build 6–9 mark clusters on a single \(3\times3\) matrix. This is the highest marks-per-minute topic in the course. Drill the procedure, not the formula.
Setup: three projections of the same sequence
Stack the sequence as \(X\in\mathbb R^{T\times d_m}\), one row per token. Project it three ways:
\(W^Q,W^K\in\mathbb R^{d_m\times d_k},\qquad W^V\in\mathbb R^{d_m\times d_v}\)
\(Q,K\in\mathbb R^{T\times d_k},\qquad V\in\mathbb R^{T\times d_v}\) Row \(i\) of each matrix is that token's query / key / value. Rows are tokens, columns are features — get this the wrong way round and every subsequent number is wrong. In a decoder-only model \(d_k=d_v\); in an encoder–decoder they may differ.
Self- versus cross-attention: if \(Q,K,V\) all come from the same sequence it is self-attention. If \(Q\) comes from one sequence and \(K,V\) from another it is cross-attention — which is how a decoder reads the encoder's output.
The four steps
\(\textbf{2. Scale: }\; \hat s=\dfrac{q^\top K^\top}{\sqrt{d_k}}\)
\(\textbf{3. Normalise: }\; \alpha_i=\dfrac{\exp\!\big(q^\top k_i/\sqrt{d_k}\big)}{\sum_{j=1}^{T}\exp\!\big(q^\top k_j/\sqrt{d_k}\big)},\qquad \alpha_i\in[0,1],\;\textstyle\sum_i\alpha_i=1\)
\(\textbf{4. Combine: }\;\mathrm{Attention}(q,K,V)=\sum_{i=1}^{T}\alpha_i v_i\) All queries at once: \(A=\mathrm{softmax}\!\big(\frac{QK^\top}{\sqrt{d_k}}\big)\in\mathbb R^{T\times T}\) and \(Z=AV\in\mathbb R^{T\times d_v}\). The softmax is row-wise — each row of \(A\) sums to 1, because each row is one query's distribution over the keys.
A convex combination of the value vectors. That single fact is worth several marks a year, because it constrains the answer: the output of an attention head must lie inside the convex hull of the rows of \(V\). If your computed output is bigger than every entry of \(V\), you have made an arithmetic error — and you can often eliminate two of four options on sight.
With entries of \(q,k\) roughly independent and unit-variance, \(q^\top k\) is a sum of \(d_k\) such products, so its variance grows like \(d_k\) and its scale like \(\sqrt{d_k}\). Feeding large-magnitude logits into a softmax saturates it — one weight goes to 1, the rest to 0, and the gradient vanishes. Dividing by \(\sqrt{d_k}\) holds the logits at \(O(1)\) regardless of head width.
› Reveal answer
Step 0 — do this before reading the sub-questions. Compute all three projections in full. Each is a \(3\times3\) times \(3\times2\) product; nine dot products of length 3, about ninety seconds.
(a) \(q_2=(3,1)\). Raw scores against the three keys: \(3(3)+1(1)=10\), \(3(1)+1(2)=5\), \(3(2)+1(3)=9\). Divide each by \(\sqrt2\):
\(\|\hat s_2\|_2=\dfrac{1}{\sqrt2}\sqrt{10^2+5^2+9^2}=\dfrac{\sqrt{206}}{\sqrt2}=\sqrt{103}=10.1489\) Pull the \(1/\sqrt2\) out of the norm and you never touch a decimal: \(\sqrt{206/2}=\sqrt{103}\). That is the whole question in one line.
(b) Softmax the scaled scores. Subtract the max (7.0711) first for stability, then exponentiate:
\(\alpha=[0.6569,\;0.0191,\;0.3239]\)
\(Z_2=0.6569\,(2,1)+0.0191\,(3,2)+0.3239\,(1,3)=(1.6952,\;1.6670)\)
Two ways to shortcut option-matching here. First, the output must be a convex combination of \((2,1),(3,2),(1,3)\), so both coordinates must lie in \([1,3]\) — that alone kills the options \([0.37,0.30,0.33]\) and \([0.66,0.02,0.32]\), which are attention weights mistaken for the output (a deliberate trap, and note they even have three components rather than two). Second, of the two survivors \([1.66,1.85]\) and \([1.70,1.67]\): token 1 gets two-thirds of the weight and its value is \((2,1)\), which has first coordinate greater than second — so the output should too. Only \([1.70,1.67]\) does.
› Reveal answer
The given exponentials are a gift — they tell you the answer's shape before you compute anything. Only two distinct values are supplied for three scores, so two of the three scaled scores must be equal. Expect a tie.
(a) \(q_1=(1,2)\). Raw scores: \(q_1^\top k_1=1+6=7\), \(q_1^\top k_2=1+2=3\), \(q_1^\top k_3=3+4=7\). The lowest is 3 → token 2. Note the tie at 7 the given exponentials predicted. This sub-part needs no scaling and no softmax at all — softmax is monotone, so ranking is unaffected. Two marks for three dot products.
(b) Scaled: \(7/\sqrt2=4.9497\), \(3/\sqrt2=2.1213\), \(4.9497\) — matching the supplied \(e^{4.950}\) and \(e^{2.121}\) exactly.
\(\alpha_3=\dfrac{141.175}{290.689}=0.4857,\qquad \alpha=[0.4857,\;0.0287,\;0.4857]\) Because tokens 1 and 3 tie, \(\alpha_1=\alpha_3\) — each is just under \(\tfrac12\). You could almost write 0.486 down by inspection.
(c) \(Z_1=0.4857(3,2)+0.0287(1,2)+0.4857(2,1)=(2.4570,\;1.5143)\), and \(2.4570+1.5143=3.9713\approx\mathbf{3.97}\).
The 10-second route to (c). The question asks for a sum of coordinates, so sum first and weight second. Row sums of \(V\) are \(5,3,3\), hence \(0.4857(5)+0.0287(3)+0.4857(3)=2.4285+0.0861+1.4571=3.9717\). One weighted sum instead of two — and it dodges the vector arithmetic entirely.
› Reveal answer
Do not compute the matrix. Position \((1,2)\) of \(QK^\top/\sqrt{d_k}\) is one dot product: row 1 of \(Q\) with row 2 of \(K\), divided by \(\sqrt4=2\). Everything else on the page is a distraction.
\(\text{AN: }(2,1,0,1)\cdot(0,1,1,0)=0+1+0+0=1,\qquad 1/2=0.5\)
Note that \(Q\) and \(K\) are given directly here — no \(X\) and no \(W\) matrices to multiply, unlike the 2026 T1 clusters. Read which the paper gives you; projecting a matrix that was already projected is a costly and easy mistake. The one real trap is transposing: \((QK^\top)_{ij}=q_i\cdot k_j\), so the second index selects the key.
Causal masking
The one modification that turns attention into an autoregressive model. Cheap marks: some sub-questions need only "which entries are \(-\infty\)", worth 1–2 marks for one line.
The AR factorisation demands that \(x_t\) depend only on \(x_1..x_{t-1}\). But plain attention lets every token see every other token, including the future — which would let the model read the answer off its own input. So the scores are modified before the softmax:
The condition is \(j\le i\), so a token does attend to itself. (The instructor's notes write \(j<i\) at one point, but every past paper states \(j\le i\) explicitly — use the paper's own definition, and it always includes the diagonal.) To answer any masking question:
- 1.Take row \(i\). The query index is the row. Not the column.
- 2.Keep the first \(i\) entries, set the rest to \(-\infty\). Nothing else changes — the surviving values keep their original numbers.
- 3.Softmax over the survivors only. The denominator is a sum of \(i\) terms, not \(T\). This is the step people get wrong.
- \([1,\;0,\;3,\;-\infty]\)
- \([1,\;0,\;3,\;2]\)
- \([-\infty,\;0,\;3,\;2]\)
- \([1,\;-\infty,\;3,\;2]\)
› Reveal answer
(a) Row 3 of \(S\) is \([1,0,3,2]\). Query 3 may see positions 1, 2, 3 and not 4, so only the last entry becomes \(-\infty\): \([1,0,3,-\infty]\). One mark for reading one row.
The zero is the trap. Option 3 masks position 1 because its score is... no, because its score looks small; option 4 masks position 2 because its score is literally \(0\). Neither is a mask. A score of 0 is a perfectly ordinary score — it contributes \(e^0=1\) to the softmax, which is why the paper bothers to supply \(e^0=1\). Masking depends on position only, never on value.
(b) Token 4 is the last query, so nothing is masked — row 4 is \([2,1,0,4]\) in full.
\(P(1)+P(2)=\dfrac{7.389+2.718}{65.705}=\dfrac{10.107}{65.705}=0.15382\)
"Jointly" means add the numerators, not the probabilities — same thing here, but adding numerators over one shared denominator is faster and avoids two roundings. Sanity check: \(e^4=54.6\) is 83% of the mass on its own, so the answer for the other three positions together must be small. 0.154 for two of them is plausible; anything above 0.5 would not be.
› Reveal answer
(a) Exactly 0. Position 4 is in the future for query 3, so it is masked, and \(e^{-\infty}=0\). One mark, no arithmetic — and the fastest mark in the whole paper. Do not be tempted to compute a softmax.
(b) Row 4 is \([0,1,2,5]\), fully visible, and softmax is monotone: the largest score always wins the largest weight. Largest is 5 at position 4. Two marks, no arithmetic.
(c) Two different rows with two different denominators — that is the entire difficulty, and where the 3 marks are.
\(\text{Row 2 masked}=[2,3,-\infty,-\infty]:\quad p(2\to1)=\dfrac{e^2}{e^2+e^3}=\dfrac{7.389}{27.474}=0.26894\)
\(\text{ratio}=\dfrac{0.84381}{0.26894}=3.1375\)
The mistake this question is built to catch is normalising both rows over all four positions. Row 2 sees only two positions, so its denominator has two terms — and \(e^5=148.413\) is supplied precisely so that anyone dividing by a whole-matrix sum gets a plausible-looking wrong number. Use it only where it belongs: nowhere in this sub-part.
› Reveal answer
Second row is \([1.0,\,2.0,\,1.0]\); query 2 sees positions 1 and 2, so the third entry is masked: \([1.0,\,2.0,\,-\infty]\).
Or skip the exponentials entirely. With only two survivors, softmax is the logistic function of the difference: \(P=\sigma(2.0-1.0)=\sigma(1)=1/(1+e^{-1})=0.731\). Worth remembering — a two-way softmax is always a sigmoid of the gap, which turns this into one keystroke.
The trap is including the masked third column: \(7.389/12.825=0.576\), which is why the accepted range (0.71–0.75) excludes it. The official key is typo'd as "0.71 to 075" — read it as 0.75.
Multi-head attention & parameter counting
Parameter-count questions appear in five of the six papers. They are pure bookkeeping — and every one of them turns on the same single insight about how \(d_k\) is chosen.
The construction
\(Q_j=XW_j^Q,\quad K_j=XW_j^K,\quad V_j=XW_j^V,\qquad Z_j=\mathrm{Attention}(Q_j,K_j,V_j)\in\mathbb R^{T\times d_v}\)
\(Z_c=[Z_1;Z_2;\dots;Z_h]\in\mathbb R^{T\times(d_v h)}=\mathbb R^{T\times d_m}\)
\(\mathrm{MHA}(X)=Z_c\,W^C\in\mathbb R^{T\times d_m},\qquad W^C\in\mathbb R^{(d_v h)\times d_m}=\mathbb R^{d_m\times d_m}\) Every head computes attention independently on its own \(d_k\)-wide slice; the results are concatenated (not summed) and mixed by one final projection \(W^C\) (also written \(W^O\)). Net effect: \(X\in\mathbb R^{T\times d_m}\to Z\in\mathbb R^{T\times d_m}\). Shape in equals shape out — which is what lets you stack blocks and add residuals.
Because \(d_k=d_m/h\), each head's \(W_j^Q\) is \(d_m\times\frac{d_m}{h}\), so it holds \(d_m^2/h\) weights. There are \(h\) of them:
Multi-head and single-head attention contain exactly the same number of learnable parameters. The heads are a partition of the same budget, not an addition to it. You get several independent attention patterns for free, each in a narrower subspace — the trade is representational width per head against number of heads.
- 1.Which matrices are in scope? "Query, key and value projections" means three. "All four projection matrices" includes \(W^O\). Read the wording — the difference is a factor of 4/3.
- 2.Biases or not? A \(D\to D\) linear layer with bias has \(D^2+D\) parameters. "Weights only" drops the \(+D\). Papers ask both ways in the same term.
- 3.Parameters or activations? Parameters do not depend on \(T\) or batch size; the output tensor does. If the question says "floating-point elements in the output tensor", you want \(B\times L\times d_m\), not a weight count.
- \(3D^2\)
- \(3D^2+3D\)
- \(D^2+D\)
- \(6D^2\)
› Reveal answer
(a) One \(\mathbb R^D\to\mathbb R^D\) layer has a \(D\times D\) weight matrix and a length-\(D\) bias: \(D^2+D\). Three such layers: \(3(D^2+D)=3D^2+3D\). Option 1 is the weights-only answer — correct arithmetic, wrong question. The phrase "including both weights and biases" is doing real work here; it is there to separate options 1 and 2.
(b) \(A\in\mathbb R^{N\times N}\) because every one of the \(N\) queries scores every one of the \(N\) keys. So \(N^2=100^2=\mathbf{10{,}000}\).
\(D=16\) is a red herring, and a well-built one. The head dimension is summed away by the dot product: \(q_i^\top k_j\) is a scalar whatever \(D\) is. Anyone who multiplies by 16 gets 160,000. Remember the shape chain — \(A\) is \(T\times T\), never \(T\times d_k\) — and this is a two-mark gift. It is also the origin of the transformer's \(O(T^2)\) cost, which is the whole motivation for §18.
- Q, K, V projection layers in multi-head and single-head attention contain an equal number of total learnable parameters.
- Q, K, V projection layers in multi-head attention contain more learnable parameters than in single-head attention.
- Q, K, V projection layers in multi-head attention contain fewer learnable parameters than in single-head attention.
› Reveal answer
"Evenly split across heads" is the phrase that decides it: \(d_k=D/h\), so the \(h\) per-head matrices of size \(D\times\frac{D}{h}\) tile exactly the same \(D\times D\) budget as one single-head matrix. Concatenating \(h\) slices of width \(D/h\) reconstructs width \(D\).
The intuition worth carrying: multi-head attention buys diversity of attention patterns, not capacity. If instead each head kept the full width \(d_k=D\) (not the standard construction) the count really would be \(h\) times larger — which is what option 2 is fishing for.
› Reveal answer
This asks about an activation, not a parameter count — so \(B\) and \(L\) matter and \(h\) does not.
The reasoning that makes \(h=8\) irrelevant is the shape-preservation property: concatenating 8 heads of width \(512/8=64\) gives width 512 again, and \(W^O\) maps \(512\to512\). The block's output is always \(B\times L\times d_{\text{model}}\) regardless of how it was internally partitioned — which is precisely why the residual connection \(x+\mathrm{sublayer}(x)\) is well-defined. \(h=8\) is there to tempt you into \(\times8\) or \(\div8\).
› Reveal answer
(a) \(W_O\) maps the concatenation back to model width. Concatenated width is \(h\,d_v=12\times64=768=d_{\text{model}}\), so \(W_O\in\mathbb R^{768\times768}\). The distractor \(768\times64\) is the size of one head's projection; \(64\times64\) and \(12\times64\) are dimensional nonsense. Check the consistency of the given numbers — \(h\,d_k=d_{\text{model}}\) holds here, confirming the standard even split.
(b) \(4\times512^2=4\times262{,}144=1{,}048{,}576\) (which is \(2^{20}\), i.e. exactly 1M — a nice self-check). Note how the option list maps to misreadings: \(262{,}144\) counts one matrix, \(786{,}432\) counts three (forgetting \(W_O\)), \(524{,}288\) counts two. The whole question is "how many matrices did they ask about". Read the stem twice, then multiply.
The transformer block: FFN, residuals, LayerNorm, positional encoding
Attention is linear in \(V\) and blind to order. These four components fix both problems. LayerNorm arithmetic and positional encodings are each worth 4–7 marks a paper.
The feed-forward layer — where the non-linearity lives
Residual connections and LayerNorm
\(\displaystyle \mu=\frac{1}{d_m}\sum_{k=1}^{d_m}x_k,\qquad \sigma^2=\frac{1}{d_m}\sum_{k=1}^{d_m}(x_k-\mu)^2,\qquad \mathrm{LN}(x)=\gamma\odot\frac{x-\mu}{\sqrt{\sigma^2+\epsilon}}+\beta\) \(\gamma\) and \(\beta\) are learnable, which is what lets the network undo the normalisation if that is useful. Notes give \(\epsilon=0.01\) or \(0.001\); papers state their own value (often \(0\)) — always use the paper's.
- Divide by \(d_m\), not \(d_m-1\). LayerNorm uses the biased (population) variance. Every past-paper key confirms this: in 2026 T1 FN, \(u=[4,6,5,3]\) gives \(\sigma^2=5/4=1.25\), not \(5/3\).
- Normalise across features, per token. Each token's \(d_m\)-vector gets its own \(\mu,\sigma^2\). This is what distinguishes it from BatchNorm, and it is why LayerNorm is independent of batch size and sequence length.
- \(\gamma\) multiplies element-wise, after normalising. Order matters: normalise, then scale by \(\gamma_i\), then add \(\beta_i\). A vector \(\gamma\) means each coordinate is scaled differently.
- Mean \(=4.0\), Variance \(=1.25\)
- Mean \(=4.5\), Variance \(=1.25\)
- Mean \(=4.5\), Variance \(=1.50\)
- Mean \(=4.0\), Variance \(=1.50\)
› Reveal answer
Step 1 — the projection. \(z_c\) is a row vector, so \(z_cW^C\) means "dot \(z_c\) with each column of \(W^C\)":
\(\text{col 2: }2(0)+1(1)+1(0)+3(1)=4\)
\(\text{col 3: }2(1)+1(0)+1(0)+3(1)=5\)
\(\text{col 4: }2(0)+1(1)+1(1)+3(0)=2\)
\(z_cW^C=[3,4,5,2]\)
Step 2 — the residual. \(u=[1,2,0,1]+[3,4,5,2]=[4,6,5,3]\). Forgetting this addition is the biggest single risk in the cluster, and it corrupts both sub-answers.
\(\sigma^2=\dfrac{(-0.5)^2+(1.5)^2+(0.5)^2+(-1.5)^2}{4}=\dfrac{0.25+2.25+0.25+2.25}{4}\)
\(\phantom{\sigma^2}=\dfrac{5}{4}=1.25\)
Step 3 — the requested coordinate only. \(\sqrt{1.25}=1.11803\):
Notice the option design in (a): the four choices are the \(2\times2\) grid of "did you add the residual" (mean 4.5 vs 4.0) against "did you use the biased variance" (1.25 vs 1.50 — and \(5/3=1.67\) would be the \(n-1\) answer, with 1.50 as a nearby decoy). The option list is the pitfall list. And do not normalise all four coordinates in (b) — you need one.
› Reveal answer
(a) \(\mu=0\), so \(\sigma^2=\frac{4+0+4+0}{4}=2\) and \(\sigma=\sqrt2\). Divide through: \((2/\sqrt2,\,0,\,-2/\sqrt2,\,0)=(1.414,0,-1.414,0)\). Symmetry shortcut: the input is antisymmetric so \(\mu=0\) for free, and the zeros must stay zero — which alone eliminates every distractor.
(b) Deviations are \((-1,0,1)\); divide by 0.8165 to get \((-1.2247,\,0,\,1.2247)\); then scale by \(\gamma\):
The decoy \((-0.612,0,1.225)\) applies \(\gamma\) in reverse order — a pure sequencing error. Note the middle coordinate is 0 whatever \(\gamma_2\) is, because \(x_2\) equals the mean.
(c) Two marks of reading comprehension. \(f\) is the identity so \(f(\mathrm{LN}(x))=\mathrm{LN}(x)=(1,-1)\), and \(y=(2,0)+(1,-1)=(3,-1)\). The point being tested is the order of operations: here the normalisation is applied inside the sublayer path (pre-norm), so the residual adds the original \(x\), not the normalised one. Answer \((2,0)\) if you forget the sublayer, or \((1,-1)\) if you forget the residual — both are on the option list.
- It remains the same \((1\times)\).
- It increases by a factor of \(1.1^{10}\).
- It doubles \((2\times)\).
- It increases 10-fold.
› Reveal answer
Under the stated independence approximation each layer multiplies the variance by \(1.1\):
\(\Rightarrow\;\mathrm{Var}(x_{10})\approx1.1^{10}\,\mathrm{Var}(x_0)=2.594\,\mathrm{Var}(x_0)\)
Option 2, "a factor of \(1.1^{10}\)", is exactly right; option 3, "it doubles", is the nearest numerical statement (\(2.594\approx2\) rather than \(1\) or \(10\)). Both papers key option 3, so the examiner wants the magnitude, cued by the words "approximately how much". Rule of thumb for this paper-setter: when an exact symbolic option and a rounded numeric option both appear, and the stem says "approximately", pick the number. Should this reappear, go with "doubles".
The physics worth taking away: residual streams make variance grow geometrically with depth. That is exactly what the LayerNorm after each block exists to prevent — it rescales the stream back to zero mean and unit variance, so a 96-layer model does not blow up by \(1.1^{96}\approx11{,}000\times\).
Positional encoding — because attention is permutation-equivariant
Attention computes a weighted sum over a set. Shuffle the input rows and the output rows shuffle identically — the mechanism has no notion of order. So a fixed positional vector is added to each token embedding before the first block:
\(\mathrm{PE}\in\mathbb R^{T\times d_m},\qquad \tilde x_j=x_j+\mathrm{PE}(j)\in\mathbb R^{d_m}\) Even indices sin, odd indices cos, sharing a wavelength in pairs. Added, not concatenated — so the dimension is unchanged. The encoding is fixed, not learned.
- \([2.14,\;0.01,\;0.03,\;3.00]\)
- \([2.14,\;1.99,\;0.03,\;3.00]\)
- \([2.14,\;0.01,\;0.30,\;2.99]\)
- \([2.00,\;0.01,\;0.03,\;3.00]\)
› Reveal answer
Build the PE vector coordinate by coordinate. With \(d_m=4\) the four slots pair up as \((2i,2i{+}1)\) for \(i=0,1\), and the two supplied argument values (3 and 0.03) tell you the two wavelengths before you compute anything:
| Slot | Formula | Argument \(j/10000^{2i/d_m}\) | Value |
|---|---|---|---|
| 0 | \(\sin\), \(i=0\) | \(3/10000^{0}=3\) | \(0.141\) |
| 1 | \(\cos\), \(i=0\) | \(3\) | \(-0.990\) |
| 2 | \(\sin\), \(i=1\) | \(3/10000^{2/4}=3/100=0.03\) | \(0.03\) |
| 3 | \(\cos\), \(i=1\) | \(0.03\) | \(0.9996\) |
Then add element-wise: \([2+0.141,\;1-0.990,\;0+0.03,\;2+0.9996]=[2.141,\;0.010,\;0.03,\;2.9996]\).
The whole question turns on one coordinate. Slot 1 uses \(\cos3=-0.990\), which nearly cancels \(x_1=1\) to give \(0.01\). Option 2 has \(1.99\) — the sign of the cosine flipped. Option 3 misreads the exponent (\(10000^{2i/d_m}=100\), so \(0.03\) not \(0.30\)); option 4 forgets slot 0 entirely. Compute coordinate 1 first and you are done in ten seconds.
(b) PE is added, so \(\tilde x\in\mathbb R^{d_m}\) just like \(x\) — dimensionality preserved (killing "increases the dimensionality", which would describe concatenation). It does not "replace" semantic information — the sum retains both, and downstream linear layers can separate them because the two carry different structure. Nor does it normalise anything.
- Sinusoidal positional encodings are learned parameters updated during training.
- Positional encodings let the model incorporate order information that attention alone cannot provide.
- The sinusoidal frequencies grow geometrically with the dimension index \(i\).
- The scheme lets relative positions be represented through linear functions of the embeddings.
- Adding PE to token embeddings guarantees each position has a unique representation.
› Reveal answer
The FN paper offered options 1–4 and the AN paper offered 1, 2, 3 and 5; in both, the "learned parameters" option is the only false one. That is the pattern to remember: sinusoidal PE is a fixed, closed-form function of position, with no gradient and no parameters. (Learned positional embeddings exist as a separate design choice, but they are not what this formula describes.)
- Order information (2). Restates permutation-equivariance: attention sees a set, so order must be injected at the input.
- Geometric progression (3). The wavelengths \(2\pi\cdot10000^{2i/d_m}\) form a geometric series in \(i\) — ratio \(10000^{2/d_m}\) per pair — so early dimensions oscillate fast and late ones slowly, giving the model a multi-scale ruler. Strictly, the frequencies decay geometrically while the wavelengths grow; the key marks this true because the intended point is the geometric spacing. Do not be talked out of it by the direction of the word "grow".
- Relative positions (4). The real reason for sinusoids: \(\mathrm{PE}(j+k)\) is a fixed linear (rotation) transform of \(\mathrm{PE}(j)\) for any offset \(k\), straight from \(\sin(a+b)\) and \(\cos(a+b)\). So a linear layer can learn to detect "\(k\) positions apart" independently of absolute location.
- Uniqueness (5). With the lowest frequency having wavelength \(2\pi\cdot10000\), no two positions in any practical sequence share an encoding.
MSQ tactic: zero negative marking means select every option you can positively justify. Here, spotting the single false statement is the whole question.
Training & decoding an AR transformer
How the loss is formed, and the five ways to turn a probability vector into a token. Beam search and top-\(k\)/top-\(p\) renormalisation are the examined pieces — both are pure bookkeeping.
Training: teacher forcing
\(\displaystyle \mathcal L=-\sum_{t=1}^{T}\log\hat y_{t,x_t},\qquad \hat y_{t,x_t}=p_\theta(x_t|x_{<t})\) Plain cross-entropy: at each position, take the model's probability for the token that actually occurred and sum the negative logs. Note this is exactly \(-\log p_\theta(x)\) for the whole sequence, by the AR factorisation — so minimising cross-entropy is literally maximum likelihood, with no bound and no gap.
Feed in the ground-truth prefix rather than the model's own predictions (that is what "teacher forcing" means), and the causal mask guarantees position \(t\) cannot see beyond \(t-1\). So all \(T\) next-token predictions are computed in one forward pass, and every position contributes a loss term. This is the transformer's decisive advantage over an RNN, which must be unrolled sequentially. Inference stays sequential either way — you cannot condition on a token you have not generated yet.
The five decoding strategies
| Strategy | Rule | Character |
|---|---|---|
| Greedy | \(\hat y_t^*=\arg\max_{v\in V}p_{\theta}(x_t{=}v|x_{<t})\) | Deterministic, fast; repetitive and poor for creative generation |
| Sampling | \(\hat y_t^*\sim\mathrm{Categorical}(\hat y_t)\) | Maximally diverse; can incoherently pick tokens from the tail |
| Top-\(k\) | Keep the \(k\) highest-probability tokens \(V_k\), renormalise \(p_k(v_i)=\frac{p(v_i)}{\sum_{j=1}^{k}p(v_j)}\), sample | Truncates the tail with a fixed count |
| Top-\(p\) (nucleus) | Take the smallest set of top tokens whose cumulative mass \(\ge p\), renormalise, sample | Adaptive: a narrow set when the model is confident, wide when it is not |
| Temperature | \(z_t'=z_t/T\) then softmax | \(T<1\) sharper (toward greedy); \(T>1\) flatter (toward uniform) |
Beam search is not in the lecture notes but is in the papers, so know it: keep the \(k\) highest-scoring partial sequences ("beams"), and at each step expand every beam by every candidate continuation, score by the sum of log-probabilities along the path, and keep the best \(k\) of the pooled candidates. Log-probs add because probabilities multiply along a path.
- ('hello','world') and ('hello','there')
- ('hello','world') and ('hi','there')
- ('hi','there') and ('hi','you')
- ('hello','there') and ('hi','you')
› Reveal answer
Score all four candidates, then take the top two. Nothing else.
| Path | Accumulated + step | Score | Rank |
|---|---|---|---|
| ('hello','world') | \(-0.7+(-0.3)\) | \(-1.0\) | 1st ✓ |
| ('hi','there') | \(-1.2+(-0.2)\) | \(-1.4\) | 2nd ✓ |
| ('hello','there') | \(-0.7+(-1.0)\) | \(-1.7\) | 3rd |
| ('hi','you') | \(-1.2+(-0.6)\) | \(-1.8\) | 4th |
Log-probs are negative, so "highest score" means closest to zero. That sign is the only real trap, and it is what options 1 and 3 are built on: each keeps both children of a single beam, which is what happens if you rank by magnitude or expand only the currently-best beam. Beam search pools candidates across all beams — the winning pair here comes one from each. Note that the best step-\(t\!+\!1\) continuation (\(-0.2\), from 'hi') does not produce the best path, because 'hi' started half a nat behind. That is the entire point of beam search over greedy decoding.
The AN twin is the same question with 'cat'/'dog': \(-1.0,-1.5\) and steps \(-0.5,-1.0\) / \(-0.1,-0.4\), giving \(-1.5\) for ('cat','sits') and \(-1.6\) for ('dog','barks') — again one from each beam.
› Reveal answer
(a) Keep \(0.5\) and \(\tfrac13\); the surviving mass is \(0.5+\tfrac13=\tfrac56\). So
Option 0.5 is the un-renormalised probability — the whole point of the question is that truncation forces renormalisation, and the kept tokens' probabilities all rise.
(b) Accumulate until the total reaches \(p=0.9\): \(0.5\to0.7\to0.85\to0.95\). Three tokens give only \(0.85<0.9\), so you need the fourth: \(|S_p|=4\) with mass \(0.95\). Then
"Smallest set whose cumulative mass exceeds \(p\)" means you overshoot deliberately — you never stop at 0.85 and you never trim the last token to make the sum exactly 0.9. Option "Size 4, prob = 0.1" is the trap for skipping the renormalisation, and "Size 3, prob = 0" for stopping one token early.
RL foundations and the policy gradient theorem
The second of the two engines. Every recent paper builds a 5–8 mark cluster on the sequence: returns → reward-to-go → advantage → gradient estimate. Learn it as a table you fill in, not as a formula you recall.
The MDP
\(r:S\times A\to\mathbb R\): reward · \(\gamma\in(0,1)\): discount · \(\rho(s_0)\): initial-state distribution The policy \(\pi_\theta(a_t|s_t)\) is a distribution over actions given a state, parameterised by \(\theta\). A trajectory is \(\tau=(s_0,a_0,s_1,a_1,\dots)\).
\(\displaystyle R(\tau)=\sum_{t=0}^{\infty}\gamma^t r(s_t,a_t),\qquad J(\theta)=\mathbb E_{\tau\sim p_\theta}\big[R(\tau)\big],\qquad \pi_{\theta}^*=\arg\max_\theta J(\theta)\) Update by gradient ascent: \(\theta^{t+1}\leftarrow\theta^t+\alpha\nabla_\theta J(\theta)\). Note the sign — we are maximising reward, not minimising a loss.
The policy gradient theorem
The problem: \(J(\theta)=\int p_\theta(\tau)R(\tau)d\tau\) depends on \(\theta\) through the distribution we sample from, and \(R(\tau)\) may not even be differentiable. The fix is the log-derivative trick:
\(\displaystyle \Longrightarrow\quad\nabla_\theta\log p_\theta(\tau)=\sum_{t}\nabla_\theta\log\pi_\theta(a_t|s_t)\) \(\rho\) and \(p\) carry no \(\theta\), so their gradients vanish. This is what makes policy gradient model-free — you never need to know the environment dynamics.
Refinement 1 — reward-to-go. An action at time \(t\) cannot affect rewards already collected, so replace the whole-trajectory return by
Refinement 2 — a baseline. Subtract any function of state, \(b(s_t)\), to cut variance. Choosing \(b(s_t)=V^\pi(s_t)\) gives the advantage form:
\(\displaystyle \approx\mathbb E\left[\sum_t\nabla_\theta\log\pi_\theta(a_t|s_t)\,A^{\pi_\theta}(s_t,a_t)\right]\)
Value, Q and advantage
\(\displaystyle Q^\pi(s_t,a_t)=\mathbb E_\pi\Big[\textstyle\sum_{k\ge0}\gamma^k r(s_k,a_k)\;\Big|\;s_0=s_t,a_0=a_t\Big]\) — ...having committed to an action
\(\displaystyle A^\pi(s,a)=Q^\pi(s,a)-V^\pi(s)\) — how much better this action is than average
Condition on \((s_t,a_t)\) and take expectations:
\(V^\pi(s_t)\) passes through the expectation untouched because it is already a function of \(s_t\) alone. So a single sampled reward-to-go, minus the value estimate, is a one-sample unbiased estimator of the advantage — which is exactly what every exam cluster asks you to compute.
\(\displaystyle =b(s)\,\nabla_\theta\underbrace{\sum_a\pi_\theta(a|s)}_{=\,1}=b(s)\cdot0=0\)
Subtracting a state-dependent baseline changes the variance but not the expectation. The mechanism: \(b(s)\) is constant with respect to \(a\) so it factors out, the \(\pi\)'s cancel, and the gradient of a constant 1 is 0. This exact question has been asked in both 2025 T3 papers.
- \(b(s)\)
- \(0\)
- \(1.0\)
- \(\nabla_\theta b(s)\)
› Reveal answer
Exactly the identity above, and the reason it is worth 3 marks twice: it is the theoretical licence for everything the exam then asks you to compute. Since the baseline term has zero mean, you may subtract \(V^\pi(s_t)\) for free — the gradient estimator stays unbiased while its variance drops, because \(R_t-V^\pi(s_t)\) is a much smaller number than \(R_t\).
Option 4 is the interesting distractor. \(\nabla_\theta b(s)\) would be the answer if \(b\) depended on \(\theta\) in a way that mattered — and this hints at the real constraint: the baseline must not depend on the action. A baseline \(b(s,a)\) would not factor out of the sum over \(a\), and would bias the gradient. That is why \(V^\pi(s)\) is a legal baseline and \(Q^\pi(s,a)\) is not.
› Reveal answer
The whole cluster is one table. Build it before answering anything. Compute the reward-to-go values backwards using \(R_t=r_t+\gamma R_{t+1}\) — four multiplications instead of ten.
| \(t\) | \(r_t\) | \(R_t=r_t+\gamma R_{t+1}\) | \(V^\pi(s_t)\) | \(\hat A_t=R_t-V^\pi\) | \(g_t\) | \(g_t\hat A_t\) |
|---|---|---|---|---|---|---|
| 3 | 4 | \(4.000\) | 4.0 | \(0.000\) | 0.1 | \(0.000\) |
| 2 | 3 | \(3+0.9(4)=6.600\) | 6.2 | \(0.400\) | 0.4 | \(0.160\) |
| 1 | −1 | \(-1+0.9(6.6)=4.940\) | 4.0 | \(0.940\) | −0.2 | \(-0.188\) |
| 0 | 2 | \(2+0.9(4.94)=6.446\) | 5.0 | \(1.446\) | 0.5 | \(0.723\) |
(a) is the bottom-row \(R_t\): \(R_0=R(\tau)=6.446\). (b) is the row above: \(R_1=4.94\). (c) is the last column summed: \(0.723-0.188+0.160+0=\mathbf{0.695}\).
Three things that make or break this cluster. First, \(R_t\) restarts its discounting at \(t\) — \(R_1=r_1+\gamma r_2+\gamma^2r_3\), not \(\gamma r_1+\gamma^2r_2+\gamma^3r_3\). Dividing \(R(\tau)\) by \(\gamma\) is wrong; the backward recursion makes this impossible to get wrong. Second, \(\hat A_3=0\) exactly (the last reward-to-go is just \(r_3=4\), and \(V^\pi(s_3)=4.0\)), so \(g_3\) is decoration — a deliberate gift. Third, the advantages are small (0 to 1.4) while the returns are large: that shrinkage is the variance reduction the baseline exists to deliver.
› Reveal answer
Identical machinery, new numbers — which is precisely why the table is worth internalising.
| \(t\) | \(r_t\) | \(R_t\) | \(V^\pi\) | \(\hat A_t\) | \(g_t\) | \(g_t\hat A_t\) |
|---|---|---|---|---|---|---|
| 3 | 5 | \(5.00\) | 5.0 | \(0.00\) | 0.1 | \(0.000\) |
| 2 | −2 | \(-2+0.8(5)=2.00\) | 1.5 | \(0.50\) | −0.2 | \(-0.100\) |
| 1 | 1 | \(1+0.8(2)=2.60\) | 2.0 | \(0.60\) | 0.3 | \(0.180\) |
| 0 | 3 | \(3+0.8(2.6)=5.08\) | 4.5 | \(0.58\) | 0.4 | \(0.232\) |
\(\hat g=0.232+0.180-0.100+0=\mathbf{0.312}\). Again \(\hat A_3=0\) because \(V^\pi(s_3)\) is set equal to the final reward — this setter does that every time, so expect the last term to vanish and use it as a check that your table is right.
What the sign of \(\hat g\) means: it is positive here, so the update \(\theta\leftarrow\theta+\alpha\hat g\) increases the log-probability of the sampled actions on balance. Where \(g_t\hat A_t<0\) (at \(t=2\), because \(g_2\) is negative while the advantage is positive) that coordinate is pushed the other way.
› Reveal answer
(a) \(G_1=r_1+\gamma r_2+\gamma^2r_3=1+0.9(0)+0.81(2)=1+0+1.62=2.62\). The \(r_2=0\) is there to see whether you keep the place of the zero term — skip it and you compute \(1+0.9(2)=2.8\), which is the 2.81 decoy.
(b) The distractors are worth naming, because each is a specific misunderstanding:
- \(\mathbb E[\nabla_\theta\pi_\theta(a|s)]\) — missing the \(\log\). Without it there is no log-derivative trick and the expression is not an expectation under \(\pi_\theta\) at all.
- \(\mathbb E[\nabla_\theta V^\pi(s)]\) — differentiating the value function directly, which needs the dynamics and defeats the purpose.
- \(\nabla J=0\) — confusing the baseline term (which does vanish, §13 above) with the whole gradient.
The \(Q^\pi\)-weighted form is the theorem's canonical statement; the \(A^\pi\)-weighted form used in the course is that same expression with a zero-mean baseline subtracted, and the reward-to-go \(R_t\) is its one-sample estimate. All three are the same object at different levels of estimation.
The LM as an RL policy
The dictionary that connects Week 10 to Week 11. Two guaranteed questions in the 2025 T3 format — one MSQ on the correspondence, one on dimensions — and both are free marks once the mapping is memorised.
Why alignment needs RL at all. Maximum likelihood on internet text makes a model fluent. It does not make it helpful, harmless or honest, because those properties are not in the likelihood. Worse, they cannot be written down as a differentiable function of the output. What humans can do is compare two responses. So we need an optimiser that works with a non-differentiable scalar signal on sampled outputs — which is exactly what policy gradient is.
| RL object | LM object | Detail |
|---|---|---|
| Policy \(\pi_\theta(a_t|s_t)\) | The LM's own conditional \(p_\theta(x_t|x_{<t})\) | No change to the model — the AR factorisation already is a policy |
| State \(s_t\) | The context: prompt + all tokens generated so far | \(s_0=\) prompt; \(s_1=[s_0\;a_0]\); the state grows |
| Action \(a_t\) | The next token emitted | Action space is the vocabulary \(V\) |
| Trajectory \(\tau\) | The full (prompt, generated tokens) sequence | One roll-out = one complete response |
| Transition \(p(s_{t+1}|s_t,a_t)\) | String concatenation | Deterministic — the environment is trivial, all the randomness is in the policy |
| Reward \(r(s_t,a_t)\) | A learned preference score, typically only at the end | Not the pretraining log-likelihood — that is the recurring wrong option |
- The state \(s_t\) corresponds to the current context: prompt plus all tokens generated so far.
- The action \(a_t\) corresponds to selecting the next token from the vocabulary.
- The trajectory \(\tau\) corresponds to the full sequence of (prompt, generated tokens) over time.
- The policy \(\pi_\theta(a_t|s_t)\) corresponds to the LM's conditional distribution \(p_\theta(x_t|x_{<t})\).
- The reward \(r(s_t,a_t)\) is necessarily the log-likelihood of the token under the pretraining objective.
› Reveal answer
Same structure in both papers: four true correspondences and one false reward claim. The reward option is false on the word "necessarily", and the reason is the whole motivation for Weeks 11–12 — if the reward were the pretraining log-likelihood, optimising it would just be more pretraining, and alignment would be a no-op. The reward comes from outside the likelihood: a model trained on human preference comparisons (§16).
Exam habit worth forming: in this course's MSQs, an option containing "necessarily", "always", "must" or "guarantees" is false far more often than not. Check whether a single counterexample exists.
- Output dim 25; trajectory space \(32000\times25\)
- Output dim 32000; trajectory space \(25^{32000}\)
- Output dim 32000; trajectory space \(32000^{25}\)
- Output dim 1; trajectory space \(32000\)
› Reveal answer
Two separate facts, each with a clean justification:
- Output dimension \(=|V|\). At each step the policy emits a full distribution over the vocabulary — one probability per token, a 32000-vector summing to 1. It does not emit a single token; sampling from the distribution does that. (Option 4's "output dim 1" confuses the sampled action with the policy.)
- Trajectory space \(=|V|^T\). Each of the \(T\) positions independently takes any of \(|V|\) values, so the count of distinct length-25 sequences is \(32000^{25}\) — base is the vocabulary, exponent is the length.
Base-versus-exponent is the entire question, and option 2 exists solely to catch the swap. Sanity-check by extremes: with \(T=1\) the space should be exactly \(|V|\), and only \(|V|^T\) gives that. The AN twin uses \(|V|=50000,\;T=20\), answer \(50000^{20}\).
Why this matters beyond the mark: \(32000^{25}\approx10^{112}\) trajectories is why you cannot enumerate, cannot compute the exact expectation, and must estimate \(\nabla J\) from a handful of sampled roll-outs. The astronomical size of this space is the reason for the whole variance-reduction apparatus — baselines, advantages, clipping.
Importance sampling → TRPO → PPO
A three-step argument driven entirely by one problem: policy gradient is on-policy, so every update throws its data away. PPO clipping is the single most-computed formula in the 2026 T1 papers.
The problem: on-policy is wasteful
The estimator \(\hat g=\frac1T\sum_t\nabla_\theta\log\pi_\theta(a_t|s_t)\hat A_t\) is an expectation under \(\pi_\theta\). The instant you take one gradient step, \(\theta\) has changed and your roll-outs are stale. For an LM, each roll-out means generating full responses — ruinously expensive to discard after one update.
Step 1 — importance sampling
Apply it with \(q=\pi_{\theta_{\text{old}}}\), and use \(\frac{\pi_\theta}{\pi_{\theta_{\text{old}}}}\nabla_\theta\log\pi_\theta=\nabla_\theta\big(\frac{\pi_\theta}{\pi_{\theta_{\text{old}}}}\big)=\nabla_\theta r_t\). The gradient becomes the gradient of a plain objective:
The ratio is unbounded. If \(\pi_\theta\) drifts far from \(\pi_{\theta_{\text{old}}}\), \(r_t\) explodes, the objective explodes, and the estimator's variance goes with it — a collapsed policy. Worse, the surrogate is only a valid local approximation near \(\theta_{\text{old}}\). So the fix is to constrain how far the policy may move, via a distributional divergence. Both TRPO and PPO are ways of doing that.
Step 2 — TRPO: constrain it explicitly
- \(\mathbb E_{s\sim\rho}\big[D_{KL}(\pi_{\text{old}}(\cdot|s)\|\pi_{\text{new}}(\cdot|s))\big]\le\delta\) (average KL)
- \(\max_s D_{KL}(\pi_{\text{old}}(\cdot|s)\|\pi_{\text{new}}(\cdot|s))\le\delta\) (pointwise max)
- \(D_{KL}(\pi_{\text{new}}\|\pi_{\text{old}})^2\le\delta\)
- \(\|\theta_{\text{new}}-\theta_{\text{old}}\|_2\le\delta\) (Euclidean distance)
› Reveal answer
Verbatim in both papers. Each distractor is instructive:
- Pointwise max (2) is the theoretically motivated constraint but is intractable — you would have to bound the KL at every state in a space of \(10^{112}\) contexts. TRPO deliberately relaxes it to an average, which is estimable from the sampled batch.
- Squared KL (3) is not a thing; and note it also reverses the argument order.
- Euclidean distance on \(\theta\) (4) is the deep conceptual error, and worth understanding: a small parameter change can produce an enormous change in the output distribution, and a large one can produce none at all. Trust regions are defined in distribution space, not parameter space — that is the entire idea behind the word "trust region", and the reason plain gradient clipping is not a substitute.
Step 3 — PPO: get the same effect without solving a constrained problem
TRPO's constrained optimisation is expensive (it needs second-order information). PPO replaces the explicit constraint with a clipped objective that removes the incentive to move far, so no constraint is needed:
Do not reason about the \(\min\) in the abstract. Mechanically:
- 1.Compute \(r_t=\pi_\theta/\pi_{\text{old}}\) for the sampled action only.
- 2.Compute \(\tilde r_t=\mathrm{clip}(r_t,1-\epsilon,1+\epsilon)\) — i.e. pull \(r_t\) back inside the window if it is outside.
- 3.Take \(\min(r_tA_t,\;\tilde r_tA_t)\). If \(r_t\) was already inside the window, \(\tilde r_t=r_t\) and the two terms are equal — the answer is just \(r_tA_t\).
The asymmetry that the \(\min\) creates. When \(A_t>0\) the objective is capped at \((1+\epsilon)A_t\): no extra credit for pushing a good action's probability up beyond the window. When \(A_t<0\) multiplying by the smaller ratio gives the more negative product, so the \(\min\) selects \(\max(r_t,1-\epsilon)\cdot A_t\) — the penalty for a bad action is not capped from below in the same way. In short: clipping removes the reward for moving too far in the favourable direction, while keeping the pressure to move away from bad actions.
› Reveal answer
Build the whole table first. All five sub-questions read off it.
| \(t\) | \(\pi_{\text{old}}\) | \(\pi_\theta\) | \(r_t\) | In \([0.8,1.2]\)? | \(\tilde r_t\) | \(A_t\) | \(r_tA_t\) | \(\tilde r_tA_t\) | \(\min\) |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 0.20 | 0.26 | 1.3 | no, too high | 1.2 | 1.5 | 1.95 | 1.80 | 1.80 |
| 1 | 0.50 | 0.40 | 0.8 | yes, at the edge | 0.8 | −0.8 | −0.64 | −0.64 | −0.64 |
| 2 | 0.10 | 0.14 | 1.4 | no, too high | 1.2 | 2.0 | 2.80 | 2.40 | 2.40 |
\(\text{total}=1.80+(-0.64)+2.40=\mathbf{3.56}\).
The three cases in this one table are exactly the three cases that exist, which is why it is such an economical question:
- \(t=0\): ratio too high, advantage positive. Clipping bites — the answer 1.8 is strictly less than the unclipped 1.95. This is the clip doing its job.
- \(t=1\): ratio exactly on the boundary. \(0.8\) is inside \([0.8,1.2]\), so \(\tilde r=r\) and both terms are \(-0.64\). The interval is closed — do not clip a value that sits on the edge, and do not be spooked by the negative advantage. Note the answer here is simply \(r_tA_t\).
- \(t=2\): ratio too high again, larger advantage, same treatment: \(1.2\times2.0=2.4\).
Two safeguards. (i) Take the ratio of the sampled action's probability only — not a sum over the distribution. (ii) When \(A_t>0\) and \(r_t>1+\epsilon\), the answer is always exactly \((1+\epsilon)A_t\), so you can write it down without computing \(r_tA_t\) at all.
› Reveal answer
(a)–(d) The full distributions are given, but the ratio uses only the sampled action — the first component:
\(r_2=\dfrac{0.48}{0.60}=0.8\;\in[0.8,1.2]\;\Rightarrow\;\text{contribution}=0.8\times(-1.5)=-1.2\)
Both ratios land exactly on a boundary, so clipping never bites and both answers are just \(r\!\cdot\!A\). This paper is testing whether you know the interval is closed — the reverse of the FN paper, where clipping bit twice. If you had wrongly clipped 1.2 down or 0.8 up you would still get the same numbers here, which makes it a forgiving question; the marks are in not panicking at the second components (0.64, 0.52), which are pure distraction.
(e) Now the second components matter, because a KL sums over the whole distribution:
\(=0.30\ln\!\frac{0.30}{0.36}+0.70\ln\!\frac{0.70}{0.64}=0.30(-0.182)+0.70(0.090)\)
\(=-0.0546+0.0630=0.0084\)
Use the supplied logs to identify which terms you need: \(0.30/0.36=0.8333\) and \(0.70/0.64=1.09375\) are given, so those are state 1's two terms; \(1.25\) and \(0.7692\) belong to state 2 and are decoys here. Two checks: the weights are \(\pi_{\text{old}}\) (the first argument of the KL) — using \(\pi_\theta\) gives the reverse KL, a different number; and the result must be \(\ge0\) even though one term is negative. A tiny value like 0.0084 is exactly what you expect for two nearly-identical distributions — and it is the quantity TRPO would have constrained explicitly and PPO controls implicitly through the clip.
- \(-0.85\)
- \(-0.80\)
- \(-0.20\)
- \(-1.00\)
› Reveal answer
\(r=0.85\) lies inside \([0.8,1.2]\), so \(\mathrm{clip}(r)=r\), both branches equal \(-0.85\), and the \(\min\) is \(-0.85\).
The negative advantage is bait. Option \(-0.80\) is what you get by clipping \(0.85\) to \(0.8\) — which people do because "clip" feels like it should always fire, or because the negative sign makes them apply the clip in the wrong direction. Always check membership of the interval first; if \(r\in[1-\epsilon,1+\epsilon]\) the clip is the identity and there is nothing to do, whatever the sign of \(A\). Option \(-1.00\) forgets \(r\) entirely.
The full PPO loss (for completeness)
Easy to garble under pressure, so reason it out rather than memorising: we want high reward (so \(-L_{\mathrm{PPO}}\), since minimising a negative maximises it), accurate values (so \(+\) a squared error), and high entropy (so \(-\beta\mathcal H\)). Each sign follows from whether the quantity is something you want more or less of.
Reward modelling & RLHF
PPO needs a reward. Nobody can score a response on an absolute scale, but anyone can say which of two is better. The Bradley–Terry model turns comparisons into a scalar — and both formulas here are one-line numeric substitutions worth 3 marks each.
The Bradley–Terry model
Collect triples \((x,y_w,y_l)\): a prompt, a preferred ("winning") completion and a dispreferred one. Model the probability that \(y_w\) is preferred as a softmax over two learned scores:
› Reveal answer
Take the difference first — it is the only input.
\(\phantom{\text{FN: }}\mathcal L=-\ln 0.7503=0.2873\)
\(\text{AN: }\Delta=2.5-1.0=1.5,\quad \sigma(1.5)=\dfrac{1}{1+e^{-1.5}}=0.8176\)
\(\phantom{\text{AN: }}\mathcal L=-\ln 0.8176=0.2014\)
The shortcut worth knowing: \(-\log\sigma(\Delta)=\log(1+e^{-\Delta})\), the softplus of \(-\Delta\). One exponential, one log — no division. For \(\Delta=1.1\): \(\ln(1+0.3329)=\ln1.3329=0.2873\).
Three sanity properties that catch sign errors. The loss is always \(>0\). It decreases as \(\Delta\) grows — the model is more confident the winner wins — which is why the AN answer (\(\Delta=1.5\)) is smaller than the FN one (\(\Delta=1.1\)). And at \(\Delta=0\) it is \(-\ln0.5=0.693\), the maximum-confusion value: any answer above 0.693 means the model ranks the pair the wrong way round, so if your loss for a correctly-ordered pair exceeds 0.693 you have flipped the subtraction.
The RLHF reward: reward model minus a leash
Optimising \(r_\phi\) alone leads to reward hacking — the policy discovers degenerate outputs that score highly under an imperfect learned reward while being useless text. The fix is a KL penalty tying the policy to the pretrained reference model:
Both appear in the same algorithm and students routinely merge them:
- The PPO clip / TRPO constraint keeps \(\pi_\theta\) near \(\pi_{\theta_{\text{old}}}\) — the policy from the last gradient step. Purpose: optimisation stability. It moves every update.
- The RLHF \(\beta\)-penalty keeps \(\pi_\theta\) near \(\pi_{\text{ref}}\) — the frozen pretrained/SFT model. Purpose: preventing reward hacking and language degeneration. It never moves.
› Reveal answer
The supplied logarithm tells you the ratio before you compute it — \(\ln4\) means the ratio is 4, i.e. \(0.8/0.2\). Use that as a check that you have the fraction the right way up.
\(\text{AN: }R=1.8-0.4\ln\!\frac{0.6}{0.3}=1.8-0.4\ln2=1.8-0.4(0.69)=1.8-0.276=1.524\)
The sign is the whole question. The policy here assigns higher probability than the reference (ratio \(>1\)), so the log is positive and the penalty subtracts — the model is being charged for having drifted. Getting \(3.2\) instead of \(1.8\) means you added. Inverting the ratio to \(\ln(0.25)=-1.4\) would give a spurious bonus.
And note what the penalty is not. It is a per-sample log-ratio, not a full KL divergence — no sum over the vocabulary, no probability weighting. Its expectation under \(\pi_\theta\) is the KL, which is why the two formulations agree in expectation, but a single sampled log-ratio can even be negative (when the policy is less likely than the reference) whereas a KL never is.
Direct Preference Optimisation
The punchline of the course: solve the KL-constrained objective in closed form, invert it, and the reward model disappears. One elegant derivation, and one recurring 3-mark substitution.
The goal: optimise the LM on preference data without a reward model and without PPO. Start from the constrained policy objective of §16:
Step 1 — the closed-form optimum
\(\displaystyle Z(x)=\sum_y\pi_{\text{ref}}(y|x)\exp\!\left(\frac{1}{\beta}r_\phi(x,y)\right)\) The reference distribution exponentially tilted by the reward. Intuitive: reweight the pretrained model's outputs by \(e^{r/\beta}\), favouring high-reward responses, with \(\beta\) controlling the sharpness. But \(Z(x)\) sums over all possible responses — astronomically intractable, so \(\pi^*\) cannot be computed directly.
Step 2 — invert it for the reward
Take logs of the optimum and solve for \(r_\phi\) instead of for \(\pi\):
\(\displaystyle \Longrightarrow\quad r_\phi^*(x,y)=\beta\log\frac{\pi^*(y|x)}{\pi_{\text{ref}}(y|x)}+\beta\log Z(x)\) The change of variable that makes DPO work. Any policy implicitly defines a reward, and this is it. Note this is the same expression as the RLHF KL penalty in §16 — the leash and the implicit reward are the same quantity, read in opposite directions.
Step 3 — substitute into Bradley–Terry, and watch \(Z(x)\) cancel
Bradley–Terry depends only on the difference \(r_w-r_l\). Both rewards carry the same \(+\beta\log Z(x)\) term — it depends on \(x\) only, not on \(y\) — so it cancels exactly:
No \(r_\phi\), no \(Z(x)\), no sampling, no PPO. This is a plain supervised classification loss on preference pairs that you can train with SGD. It requires exactly four forward passes per pair: \(\pi_\theta\) and \(\pi_{\text{ref}}\) on each of \(y_w\) and \(y_l\). The intractable partition function was never a problem because Bradley–Terry only ever looks at differences — that is the one-sentence summary of the whole method.
- \(0.10\)
- \(0.23\)
- \(0.45\)
- \(1.00\)
› Reveal answer
Use \(r^*=\beta\log\frac{\pi^*}{\pi_{\text{ref}}}\), dropping the \(\beta\log Z(x)\) term (it is unidentifiable and cancels in every use of the reward):
Recognise \(\ln10=2.3026\) on sight — a tenfold ratio is the setter's favourite because \(0.1\times2.3=0.23\) lands cleanly. Option \(0.10\) is \(\beta\) itself (forgetting the log); \(0.45\) is \(\log_{10}\)-based arithmetic gone astray; \(1.00\) comes from \(\log_{10}10=1\) without the \(\beta\). Natural logs unless stated otherwise.
What the number means: the aligned policy is 10× more likely than the reference to produce this response, and at \(\beta=0.1\) that is scored as a reward of 0.23. Turn \(\beta\) down and the same behavioural change implies a smaller reward — because a weaker leash means less reward is needed to explain the same drift.
- \(0.0\)
- \(0.5\)
- \(1.0\)
- Undefined
› Reveal answer
\(\sigma(4.0-4.0)=\sigma(0)=\frac{1}{1+e^{0}}=\frac12\). Two seconds of arithmetic — but the concept it tests is the most important property of the DPO gradient, and worth stating properly:
- The weight is the model's own error probability, so DPO is self-annealing. Pairs the model already ranks correctly (\(\hat r_w\gg\hat r_l\)) get \(\sigma(\text{large negative})\approx0\) and contribute almost nothing.
- Pairs it ranks wrongly get \(\sigma(\text{large positive})\approx1\) and dominate the update.
- Indifference sits exactly in the middle at \(0.5\) — maximum uncertainty, half weight.
Do not mistake "indifferent" for "no gradient". Option \(0.0\) is the trap for reasoning "equal rewards, so nothing to learn". The opposite holds: equal rewards mean the model has not yet learned this preference, so the example is highly informative. Zero weight arrives only once the preference is confidently correct.
State-space models: S4 and Mamba
The course's coda: an alternative to attention that is linear rather than quadratic in sequence length. Examined so far by exactly one question — the ZOH discretisation — which is a single exponential. Learn that cold, then read the rest once for concept MCQs.
The continuous model, and why it must be discretised
\(y(t)=Cx(t)\) \(u(t)\) input, \(y(t)\) output, \(x(t)\) an \(N\)-dimensional hidden state; \(A,B,C\) learnable. Text is discrete, so the first step is always to discretise with a step size \(\Delta\), where \(u_k=u(k\Delta)\).
| Method | Discretised parameters | Where it appears |
|---|---|---|
| Bilinear (Tustin) | \(\bar A=\big(I-\tfrac{\Delta}{2}A\big)^{-1}\big(I+\tfrac{\Delta}{2}A\big)\), \(\bar B=\big(I-\tfrac{\Delta}{2}A\big)^{-1}\Delta B\), \(\bar C=C\) | The lecture notes' method |
| Zero-order hold (ZOH) | \(\bar A=\exp(\Delta A)\), \(\bar B=(\Delta A)^{-1}(\exp(\Delta A)-I)\Delta B\) | What the papers ask for — and they supply the formula |
› Reveal answer
\(\text{AN: }\bar A=e^{0.5\times(-2.0)}=e^{-1}=0.3679\)
Multiply, then exponentiate — that is the entire question, and the formula is given. The AN version is \(e^{-1}\) exactly, worth recognising as \(0.368\) without a calculator.
Two checks that make this error-proof. Since \(A<0\) (the stem says "representing decay") the exponent is negative, so \(\bar A\in(0,1)\) — any answer above 1 means a dropped minus sign, and it would also mean an unstable recurrence in which \(x_k=\bar A^kx_0\) explodes. And \(\bar A\) is the per-step memory-retention factor: \(0.472\) means each step keeps 47% of the previous state, so the model's memory decays with a half-life of about one step. Larger \(\Delta\) or more negative \(A\) = shorter memory.
From recurrence to convolution — and why S4 is fast
Set \(x_{-1}=0\) and unroll:
\(\displaystyle y_k=\bar C\bar A^k\bar Bu_0+\bar C\bar A^{k-1}\bar Bu_1+\dots+\bar C\bar Bu_k\) Every output is a fixed weighted sum of past inputs, with weights \(\bar C\bar A^i\bar B\) that do not depend on \(k\).
A linear recurrence is exactly a convolution with a fixed kernel. Hence an SSM has two equivalent modes: a recurrent one (\(O(1)\) memory per step — ideal for inference) and a convolutional one (parallel over the whole sequence via FFT — ideal for training). That duality is what attention cannot offer: it parallelises over training but costs \(O(T^2)\), whereas an SSM is \(O(T\log T)\) via FFT and \(O(T)\) sequentially.
Computing \(\bar K\) efficiently (S4). Building the kernel naively needs \(L\) matrix powers. S4 works in the frequency domain via the generating function \(\hat K_L(z)=\sum_{i=0}^{L-1}\bar C\bar A^i\bar Bz^i=\bar C\big[\sum_i(\bar Az)^i\big]\bar B\), and the matrix geometric series \(\sum_{i=0}^{L-1}(\bar Az)^i=(I-\bar A^Lz^L)(I-\bar Az)^{-1}\) collapses as \(L\to\infty\) to
| Structure on \(\bar A\) | Consequence |
|---|---|
| Diagonal, \(\bar A=\Lambda=\mathrm{diag}(\lambda_1,\dots,\lambda_N)\) | \((I-\Lambda z)^{-1}=\mathrm{diag}\big(\tfrac{1}{1-\lambda_iz}\big)\), so \(\hat K_\Lambda(z)=\sum_i\frac{\bar C_i\bar B_i}{1-\lambda_iz}\) — a sum of \(N\) scalar terms, no inversion at all |
| DPLR: \(\bar A=\Lambda-pq^*\) with \(p,q\) rank-1 and learnable | The Woodbury identity reduces the inverse of "diagonal plus low rank" to diagonal terms plus a rank-1 correction — still cheap, but strictly more expressive |
| HiPPO initialisation | In S4, \(A\) is initialised to the special HiPPO matrix, chosen so the state optimally compresses the input history onto a polynomial basis. Not a constraint but a starting point — and the reason S4 handles very long-range dependencies. |
For multi-dimensional data, SSMs are applied dimension-wise: each channel gets its own independent SSM. Training is ordinary empirical risk minimisation.
The limitation of S4. Because \((A,B,C)\) are fixed in time, the kernel \(\bar K\) is fixed — the model applies the same filter regardless of what it is reading. So it cannot do selective copying: it has no mechanism to decide "remember this token, ignore that one". Attention gets this for free, because its weights are computed from the content.
Mamba's fix is to make the parameters input-dependent:
The cost of that fix is the examinable consequence. Time-varying parameters mean there is no fixed kernel, so the convolutional view is gone and FFT-based training is impossible. Mamba therefore computes in the sequence domain using a hardware-aware parallel-scan algorithm instead of the frequency domain. Trade: content-selective memory, in exchange for giving up the convolution.
Weeks 1–8 carry-over
The 2026 T1 papers open with exactly 13 marks of Quiz 1 and Quiz 2 material, in a remarkably stable pattern. Full treatment is in the Quiz 1 and Quiz 2 guides — this section is the checklist of what actually reappears, with the real numbers.
| Slot | 2026 T1 FN | 2026 T1 AN | Marks |
|---|---|---|---|
| 1 | KL divergence properties (MSQ) | Numeric \(D_{KL}(P\|Q)\) over a small discrete space | 2 |
| 2 | GAN properties (MSQ) | GAN vs VAE: encoders and blurriness (MSQ) | 2–3 |
| 3 | Optimal discriminator, numeric | ELBO term-by-term reasoning (MSQ) | 3 |
| 4 | GMM responsibility, numeric | Optimal discriminator, numeric | 2–3 |
| 5 | \(\beta\)-VAE: effect of increasing \(\beta\) | GMM responsibility, numeric | 3 |
The pattern is stable enough to plan around: one KL item, one GAN concept item, one optimal-discriminator numeric, one GMM responsibility numeric, and one VAE/ELBO item. The two numerics are the reliable marks — drill those two formulas and you have banked 5–6 marks before touching Weeks 9–12.
For a 1-D Gaussian, \(\mathcal N(x;\mu,\sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp\!\big(-\frac{(x-\mu)^2}{2\sigma^2}\big)\) — and note that \(\sigma^2\) is given as the variance, so \(\sigma_2^2=9\) means \(\sigma_2=3\). Confusing the two is the single most common way to lose this mark.
› Reveal answer
(a) is the harder of the two, because you must read the densities out of a word problem.
\(D^*(\text{car})=\dfrac{0.75}{0.75+1}=\dfrac{0.75}{1.75}=0.4286\)
The two readings that decide it: "three times as many cars as bikes" makes the real distribution \(3\!:\!1\), i.e. \(0.75\) on cars — not 3, and not \(1/3\). And "produces only car images" makes the generator's density on cars \(1\), not \(0.75\). The answer is below \(0.5\), and that is the meaningful check: the generator over-produces cars relative to the real distribution, so a car is more likely to be fake than real, and an optimal discriminator must say so. Anyone who answers \(0.5\) has assumed convergence \(p_g=p_{\text{data}}\) — which the question has deliberately broken.
(b) \(D^*(x)=\frac{1/4}{1/4+3/4}=0.25\) is the probability of being real. The question asks for generated, so take the complement: \(1-0.25=0.75\). Equivalently \(\frac{p_G}{p_{\text{data}}+p_G}=\frac{3/4}{1}=0.75\). Underline the word "generated" or "real" before computing — the two papers ask opposite directions in consecutive terms, and both 0.25 and 0.75 are exactly-matched answers, so there is no partial credit for the complement.
› Reveal answer
Compute the two weighted densities, then divide. Do not normalise anything early.
\(\phantom{\text{FN: }}\pi_2\mathcal N_2=0.3\cdot\dfrac{1}{\sqrt{18\pi}}e^{-\frac{(4-6)^2}{18}}=0.3(0.13298)e^{-0.2222}=0.3(0.10648)=0.031945\)
\(\phantom{\text{FN: }}\gamma(z_1)=\dfrac{0.037794}{0.037794+0.031945}=\dfrac{0.037794}{0.069739}=0.5419\)
\(\phantom{\text{AN: }}\pi_2\mathcal N_2=0.4\cdot\dfrac{1}{\sqrt{8\pi}}e^{-\frac{9}{8}}=0.4(0.19947)e^{-1.125}=0.4(0.06476)=0.025904\)
\(\phantom{\text{AN: }}\gamma(z_1)=\dfrac{0.032395}{0.058299}=0.5557\)
Three traps, all of which appear here by design. (i) \(\sigma_2^2=9\Rightarrow\sigma_2=3\), so the normaliser is \(\frac{1}{3\sqrt{2\pi}}\) and the exponent denominator is \(2(9)=18\). (ii) You cannot drop the \(\frac{1}{\sqrt{2\pi\sigma^2}}\) prefactor, because the two components have different variances so it does not cancel — here \(C_2\) is three times wider and therefore three times flatter, which is most of why the answer is near \(\tfrac12\) despite \(\pi_1\) being much larger. (iii) The answer is a ratio, so no \(2\pi\) arithmetic is wasted if you keep both terms in the same form.
Why both answers sit just above 0.5: the point is placed roughly equidistant in standardised terms between a tall narrow component and a short wide one. The setter tunes it so the two weighted densities nearly tie — which means a small slip in either exponent moves the answer outside the accepted band. Carry four decimals.
- A standard GAN cannot reconstruct a specific input because it learns no explicit encoder mapping inputs to the latent space.
- The blurriness of VAE samples is primarily due to stochastic sampling in the latent space.
- GANs can generate realistic samples despite learning no encoder, as they sample from a structured latent distribution.
- The regularisation term in VAEs improves sharpness by enforcing consistency in reconstructions.
- Optimising only the KL term forces \(q_\phi(z|x)\) to match the prior \(p(z)\) for all \(x\), i.e. to become independent of the input.
› Reveal answer
The two false options are false for the same underlying reason, which makes them easy to dispatch together: both misattribute a property of the reconstruction term to the KL term.
- VAE blurriness comes from the reconstruction likelihood — a Gaussian \(p_\theta(x|z)\) makes the objective an L2 loss, and L2's optimum is the mean of all plausible images, which is a blur. Latent sampling contributes noise, not blur. (The deeper cause is maximising likelihood at all: it penalises missing a mode far more than covering a bad one, so a VAE hedges. A GAN's discriminator penalises implausibility directly, which is why GANs are sharper but drop modes.)
- The KL term is a regulariser on \(z\), pulling \(q_\phi(z|x)\) toward the prior. It does the opposite of improving sharpness — that is precisely the trade-off \(\beta\)-VAE exposes, and the subject of the next question.
Option 5 is the sharpest thing on this page. Optimising the KL alone is minimised by \(q_\phi(z|x)=p(z)\) for every \(x\) — the encoder ignores its input entirely and the latent carries zero information. That is posterior collapse, stated as an optimisation fact rather than a phenomenon: the reconstruction term is the only thing preventing it.
- \(q_\phi(z|x)\) approaches \(\mathcal N(0,I)\) but reconstructions become worse.
- \(q_\phi(z|x)\) goes farther from \(\mathcal N(0,I)\) and reconstructions become better.
- \(q_\phi(z|x)\) approaches \(\mathcal N(0,I)\) and reconstructions become better.
- \(q_\phi(z|x)\) goes farther from \(\mathcal N(0,I)\) and reconstructions become worse.
› Reveal answer
Reason from the loss, not from memory. This is a minimisation, and \(\beta\) multiplies the KL term. Raising \(\beta\) makes KL violations more expensive, so the optimiser buys KL reduction by spending reconstruction quality. Hence the posterior is pushed toward the prior and reconstructions degrade — the two effects always move in opposite directions, which immediately eliminates options 3 and 4 (both of which have them moving together).
In the limit \(\beta\to\infty\) you reach exactly the posterior collapse of the previous question: \(q_\phi(z|x)=\mathcal N(0,I)\) for all \(x\), zero KL, and a decoder that has no information to reconstruct from. In the limit \(\beta\to0\) you get a plain autoencoder with sharp reconstructions and an unusable, unstructured latent space. \(\beta\) is the dial on the rate–distortion trade-off, and its selling point is that intermediate values buy disentangled latents at a modest reconstruction cost.
Worked derivations
Three proofs whose steps are what the concept MCQs test. Each step below says not just what happens but why the move is legal — which is what kills the distractors.
Derivation 1 — the policy gradient theorem
Derivation 2 — the score identity via Tweedie's formula
-
\(\displaystyle \mathbb E[\mu_z\,|\,z]=z+\Sigma_z\nabla_z\log p(z)\qquad\text{for }z\sim\mathcal N(z;\mu_z,\Sigma_z)\)Tweedie's formula: the posterior mean of a Gaussian's mean, given one observation, is the observation nudged along the score. It is the general statement; everything else is substitution.
-
\(\displaystyle q(x_t|x_0)=\mathcal N\big(x_t;\sqrt{\bar\alpha_t}x_0,\,(1-\bar\alpha_t)I\big)\;\Rightarrow\;\mu_z=\sqrt{\bar\alpha_t}x_0,\;\;\Sigma_z=(1-\bar\alpha_t)I\)Read off the DDPM forward marginal from Quiz 2. Note it is the variance \(1-\bar\alpha_t\) that will enter — the source of the \(\sqrt{1-\bar\alpha_t}\) in the answer and of every distractor built on \(\bar\alpha_t\).
-
\(\displaystyle \mathbb E[\mu|x_t]=x_t+(1-\bar\alpha_t)\nabla_{x_t}\log p(x_t)\)Substitute into Tweedie. The identity matrix drops out since the covariance is isotropic.
-
\(\displaystyle \mathbb E[\mu|x_t]=\sqrt{\bar\alpha_t}\,x_0\;\Rightarrow\;\sqrt{\bar\alpha_t}\,x_0=x_t+(1-\bar\alpha_t)\nabla_{x_t}\log p(x_t)\)The best estimate of the mean is the true mean. Rearranged: \(x_0=\frac{x_t+(1-\bar\alpha_t)\nabla_{x_t}\log p(x_t)}{\sqrt{\bar\alpha_t}}\) — call it the score expression for \(x_0\).
-
\(\displaystyle x_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\,\epsilon_t\;\Rightarrow\;x_0=\frac{x_t-\sqrt{1-\bar\alpha_t}\,\epsilon_t}{\sqrt{\bar\alpha_t}}\)The noise expression for \(x_0\), straight from the definition of the forward process. Two expressions for the same object — so they must agree.
-
\(\displaystyle (1-\bar\alpha_t)\nabla_{x_t}\log p(x_t)=-\sqrt{1-\bar\alpha_t}\,\epsilon_t\;\Longrightarrow\;\nabla_{x_t}\log p(x_t)=-\frac{\epsilon_t}{\sqrt{1-\bar\alpha_t}}\)Equate, cancel \(\sqrt{\bar\alpha_t}\) and \(x_t\), and divide by \(1-\bar\alpha_t\) — one power of the square root survives the cancellation, which is the single most-tested detail in Week 9. So the score is the added noise, negatively scaled: a network trained to regress on \(\epsilon\) is already a score model, \(s_\theta=-\hat\epsilon_\theta/\sqrt{1-\bar\alpha_t}\), which is what makes guidance possible without retraining anything.
Derivation 3 — DPO: eliminating the reward model
-
\(\displaystyle \mathcal L_{\text{policy}}=\mathbb E_{\pi_\theta}\big[r_\phi(x,y)-\beta D_{KL}(\pi_\theta\|\pi_{\text{ref}})\big]\)The RLHF objective: maximise reward while staying near the reference. RLHF solves this with PPO. DPO instead solves it exactly, on paper.
-
\(\displaystyle \pi^*(y|x)=\frac{1}{Z(x)}\pi_{\text{ref}}(y|x)\exp\!\Big(\tfrac{1}{\beta}r_\phi(x,y)\Big),\qquad Z(x)=\sum_y\pi_{\text{ref}}(y|x)e^{r_\phi(x,y)/\beta}\)The closed-form maximiser: the reference distribution exponentially tilted by the reward. Correct but useless on its own — \(Z(x)\) sums over every possible response, so \(\pi^*\) cannot be evaluated or sampled.
-
\(\displaystyle \log\pi^*(y|x)=\log\pi_{\text{ref}}(y|x)+\tfrac{1}{\beta}r_\phi(x,y)-\log Z(x)\)Take logs. The product becomes a sum, and \(Z(x)\) becomes an additive term that depends on \(x\) alone — hold on to that, it is the crux.
-
\(\displaystyle r_\phi^*(x,y)=\beta\log\frac{\pi^*(y|x)}{\pi_{\text{ref}}(y|x)}+\beta\log Z(x)\)The change of variable. Instead of solving for the policy given a reward, solve for the reward given a policy. Every policy implicitly defines one — and note this is the same log-ratio that appears as the RLHF KL penalty in §16.
-
\(\displaystyle p(y_w\succ y_l)=\sigma\big(r^*_\phi(x,y_w)-r^*_\phi(x,y_l)\big)\)Substitute the implicit reward into Bradley–Terry (§16), which depends only on the difference of two rewards.
-
\(\displaystyle r^*_w-r^*_l=\beta\log\frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)}-\beta\log\frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)}+\underbrace{\beta\log Z(x)-\beta\log Z(x)}_{=\,0}\)The intractable partition function cancels exactly, because it depends on \(x\) and both completions share the same \(x\). Maximising the log-likelihood of the observed preferences under this expression is the DPO objective: a plain supervised loss on preference pairs, with no reward model, no roll-outs, no PPO, and four forward passes per pair. The whole method exists because Bradley–Terry never looks at anything but differences.
Formula cheat sheet
Everything you might need to plug numbers into, on one screen.
Score from noise
square root; minus sign; variance not \(\bar\alpha\)
Tweedie
the route to the score identity
Classifier guidance
\(\nabla\log p(x_t)+\nabla\log p(y|x_t)\)
\(\nabla\log p(y)=0\)
Classifier-free guidance
difference first; extrapolates past \(\epsilon_c\)
DDIM sampler (\(\sigma_t=0\))
\(\hat x_0=\frac{x_t-\sqrt{1-\bar\alpha_t}\hat\epsilon_\theta}{\sqrt{\bar\alpha_t}}\)
DDIM \(\eta\)
\(\eta{=}0\) DDIM, \(\eta{=}1\) DDPM
DDPM posterior coefficients
\(c_1+c_2\approx1\) — use as a check
AR factorisation
exact; no ELBO, no gap
Attention
row-wise softmax; \(A\in\mathbb R^{T\times T}\)
Projections
rows = tokens; \((QK^\top)_{ij}=q_i\!\cdot\!k_j\)
Causal mask
added; diagonal kept; row \(i\) has \(i\) survivors
Multi-head
same parameter count as single-head
Parameter counts
output tensor \(=B\times L\times d_m\); \(|A|=N^2\)
LayerNorm
divide by \(d_m\) (biased); per token
Residual + norm
variance grows \(\times(1+c)\) per layer
Sinusoidal PE
odd slots cos; added; fixed, not learned
AR loss
teacher forcing; \(=-\log p_\theta(x)\)
Top-\(k\) / top-\(p\)
always renormalise; top-\(p\) overshoots \(p\)
Beam search
add log-probs; pool across beams; keep top \(k\)
Temperature
\(T<1\) sharper, \(T>1\) flatter
Return & reward-to-go
recurse backwards; discounting restarts at \(t\)
Advantage
\(A^\pi=Q^\pi-V^\pi\); unbiased one-sample estimate
Policy gradient
ascent: \(\theta\leftarrow\theta+\alpha\hat g\)
Baseline identity
state-only baselines are free
Importance sampling
\(r_t=\pi_\theta/\pi_{\theta_{\text{old}}}\), sampled action only
TRPO constraint
average KL, in distribution space
PPO clip
interval closed; inside ⇒ just \(r_tA_t\)
PPO full loss
reward up, value error down, entropy up
Bradley–Terry
\(\mathcal L=-\log\sigma(\Delta)=\log(1+e^{-\Delta})\); \(\Delta{=}0\Rightarrow0.693\)
RLHF reward
ratio \(>1\Rightarrow\) penalty subtracts
DPO optimum & implicit reward
\(Z(x)\) cancels in the difference
DPO objective
gradient weight \(=\sigma(\hat r_l-\hat r_w)\)
SSM discretisation
bilinear: \((I-\tfrac{\Delta}{2}A)^{-1}(I+\tfrac{\Delta}{2}A)\)
SSM kernel
\(\hat K(z)=\bar C(I-\bar Az)^{-1}\bar B\)
Optimal discriminator
"generated" \(=1-D^*\)
GMM responsibility
keep the \(\frac{1}{\sqrt{2\pi\sigma^2}}\); \(\sigma^2\) is the variance
Night-before recall list
Say each one out loud. If any makes you hesitate, jump back to its section.
- DDPM's L2 objective is regression on the added noise
- Score \(=-\epsilon_t/\sqrt{1-\bar\alpha_t}\) — minus, and a square root
- Tweedie: \(\mathbb E[\mu_z|z]=z+\Sigma_z\nabla_z\log p(z)\)
- An \(\epsilon\)-predictor is a score predictor — no retraining needed
- Classifier guidance works because \(\nabla_{x_t}\log p(y)=0\)
- CFG: \(\epsilon_u+s(\epsilon_c-\epsilon_u)\); difference first; it extrapolates
- Training a classifier at all noise levels is why CFG exists
- LDM: same maths, different space; encoder frozen
- DDPM's two flaws: slow sampling, non-unique invertibility
- DDIM: deterministic, non-Markovian, same marginals
- Training is identical for DDPM and DDIM; only inference differs
- \(\sigma_t=0\Rightarrow\) DDIM; DDPM posterior std \(\Rightarrow\) DDPM; \(\eta\) interpolates
- Only randomness in DDIM is \(x_T\) → DDIM inversion
- AR: \(p_\theta(x)=\prod_tp_\theta(x_t|x_{<t})\) — chain rule, exact
- RNN failure mode: vanishing gradients, fixed-size \(h_t\)
- Attention's four steps: similarity, scale, softmax, combine
- Output is a convex combination of value rows
- Scale by \(\sqrt{d_k}\) to stop the softmax saturating
- Rows are tokens; \((QK^\top)_{ij}=q_i\!\cdot\!k_j\)
- Mask is added; \(j\le i\) keeps the diagonal; a score of 0 is not masked
- Softmax only over surviving positions — row \(i\) has \(i\) of them
- Softmax is monotone → "highest/lowest weight" needs no arithmetic
- Two-way softmax \(=\sigma(\text{difference})\)
- Multi-head has the same parameter count as single-head
- \(|A|=N^2\), independent of \(d_k\) — the source of \(O(T^2)\)
- Parameters vs activations: \(D^2+D\) vs \(B\times L\times d_m\)
- FFN supplies the non-linearity; attention alone is linear
- LayerNorm: biased variance, per token, \(\gamma\) after normalising
- Residual streams grow variance geometrically — hence LayerNorm
- PE: even sin, odd cos, added, fixed, geometric wavelengths
- PE encodes relative position as a linear transform
- Teacher forcing + causal mask → parallel training, sequential inference
- Top-\(k\)/top-\(p\) always renormalise; top-\(p\) overshoots
- Beam search adds log-probs and pools across beams
- Log-derivative trick: \(\nabla p_\theta=p_\theta\nabla\log p_\theta\)
- The transition kernel drops out → policy gradient is model-free
- Reward need not be differentiable — that is the point
- \(R_t\) restarts discounting at \(t\); recurse backwards
- State-only baselines are unbiased; action-dependent ones are not
- \(R_t-V^\pi(s_t)\) is an unbiased one-sample advantage
- LM ↔ RL: prefix = state, token = action, LM = policy
- Reward is not the pretraining log-likelihood
- Output dim \(=|V|\); trajectory space \(=|V|^T\)
- Policy gradient is on-policy → importance sampling
- Unbounded ratios explode → TRPO / PPO
- TRPO: average KL, in distribution space, not on \(\theta\)
- PPO: check \(r_t\in[1-\epsilon,1+\epsilon]\) first; interval is closed
- Clip caps the gain on good actions; asymmetric in \(A_t\)
- Two KLs: clip → \(\pi_{\text{old}}\) (stability); \(\beta\) → \(\pi_{\text{ref}}\) (reward hacking)
- Bradley–Terry sees only differences of rewards
- \(-\log\sigma(\Delta)\): positive, decreasing in \(\Delta\), \(0.693\) at \(\Delta=0\)
- RLHF penalty subtracts when \(\pi_\theta>\pi_{\text{ref}}\)
- DPO optimum: \(\pi_{\text{ref}}\) tilted by \(e^{r/\beta}\), intractable \(Z(x)\)
- Invert for the reward, and \(Z(x)\) cancels in the difference
- DPO gradient weight \(=\sigma(\hat r_l-\hat r_w)\); self-annealing; \(0.5\) at indifference
- ZOH: \(\bar A=e^{\Delta A}\); \(A<0\Rightarrow\bar A\in(0,1)\)
- A linear recurrence is a convolution — recurrent and convolutional modes
- S4: diagonal or DPLR \(\bar A\), HiPPO init, frequency domain
- Mamba: input-dependent \((A,B,C)\), no fixed kernel, parallel scan
- Carry-over: \(D^*=\frac{p_d}{p_d+p_g}\), GMM responsibility, \(\beta\)-VAE trade-off
- Zero negative marking — never leave a box empty