Mathematical Foundations of Generative AI

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.

50Marks · GenAI section
16–22Questions / paper
0Negative marking
66%Marks in 2 topics
How to use this. Read top-to-bottom once — the four weeks are one continuous argument, and each section is the previous one pushed a step further. Then treat the ★ High-yield callouts and the example questions (click an option, or "Reveal answer") as your drill deck. Everything marked 2025 T3 FN / 2025 T3 AN / 2026 T1 FN / 2026 T1 AN is a real question from a past end-term, with its official key, and every number in this guide has been recomputed from scratch. The cheat sheet and recall list are your final-hour pages.
00Strategy first

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.

★ The single most useful fact on this page

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)
Shape17 standalone questions, 3–4 marks each22–23 questions, mostly in comprehension clusters of 2–5 sub-questions off one shared setup
Weeks 1–8None. Pure Weeks 9–1213 marks every time — KL, GAN, GMM, \(\beta\)-VAE, ELBO
Week 9 diffusion9 marks — score vector, CFG, DDIMZero. Dropped entirely
RLHF / DPO / SSM12 marks — BT loss, KL-penalised reward, DPO reward, ZOHZero. Stops at PPO
Style of questionBroad and shallow — one idea per question, often a single formula substitutionNarrow and deep — one matrix, then five questions that each need the previous answer
Chief riskA topic you skipped entirelyOne arithmetic slip cascading through a whole cluster
⚠ The comprehension-cluster trap

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.

★ Eight formulas cover the majority of the marks

If you memorise nothing else, memorise these cold:

  1. 1.Scaled dot-product attention: \(A=\mathrm{softmax}\!\big(\tfrac{QK^\top}{\sqrt{d_k}}\big)\), output \(Z=AV\)
  2. 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. 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. 4.Sinusoidal PE: \(\mathrm{PE}(j,2i)=\sin\!\big(j/10000^{2i/d_m}\big)\), \(\mathrm{PE}(j,2i{+}1)=\cos(\cdot)\)
  5. 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. 6.PPO clipped term: \(\min\big(r_tA_t,\;\mathrm{clip}(r_t,1-\epsilon,1+\epsilon)A_t\big)\)
  7. 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. 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)\)
Marks-per-minute triage
  • 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.
⚠ Two errors in the 2025 T3 FN official key — verified against its own AN twin

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.

01Mental model

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:

Week 9diffusion, finished
Week 10autoregressive transformers
Weeks 11–12alignment: RL, RLHF, DPO
ArcThe question it answersThe 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).
The through-line: every week is a change of what you regress on

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.

A notation warning that will save you marks

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.

02Week 9 · foundation

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

Forward marginal, and its inversion \(\displaystyle x_t=\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\epsilon_t,\qquad \epsilon_t\sim\mathcal N(0,I)\)
\(\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):

The two means, in noise coordinates \(\displaystyle \mu_q(x_t,\epsilon_t)=\frac{1}{\sqrt{\alpha_t}}x_t-\frac{1-\alpha_t}{\sqrt{1-\bar\alpha_t}\sqrt{\alpha_t}}\,\epsilon_t\)
\(\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.
The objective, in one line \(\displaystyle \frac{1}{2\sigma_q^2}\|\mu_q-\mu_\theta\|_2^2=\frac{1}{2\sigma_q^2}\frac{(1-\alpha_t)^2}{(1-\bar\alpha_t)\,\alpha_t}\;\big\|\epsilon_t-\hat\epsilon_\theta(x_t)\big\|_2^2\;\propto\;\big\|\epsilon_t-\hat\epsilon_\theta(x_t)\big\|_2^2\) The whole prefactor is a known constant at each \(t\), so it is dropped in practice. What remains is plain L2 regression on the added noise, computed by a U-Net that takes \((x_t,t)\) and outputs a tensor the same shape as \(x_t\).
★ What the U-Net actually is

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.

NAT2025 T2 · Q1295 marks
In a DDPM with \(\bar\alpha_{t-1}=0.95\), \(\bar\alpha_t=0.91\) (so \(\alpha_t=0.9578947\), \(\beta_t=0.0421053\)), compute the posterior mean coefficients \(c_1=\frac{\sqrt{\bar\alpha_{t-1}}\,\beta_t}{1-\bar\alpha_t}\) and \(c_2=\frac{\sqrt{\alpha_t}(1-\bar\alpha_{t-1})}{1-\bar\alpha_t}\).
Reveal answer
\(c_1\approx0.456,\;\; c_2\approx0.544\)

Denominator first: \(1-\bar\alpha_t=0.09\).

\(c_1=\dfrac{\sqrt{0.95}\times0.0421053}{0.09}=\dfrac{0.974679\times0.0421053}{0.09}=\dfrac{0.041039}{0.09}=0.4560\)
\(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.

03★★ 9 marks

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

For any Gaussian \(z\sim\mathcal N(z;\mu_z,\Sigma_z)\) \(\displaystyle \mathbb E[\mu_z\,|\,z]=z+\Sigma_z\,\nabla_z\log p(z)\) \(\nabla_z\log p(z)\) is the score function: the gradient of the log-density with respect to the data, not the parameters. It points "uphill" toward regions of higher probability — which is why following it generates samples.

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:

\(\displaystyle \mathbb E[\mu\,|\,x_t]=x_t+(1-\bar\alpha_t)\nabla_{x_t}\log p(x_t)\)
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}}\)
★ Equate the two expressions for \(x_0\) — the money identity
\(\displaystyle \nabla_{x_t}\log p(x_t)=-\frac{1}{\sqrt{1-\bar\alpha_t}}\;\epsilon_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.

⚠ Three ways to get this wrong
  • 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\).
MCQ2025 T3 AN · Q23 marks
Given \(\nabla_{x_t}\log p_t(x_t)\approx-\frac{1}{\sqrt{1-\bar\alpha_t}}\epsilon_\theta(x_t,t)\), a timestep with \(\bar\alpha_t=0.36\), and a predicted noise vector \(\epsilon_\theta=[0.8,\,-1.6]^\top\), compute the estimated score vector.
  • \([-1.0,\;2.0]^\top\)
  • \([-1.25,\;2.5]^\top\)
  • \([-0.8,\;1.6]^\top\)
  • \([-0.48,\;0.96]^\top\)
Reveal answer
\([-1.0,\;2.0]^\top\)

\(\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.

MCQ2025 T2 · Q1285 marks
In DDPM with \(x_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\,\epsilon\), \(\epsilon\sim\mathcal N(0,I)\), the conditional score \(\nabla_{x_t}\log q(x_t|x_0)\) equals:
  • \(-\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
\(-\frac{1}{\sqrt{1-\bar\alpha_t}}\,\epsilon\)

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

\(\displaystyle \nabla_{x_t}\log q(x_t|x_0)=-\frac{x_t-\sqrt{\bar\alpha_t}x_0}{1-\bar\alpha_t}=-\frac{\sqrt{1-\bar\alpha_t}\,\epsilon}{1-\bar\alpha_t}=-\frac{\epsilon}{\sqrt{1-\bar\alpha_t}}\)

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.

04★★ 6+ marks

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

Take \(\nabla_{x_t}\log\) of Bayes' rule \(\displaystyle \nabla_{x_t}\log p(x_t|y)=\nabla_{x_t}\log\frac{p(x_t)\,p(y|x_t)}{p(y)}=\nabla_{x_t}\log p(x_t)+\nabla_{x_t}\log p(y|x_t)-\underbrace{\nabla_{x_t}\log p(y)}_{=\,0}\) \(p(y)\) has no \(x_t\) in it, so its gradient vanishes. That single cancellation is the whole trick.
\(\displaystyle \underbrace{\nabla_{x_t}\log p(x_t|y)}_{\text{conditional score}}=\underbrace{\nabla_{x_t}\log p(x_t)}_{\text{what the U-Net already gives}}+\underbrace{\nabla_{x_t}\log p(y|x_t)}_{\text{classifier gradient}}\)

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.

⚠ Why classifier guidance is not what people use

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 \nabla\log p(y|x_t)=\nabla\log p(x_t|y)-\nabla\log p(x_t)\)
\(\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.
★ CFG, in the two forms you will be asked for
\(\displaystyle \nabla\log p(x_t|y)=s\,\nabla\log p(x_t|y)+(1-s)\,\nabla\log p(x_t)\)
\(\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.

MCQ2025 T3 AN · Q33 marks
CFG with guidance scale \(s=6.0\). Unconditional prediction \(\epsilon_\theta(x_t|\varnothing)=[0.2,\,0.1]^\top\); conditional prediction \(\epsilon_\theta(x_t|y)=[0.5,\,-0.2]^\top\). Compute the guided noise vector \(\tilde\epsilon\).
  • \([3.2,\;-1.7]^\top\)
  • \([2.0,\;-1.7]^\top\)
  • \([2.0,\;-1.2]^\top\)
  • \([1.8,\;-1.8]^\top\)
Reveal answer
\([2.0,\;-1.7]^\top\)

Always compute the difference vector first — it is the only step where a sign can go wrong.

\(\epsilon_c-\epsilon_u=[0.5-0.2,\;\,-0.2-0.1]^\top=[0.3,\;-0.3]^\top\)
\(\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.

MCQ2025 T2 · Q1315 marks
Classifier-free guidance with DDIM. CFG is compatible with DDIM by:
  • 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
Replacing \(\epsilon_\theta\) by \(\epsilon_u+w(\epsilon_c-\epsilon_u)\) before each DDIM step

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.

05Week 9 · concept

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.

Train \(E_\phi,D_\theta\)e.g. a VQ-VAE
Project \(z_0=E_{\phi^*}(x_0)\)freeze the autoencoder
DDPM on \(z\)-spacetrain diffusion here
Decode \(x=D_{\theta^*}(z_{\text{novel}})\)sample

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.

★ Why this matters — the three-point answer
  1. 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. 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. 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.
06★★★ asked every T3 paper

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\):

The \(\sigma\)-family \(\displaystyle q_\sigma(x_{1:T}|x_0)\triangleq q_\sigma(x_T|x_0)\prod_{t=2}^{T}q_\sigma(x_{t-1}|x_t,x_0)\)
\(\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}\).
★ The main result — and why you get DDIM for free

Every member of this family is constructed to have the same marginal as DDPM:

\(\displaystyle q_\sigma(x_t|x_0)=\mathcal N\big(x_t;\sqrt{\bar\alpha_t}\,x_0,\;(1-\bar\alpha_t)I\big)\qquad\text{for every }\sigma\)

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\)

General \(\sigma\)-sampler, with \(z\sim\mathcal N(0,I)\) \(\displaystyle x_{t-1}=\sqrt{\bar\alpha_{t-1}}\underbrace{\left(\frac{x_t-\sqrt{1-\bar\alpha_t}\,\hat\epsilon_\theta}{\sqrt{\bar\alpha_t}}\right)}_{\text{predicted }\hat x_0}+\sqrt{1-\bar\alpha_{t-1}-\sigma_t^2}\;\hat\epsilon_\theta+\sigma_t\,z\) Three parts: point at the predicted clean image, re-add the right amount of the noise direction, inject fresh noise. The whole DDIM story is what happens to the third part.
Choice of \(\sigma_t\)What you getCharacter
\(\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 exactlyStochastic, Markovian
\(\sigma_t=0\) for all \(t\)DDIMDeterministic, 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
The DDIM sampler (\(\sigma_t=0\)) — memorise this shape \(\displaystyle x_{t-1}=\sqrt{\bar\alpha_{t-1}}\left(\frac{x_t-\sqrt{1-\bar\alpha_t}\,\hat\epsilon_\theta}{\sqrt{\bar\alpha_t}}\right)+\sqrt{1-\bar\alpha_{t-1}}\;\hat\epsilon_\theta\) No \(z\) anywhere. The only randomness in the entire generation is the initial draw \(x_T\sim\mathcal N(0,I)\) — so the map \(x_T\mapsto x_0\) is a deterministic function, hence invertible. That is DDIM inversion: run the deterministic map backwards to recover the unique latent code of a real image, which is what makes latent-space editing possible.
Where the speed-up actually comes from

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.

MCQ2025 T3 FN · Q10  &  2025 T3 AN · Q103 marks each
DDIMs are faster than DDPM mainly because:
  • 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
The sampling process is deterministic when \(\sigma_t=0\)

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).

MCQ2025 T2 · Q1305 marks
DDIM with \(\eta=0\) updates \(x_{t-1}=\sqrt{\bar\alpha_{t-1}}\,\hat x_0+\sqrt{1-\bar\alpha_{t-1}}\,\hat\epsilon\), where \(\hat x_0\) is from \((x_t,\hat\epsilon)\). This sampler is:
  • Deterministic and non-Markovian but matches \(q(x_t|x_0)\) marginals
  • Stochastic and Markovian
  • Identical to DDPM (\(\eta=1\))
  • Invalid
Reveal answer
Deterministic and non-Markovian but matches \(q(x_t|x_0)\) marginals

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.

MCQ2025 T2 · Q1885 marks
General \(\eta\) noise scale in DDIM. The injected noise variance per step is:
  • \(\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
\(\sigma_\eta^2=\eta^2\tilde\beta_t\)

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\).

07Week 10 · foundation

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:

\(\displaystyle \theta^*=\arg\min_\theta D_{KL}(p_x\|p_\theta)=\arg\max_\theta\;\mathbb E_{p_x}\log p_\theta(x)\) Identical to the first move of Quiz 2. The entropy of \(p_x\) carries no \(\theta\), so it drops.
★ The autoregressive factorisation
\(\displaystyle p_\theta(x)=p_\theta(x_1,x_2,\dots,x_T)=\prod_{t=1}^{T}p_\theta(x_t\,|\,x_{<t}),\qquad x_{<t}=\{x_1,\dots,x_{t-1}\}\)

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

ModelHow \(p_\theta(x_t|x_{<t})\) is computedFatal 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 learnableLinear, 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.
TransformerAttention over all previous tokens at once, with causal maskingCost 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.

MCQ2025 T2 · Q1375 marks
An AR-LM can be viewed as an MDP by:
  • State = token prefix, action = next token
  • State = next token, action = prefix
  • State = vocabulary, action = logits
  • Impossible
Reveal answer
State = token prefix, action = next token

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.

08★★★ the single biggest topic

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:

Queries, keys, values \(Q=XW^Q,\quad K=XW^K,\quad V=XW^V\)
\(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

For one query \(q\in\mathbb R^{d_k}\) against all keys \(\textbf{1. Similarity: }\; s_i=q^\top k_i,\qquad s=q^\top K^\top\in\mathbb R^{1\times T}\)
\(\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.
★ What the attention output is

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.

Why divide by \(\sqrt{d_k}\) — the answer they want

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.

SA2026 T1 FN · Q9–10 (comprehension)3 + 3 marks
A sequence of length \(T=3\) is \(X=\begin{bmatrix}2&1&0\\1&0&2\\0&2&1\end{bmatrix}\) (rows are tokens), with \(W_Q=\begin{bmatrix}1&1\\0&1\\1&0\end{bmatrix}\), \(W_K=\begin{bmatrix}1&0\\1&1\\0&1\end{bmatrix}\), \(W_V=\begin{bmatrix}1&0\\0&1\\1&1\end{bmatrix}\), \(d_k=2\), scaling by \(\sqrt2\).
(a) Let the scaled scores for query \(q_2\) be \(\big[\tfrac{q_2^\top k_1}{\sqrt{d_k}},\tfrac{q_2^\top k_2}{\sqrt{d_k}},\tfrac{q_2^\top k_3}{\sqrt{d_k}}\big]\). Compute its \(L_2\) norm (2 d.p.).   (b) Compute the attention output vector for the second token.
Reveal answer
(a) 10.15   |   (b) \([1.70,\;1.67]\)

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.

\(Q=XW_Q=\begin{bmatrix}2&3\\3&1\\1&2\end{bmatrix},\qquad K=XW_K=\begin{bmatrix}3&1\\1&2\\2&3\end{bmatrix},\qquad V=XW_V=\begin{bmatrix}2&1\\3&2\\1&3\end{bmatrix}\) Check one entry by hand: \(Q_{11}=2(1)+1(0)+0(1)=2\). \(K_{23}\)? Row 2 of \(X\) is \((1,0,2)\), column 2 of \(W_K\) is \((0,1,1)\), so \(K_{22}=0+0+2=2\). ✓

(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=\big[\tfrac{10}{\sqrt2},\tfrac{5}{\sqrt2},\tfrac{9}{\sqrt2}\big]=[7.0711,\;3.5355,\;6.3640]\)
\(\|\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:

\(e^{0}=1,\quad e^{-3.5355}=0.0291,\quad e^{-0.7071}=0.4931\quad\Rightarrow\quad\text{sum}=1.5222\)
\(\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.

SA2026 T1 AN · Q11–13 (comprehension)2 + 2 + 3 marks
\(T=3\), \(X=\begin{bmatrix}1&2&0\\0&1&1\\2&0&1\end{bmatrix}\), \(W_Q=\begin{bmatrix}1&0\\0&1\\1&1\end{bmatrix}\), \(W_K=\begin{bmatrix}1&1\\0&1\\1&0\end{bmatrix}\), \(W_V=\begin{bmatrix}1&0\\1&1\\0&1\end{bmatrix}\), \(d_k=2\). For the first query use \(e^{2.121}\approx8.339\), \(e^{4.950}\approx141.175\).
(a) Which token receives the lowest attention score from \(q_1\) before scaling?   (b) The attention weight on token 3 for query 1 (3 d.p.).   (c) The sum of the first and second coordinates of the attention output for query 1 (2 d.p.).
Reveal answer
(a) Token 2   |   (b) 0.486   |   (c) 3.97

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.

\(Q=XW_Q=\begin{bmatrix}1&2\\1&2\\3&1\end{bmatrix},\qquad K=XW_K=\begin{bmatrix}1&3\\1&1\\3&2\end{bmatrix},\qquad V=XW_V=\begin{bmatrix}3&2\\1&2\\2&1\end{bmatrix}\)

(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.

\(\text{sum}=141.175+8.339+141.175=290.689\)
\(\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.

SA2025 T3 FN · Q13  &  2025 T3 AN · Q133 marks each
Single-head self-attention with \(d_k=4\), sequence length \(L=2\). FN: \(Q=\begin{bmatrix}1&0&2&1\\0&1&0&2\end{bmatrix}\), \(K=\begin{bmatrix}1&0&1&0\\0&2&0&1\end{bmatrix}\).    AN: \(Q=\begin{bmatrix}2&1&0&1\\1&0&3&1\end{bmatrix}\), \(K=\begin{bmatrix}1&2&0&1\\0&1&1&0\end{bmatrix}\).
Compute the raw scores scaled by \(1/\sqrt{d_k}\). What is the element at position \((1,2)\) of the scaled score matrix?
Reveal answer
0.5 in both papers

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{FN: }(1,0,2,1)\cdot(0,2,0,1)=0+0+0+1=1,\qquad 1/2=0.5\)
\(\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.

09★★★ in every recent paper

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 mask, and where it goes \(\displaystyle M_{ij}=\begin{cases}0,&j\le i\\[2pt] -\infty,&j>i\end{cases}\qquad\qquad A_m=\mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)\) Element-wise addition, not multiplication. Since \(e^{-\infty}=0\), every masked position gets attention weight exactly zero, and the surviving weights renormalise to sum to 1. Row \(i\) therefore has exactly \(i\) non-zero entries: row 1 attends to 1 token, row 4 to all 4.
★ The diagonal is not masked — and the three-step procedure

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. 1.Take row \(i\). The query index is the row. Not the column.
  2. 2.Keep the first \(i\) entries, set the rest to \(-\infty\). Nothing else changes — the surviving values keep their original numbers.
  3. 3.Softmax over the survivors only. The denominator is a sum of \(i\) terms, not \(T\). This is the step people get wrong.
MCQ + SA2026 T1 FN · Q11–12 (comprehension)1 + 3 marks
A decoder with sequence length 4 has pre-mask scaled score matrix \(S=\begin{bmatrix}3&1&2&0\\2&4&1&3\\1&0&3&2\\2&1&0&4\end{bmatrix}\), with \(M_{ij}=0\) for \(j\le i\) and \(-\infty\) otherwise. Use \(e^0=1,\;e^1=2.718,\;e^2=7.389,\;e^3=20.085,\;e^4=54.598\).
(a) Which is the masked score vector for the third query?   (b) For token 4, compute the attention probability assigned jointly to positions 1 and 2 (3 d.p.).
  • \([1,\;0,\;3,\;-\infty]\)
  • \([1,\;0,\;3,\;2]\)
  • \([-\infty,\;0,\;3,\;2]\)
  • \([1,\;-\infty,\;3,\;2]\)
Reveal answer
(a) \([1,\,0,\,3,\,-\infty]\)   |   (b) 0.154

(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.

\(\text{denominator}=e^2+e^1+e^0+e^4=7.389+2.718+1+54.598=65.705\)
\(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.

SA2026 T1 AN · Q14–16 (comprehension)1 + 2 + 3 marks
Pre-mask scaled scores \(S=\begin{bmatrix}4&1&0&2\\2&3&1&0\\1&2&4&3\\0&1&2&5\end{bmatrix}\), same causal mask, with \(e^5=148.413\) also supplied.
(a) For token 3, the attention probability assigned to position 4.   (b) Which position receives the highest attention weight for token 4?   (c) Compute \(\dfrac{p(\text{token 3}\to\text{position 3})}{p(\text{token 2}\to\text{position 1})}\) (3 d.p.).
Reveal answer
(a) 0   |   (b) Position 4   |   (c) 3.137

(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 3 masked}=[1,2,4,-\infty]:\quad p(3\to3)=\dfrac{e^4}{e^1+e^2+e^4}=\dfrac{54.598}{64.705}=0.84381\)
\(\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.

SA2025 T3 FN · Q143 marks
In a decoder-only (GPT-style) transformer, raw scores for \(L=3\) are \(S=\begin{bmatrix}2.0&1.0&0.5\\1.0&2.0&1.0\\0.5&1.0&2.0\end{bmatrix}\) and \(M\) sets future positions to \(-\infty\). Compute \(P(\text{attend to }t{=}2\mid\text{current }t{=}2)\) after softmaxing the second row.
Reveal answer
0.731

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]\).

\(P(t{=}2)=\dfrac{e^{2}}{e^{1}+e^{2}}=\dfrac{7.389}{2.718+7.389}=\dfrac{7.389}{10.107}=0.7311\)

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.

10★★★ 12+ marks

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

\(h\) heads, each on a slice of the model dimension \(\text{Typically }\;d_k=d_m/h\)
\(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.
★ Multi-head attention is free — the answer to the recurring MCQ

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:

\(\displaystyle h\times\frac{d_m^2}{h}=d_m^2\quad\text{per projection type, for any }h\)

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.

The counting recipe — three questions to ask
  1. 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. 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. 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.
MCQ + SA2026 T1 AN · Q7–8 (comprehension)3 + 2 marks
In self-attention each input vector has dimension \(D\); queries, keys and values are computed by separate linear transformations each mapping \(\mathbb R^D\to\mathbb R^D\). There are \(N\) input vectors.
(a) How many learnable parameters (weights and biases) compute the queries, keys and values?   (b) How many attention weights \(a[i,j]\) are computed in total if \(N=100\) and \(D=16\)?
  • \(3D^2\)
  • \(3D^2+3D\)
  • \(D^2+D\)
  • \(6D^2\)
Reveal answer
(a) \(3D^2+3D\)   |   (b) 10,000

(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.

MCQ2026 T1 FN · Q72 marks
For a fixed input size and embedding dimension \(D\), consider standard multi-head attention where the embedding dimension is evenly split across heads. Select the correct statement:
  • 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
An equal number

"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.

SA2025 T3 AN · Q143 marks
A transformer with \(d_{\text{model}}=512\) uses \(h=8\) parallel heads, concatenated and projected by \(W^O\). With batch size \(B=32\) and sequence length \(L=50\), how many floating-point elements are in the final output tensor of the multi-head attention block (before the residual connection)?
Reveal answer
819,200

This asks about an activation, not a parameter count — so \(B\) and \(L\) matter and \(h\) does not.

\(B\times L\times d_{\text{model}}=32\times50\times512=819{,}200\)

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\).

MCQ2025 T2 · Q134  &  Q1915 marks each
(a) What is the output projection size of \(W_O\), given \(d_{\text{model}}=768\), \(h=12\), \(d_k=64\)?   (b) In single-head self-attention with \(d_{\text{model}}=512\), if all four projection matrices \(W_Q,W_K,W_V,W_O\in\mathbb R^{512\times512}\) are used (weights only, no bias), how many trainable parameters do they contain in total?
Reveal answer
(a) \(768\times768=589{,}824\)   |   (b) 1,048,576

(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.

11★★★ 20+ marks

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

Applied to each position independently \(\mathrm{FFN}(z_j)=\big[\sigma(z_jW_1+b_1)\big]W_2+b_2,\qquad W_1\in\mathbb R^{d_m\times d_f},\;W_2\in\mathbb R^{d_f\times d_m}\) Everything in the attention block — projections, the weighted sum, the output mix — is linear. Without the FFN, a stack of attention layers would collapse to one linear map. \(\sigma\) is ReLU or tanh, and the same \(W_1,W_2\) are shared across all \(T\) positions. Finally the output layer projects to vocabulary size: \(\tilde z_j=\hat z_jW_p+b_p\in\mathbb R^{|V|}\) with \(W_p\in\mathbb R^{d_m\times|V|}\), and \(\hat y_j=\mathrm{softmax}(\tilde z_j)\).

Residual connections and LayerNorm

The pattern, applied around every sublayer \(\mathrm{output}=\mathrm{LayerNorm}\big(\underbrace{x+\mathrm{sublayer}(x)}_{\text{residual}}\big)\)
\(\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.
⚠ Three LayerNorm details that decide the mark
  • 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.
MCQ + SA2026 T1 FN · Q13–14 (comprehension)4 + 3 marks
A transformer block with \(d_m=4\) and two heads (\(d_k=2\)) produces concatenated output \(z_c=[2,1,1,3]\). The sublayer output is \(y=\mathrm{LayerNorm}(u)\) with \(u=x+z_cW^C\), where \(W^C=\begin{bmatrix}1&0&1&0\\0&1&0&1\\1&0&0&1\\0&1&1&0\end{bmatrix}\), residual input \(x=[1,2,0,1]\), \(\gamma=[1,2,1,1]\), \(\beta=[0,1,0,-1]\), \(\epsilon=0\).
(a) Find the mean and variance of \(u\).   (b) Compute the second coordinate of the final layer-normalised output (3 d.p.).
  • 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
(a) Mean 4.5, Variance 1.25   |   (b) 3.683

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 1: }2(1)+1(0)+1(1)+3(0)=3\)
\(\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.

\(\mu=\dfrac{4+6+5+3}{4}=\dfrac{18}{4}=4.5\)
\(\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\):

\(y_2=\gamma_2\dfrac{u_2-\mu}{\sqrt{\sigma^2+\epsilon}}+\beta_2=2\cdot\dfrac{6-4.5}{1.11803}+1=2(1.34164)+1=3.6833\)

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.

MCQ2025 T2 · Q192, Q193, Q1355 marks each
(a) \(x=(2,0,-2,0)\), \(\gamma=1\), \(\beta=0\), \(\epsilon\to0\). Compute \(\mathrm{LN}(x)\).   (b) \(x=(1,2,3)\) with mean 2, var \(\tfrac23\), std \(\approx0.8165\), \(\gamma=(1,2,0.5)\), \(\beta=0\). Compute \(\mathrm{LN}(x)\).   (c) \(x=(2,0)\), \(\mathrm{LN}(x)=(1,-1)\), sublayer \(f\) is the identity. What is \(y=x+f(\mathrm{LN}(x))\)?
Reveal answer
(a) \((\tfrac{2}{\sqrt2},0,-\tfrac{2}{\sqrt2},0)\)  |  (b) \((-1.225,\,0,\,0.612)\)  |  (c) \((3,-1)\)

(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\):

\(\big(1(-1.2247),\;2(0),\;0.5(1.2247)\big)=(-1.225,\;0,\;0.612)\)

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.

MCQ2025 T3 FN · Q4  &  2025 T3 AN · Q43 marks each
In a deep transformer with residual connections, layer \(l\) outputs \(x_l=x_{l-1}+F(x_{l-1})\). At initialisation \(F\) outputs values with variance \(\approx0.1\times\mathrm{Var}(x_{l-1})\). After 10 layers, assuming independence, roughly how much has the signal variance increased relative to \(\mathrm{Var}(x_0)\)? (Use \(\mathrm{Var}(A+B)\approx\mathrm{Var}(A)+\mathrm{Var}(B)\).)
  • 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
It doubles \((2\times)\) — keyed identically in both papers

Under the stated independence approximation each layer multiplies the variance by \(1.1\):

\(\mathrm{Var}(x_l)\approx\mathrm{Var}(x_{l-1})+0.1\,\mathrm{Var}(x_{l-1})=1.1\,\mathrm{Var}(x_{l-1})\)
\(\Rightarrow\;\mathrm{Var}(x_{10})\approx1.1^{10}\,\mathrm{Var}(x_0)=2.594\,\mathrm{Var}(x_0)\)
⚠ Read this one carefully — two options are defensible

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:

Sinusoidal encoding: \(j\) = position, \(i\) = embedding-dimension index \(\displaystyle \mathrm{PE}(j,2i)=\sin\!\left(\frac{j}{10000^{2i/d_m}}\right),\qquad \mathrm{PE}(j,2i+1)=\cos\!\left(\frac{j}{10000^{2i/d_m}}\right)\)
\(\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.
MCQ2026 T1 AN · Q17–18 (comprehension)4 + 2 marks
For a token at position \(j=3\) the base embedding is \(x=[2,1,0,2]\), with \(d_m=4\) and \(i:0\to3\). Use \(\sin3\approx0.141\), \(\cos3\approx-0.990\), \(\sin0.03\approx0.03\), \(\cos0.03\approx0.9996\).
(a) Compute \(\tilde x=x+\mathrm{PE}(3)\).   (b) Which statement about adding \(\mathrm{PE}\) to \(x\) is true?
  • \([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
(a) \([2.14,\,0.01,\,0.03,\,3.00]\)   |   (b) It adds position information while preserving embedding dimensionality

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:

SlotFormulaArgument \(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.

MSQ2025 T3 FN · Q12  &  2025 T3 AN · Q124 marks each
Based on the properties of sinusoidal positional encodings, identify all correct statements:
  • 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
All except the first

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.

12★★ 6+ marks

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

Shift the sequence by one \(\text{Input tokens: }\{x_1,x_2,\dots,x_{T-1}\}\qquad\text{Target tokens: }\{x_2,x_3,\dots,x_T\}\)
\(\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.
Why causal masking makes training parallel

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

StrategyRuleCharacter
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)}\), sampleTruncates the tail with a fixed count
Top-\(p\) (nucleus)Take the smallest set of top tokens whose cumulative mass \(\ge p\), renormalise, sampleAdaptive: 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.

MCQ2025 T3 FN · Q5  &  2025 T3 AN · Q53 marks each
Beam search with width \(k=2\). At step \(t\): Beam A \(=-0.7\) (ending 'hello'), Beam B \(=-1.2\) (ending 'hi'). At step \(t+1\): given 'hello' → 'world' \((-0.3)\), 'there' \((-1.0)\); given 'hi' → 'there' \((-0.2)\), 'you' \((-0.6)\). Which two paths form the new beams?
  • ('hello','world') and ('hello','there')
  • ('hello','world') and ('hi','there')
  • ('hi','there') and ('hi','you')
  • ('hello','there') and ('hi','you')
Reveal answer
('hello','world') and ('hi','there')

Score all four candidates, then take the top two. Nothing else.

PathAccumulated + stepScoreRank
('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.

MCQ2025 T2 · Q132  &  Q1905 marks each
(a) Top-\(k\): given probabilities \((0.5,\tfrac13,\tfrac16)\) with \(k=2\), keep the top 2 and renormalise. What does \(P_1\) become?   (b) Top-\(p\): given sorted probabilities \((0.5,0.2,0.15,0.1,0.05)\) and \(p=0.9\), find the minimal nucleus size \(|S_p|\), then the renormalised probability of the 4th token.
Reveal answer
(a) 0.6   |   (b) Size 4, prob \(\approx0.105\)

(a) Keep \(0.5\) and \(\tfrac13\); the surviving mass is \(0.5+\tfrac13=\tfrac56\). So

\(P_1=\dfrac{0.5}{5/6}=\dfrac{1}{2}\cdot\dfrac{6}{5}=0.6\)

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

\(P_4'=\dfrac{0.1}{0.95}=0.1053\)

"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.

13★★★ 30+ marks

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

The six-tuple \((S,A,P,r,\gamma,\rho)\) \(S\): state space  ·  \(A\): action space  ·  \(p(s_{t+1}|s_t,a_t)\): transition kernel
\(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)\).
Trajectory distribution, return, and the objective \(\displaystyle p_\theta(\tau)=\rho(s_0)\prod_{t=0}^{\infty}\pi_\theta(a_t|s_t)\,p(s_{t+1}|s_t,a_t)\)
\(\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 \nabla_\theta p_\theta(\tau)=p_\theta(\tau)\,\nabla_\theta\log p_\theta(\tau)\) A trivial identity (\(\nabla\log f=\nabla f/f\)) with a large consequence: it converts \(\nabla\!\int p_\theta R\) back into an expectation under \(p_\theta\), which can be estimated from sampled roll-outs.
And the transition kernel disappears \(\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)\)
\(\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.
★ The theorem, and its two refinements
\(\displaystyle \nabla_\theta J(\theta)=\mathbb E_{\tau\sim p_\theta}\left[\sum_{t=0}^{\infty}\nabla_\theta\log\pi_\theta(a_t|s_t)\;R(\tau)\right]\)

Refinement 1 — reward-to-go. An action at time \(t\) cannot affect rewards already collected, so replace the whole-trajectory return by

\(\displaystyle R_t\triangleq\sum_{k=0}^{\infty}\gamma^k r(s_{t+k},a_{t+k}),\qquad\text{note }R(\tau)=R_0\)

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 \nabla_\theta J(\theta)=\mathbb E\left[\sum_{t}\nabla_\theta\log\pi_\theta(a_t|s_t)\big[R_t-V^\pi(s_t)\big]\right]\)
\(\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 V^\pi(s_t)=\mathbb E_\pi\Big[\textstyle\sum_{k\ge0}\gamma^k r(s_k,a_k)\;\Big|\;s_0=s_t\Big]\)  —  expected return from a state
\(\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
Why \(R_t-V^\pi(s_t)\) is an unbiased estimate of the advantage

Condition on \((s_t,a_t)\) and take expectations:

\(\mathbb E\big[R_t-V^\pi(s_t)\,\big|\,s_t,a_t\big]=\underbrace{\mathbb E[R_t|s_t,a_t]}_{=\,Q^\pi(s_t,a_t)}-V^\pi(s_t)=A^\pi(s_t,a_t)\)

\(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.

★ Why a baseline is allowed at all — the expected-score-is-zero identity
\(\displaystyle \mathbb E_{a\sim\pi}\big[\nabla_\theta\log\pi_\theta(a|s)\cdot b(s)\big]=b(s)\sum_a\pi_\theta(a|s)\frac{\nabla_\theta\pi_\theta(a|s)}{\pi_\theta(a|s)}\)
\(\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.

MCQ2025 T3 FN · Q9  &  2025 T3 AN · Q93 marks each
The policy gradient theorem states \(\nabla J(\theta)=\mathbb E[\nabla\log\pi(a|s)A(s,a)]\). Introducing a baseline \(b(s)\) makes the term \(\nabla\log\pi(a|s)\big(Q(s,a)-b(s)\big)\). What is the expected value of the baseline term \(\mathbb E_{a\sim\pi}\big[\nabla_\theta\log\pi(a|s)\cdot b(s)\big]\)?
  • \(b(s)\)
  • \(0\)
  • \(1.0\)
  • \(\nabla_\theta b(s)\)
Reveal answer
\(0\)

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.

SA2026 T1 FN · Q15–17 (comprehension)2 + 2 + 3 marks
A language model generates a response of length 4 with rewards \(r_0=2,\;r_1=-1,\;r_2=3,\;r_3=4\) and \(\gamma=0.9\). State values \(V^\pi=[5.0,\,4.0,\,6.2,\,4.0]\); log-policy gradient scalars \(g=[0.5,\,-0.2,\,0.4,\,0.1]\).
(a) The full discounted return \(R(\tau)=r_0+\gamma r_1+\gamma^2r_2+\gamma^3r_3\) (3 d.p.).   (b) The reward-to-go \(R_1\) (2 d.p.).   (c) \(\hat g=\sum_{t=0}^{3}g_t\hat A_t\) where \(\hat A_t=R_t-V^\pi(s_t)\) (3 d.p.).
Reveal answer
(a) 6.446   |   (b) 4.94   |   (c) 0.695

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\)
34\(4.000\)4.0\(0.000\)0.1\(0.000\)
23\(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\)
02\(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.

SA2026 T1 AN · Q9–10 (comprehension)2 + 3 marks
Rewards \(r_0=3,\;r_1=1,\;r_2=-2,\;r_3=5\), \(\gamma=0.8\), values \(V^\pi=[4.5,\,2.0,\,1.5,\,5.0]\), scalars \(g=[0.4,\,0.3,\,-0.2,\,0.1]\).
(a) The full discounted return (2 d.p.).   (b) \(\hat g=\sum_t g_t\hat A_t\) with \(\hat A_t=R_t-V^\pi(s_t)\) (3 d.p.).
Reveal answer
(a) 5.08   |   (b) 0.312

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\)
35\(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\)
11\(1+0.8(2)=2.60\)2.0\(0.60\)0.3\(0.180\)
03\(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.

MCQ2025 T2 · Q136  &  Q1945 marks each
(a) Given rewards \(r_1=1,\;r_2=0,\;r_3=2\) and \(\gamma=0.9\), compute \(G_1\) in the case of reward models.   (b) In the policy gradient theorem, which is correct for episodic \(J(\theta)\)?
Reveal answer
(a) 2.62   |   (b) \(\nabla J=\mathbb E_{s\sim d^\pi,a\sim\pi}\big[\nabla_\theta\log\pi_\theta(a|s)\,Q^\pi(s,a)\big]\)

(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.

14★★★ 7 marks/paper in T3

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.

★ The LM ↔ RL dictionary
RL objectLM objectDetail
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 emittedAction space is the vocabulary \(V\)
Trajectory \(\tau\)The full (prompt, generated tokens) sequenceOne roll-out = one complete response
Transition \(p(s_{t+1}|s_t,a_t)\)String concatenationDeterministic — 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 endNot the pretraining log-likelihood — that is the recurring wrong option
MSQ2025 T3 FN · Q11  &  2025 T3 AN · Q114 marks each
An AR language model predicts \(x_t\) given history \(x_{<t}\). In the RL interpretation used for alignment, which correspondences are correct?
  • 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
All except the reward statement

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.

MCQ2025 T3 FN · Q7  &  2025 T3 AN · Q73 marks each
Treating an AR-LM as an RL policy with state = context and action space = vocabulary \(V\). With \(|V|=32000\) and generated length \(T=25\), what is the dimension of the policy's output distribution at a single timestep, and the dimensionality of the full trajectory space?
  • 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
Output dim 32000; trajectory space \(32000^{25}\)

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.

15★★★ 8 marks/paper in T1

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

Compute an expectation under \(p\) using samples from \(q\) \(\displaystyle \mathbb E_{x\sim p}\big[f(x)\big]=\int p(x)f(x)\frac{q(x)}{q(x)}dx=\mathbb E_{x\sim q}\!\left[\frac{p(x)}{q(x)}f(x)\right]\) Multiply and divide by \(q\) — structurally the same move that produced the ELBO in Quiz 2. The ratio \(p/q\) reweights each sample to correct for having drawn it from the wrong distribution.

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 importance-sampling surrogate \(\displaystyle L_{\mathrm{IS}}(\theta)=\mathbb E_{\pi_{\theta_{\text{old}}}}\!\left[\frac{\pi_\theta(a_t|s_t)}{\pi_{\theta_{\text{old}}}(a_t|s_t)}\,A_t\right]=\mathbb E_{\pi_{\theta_{\text{old}}}}\big[r_t(\theta)A_t\big]\) It can be verified that \(\nabla_\theta L(\theta)=\nabla_\theta J(\theta)\) at \(\theta=\theta_{\text{old}}\) — so optimising the surrogate is policy gradient at the point where you collected the data, and now you may take several steps on one batch.
⚠ Why you cannot just maximise \(L_{\mathrm{IS}}\)

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

\(\displaystyle L_{\mathrm{TRPO}}(\theta)=\mathbb E_{\pi_{\theta_{\text{old}}}}\big[r_t\,A_t\big]\qquad\text{subject to}\qquad \mathbb E_{s\sim\rho}\Big[D_{KL}\big(\pi_{\theta_{\text{old}}}(\cdot|s)\,\|\,\pi_\theta(\cdot|s)\big)\Big]\le\delta\) Three things to notice, all examined: the constraint is an expectation over states (an average KL), not a per-state maximum; it is on the KL itself, not its square; and it is a distributional divergence, not a Euclidean distance on \(\theta\).
MCQ2025 T3 FN · Q8  &  2025 T3 AN · Q83 marks each
TRPO maximises the surrogate objective subject to a constraint on the KL divergence between the old and new policies. What is the nature of this constraint?
  • \(\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
The average KL, \(\mathbb E_{s\sim\rho}[D_{KL}]\le\delta\)

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:

The PPO clipped surrogate — the most-computed formula in the bank \(\displaystyle L_{\mathrm{PPO}}(\theta)=\mathbb E_{\pi_{\theta_{\text{old}}}}\Big[\min\big(r_t A_t,\;\mathrm{clip}(r_t,1-\epsilon,1+\epsilon)\,A_t\big)\Big],\qquad r_t=\frac{\pi_\theta(a_t|s_t)}{\pi_{\theta_{\text{old}}}(a_t|s_t)}\) \(\epsilon\) is small (0.1 or 0.2). No explicit KL is ever computed.
★ How to evaluate the clipped term in ten seconds

Do not reason about the \(\min\) in the abstract. Mechanically:

  1. 1.Compute \(r_t=\pi_\theta/\pi_{\text{old}}\) for the sampled action only.
  2. 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. 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.

SA2026 T1 FN · Q18–22 (comprehension)1+2+2+2+1 marks
Three time steps from a sampled response. Sampled-action probabilities under the old and updated policies, with estimated advantages: \(\pi_{\text{old}}=[0.20,\,0.50,\,0.10]\), \(\pi_\theta=[0.26,\,0.40,\,0.14]\), \(A=[1.5,\,-0.8,\,2.0]\), PPO clipping with \(\epsilon=0.2\) so the range is \([0.8,1.2]\).
(a) \(r_0\) (1 d.p.)   (b) clipped contribution at \(t{=}0\) (1 d.p.)   (c) at \(t{=}1\) (2 d.p.)   (d) at \(t{=}2\) (1 d.p.)   (e) the total over the three steps (2 d.p.)
Reveal answer
(a) 1.3  |  (b) 1.8  |  (c) −0.64  |  (d) 2.4  |  (e) 3.56

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\)
00.200.261.3no, too high1.21.51.951.801.80
10.500.400.8yes, at the edge0.8−0.8−0.64−0.64−0.64
20.100.141.4no, too high1.22.02.802.402.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.

SA2026 T1 AN · Q19–23 (comprehension)1+2+1+2+2 marks
Two sampled states, with full action distributions over two actions. State 1: \(\pi_{\text{old}}=[0.30,0.70]\), \(\pi_\theta=[0.36,0.64]\). State 2: \(\pi_{\text{old}}=[0.60,0.40]\), \(\pi_\theta=[0.48,0.52]\). The sampled action was the first in both states; \(A_1=1.8\), \(A_2=-1.5\), \(\epsilon=0.2\). Given \(\ln(0.8333)\approx-0.182\), \(\ln(1.09375)\approx0.090\), \(\ln(1.25)\approx0.223\), \(\ln(0.7692)\approx-0.262\).
(a) Sampled-action ratio, state 1   (b) clipped PPO contribution, state 1 (2 d.p.)   (c) ratio, state 2   (d) clipped contribution, state 2 (1 d.p.)   (e) \(D_{KL}(\pi_{\text{old}}\|\pi_\theta)\) for state 1 (4 d.p.)
Reveal answer
(a) 1.2  |  (b) 2.16  |  (c) 0.8  |  (d) −1.2  |  (e) 0.0080

(a)–(d) The full distributions are given, but the ratio uses only the sampled action — the first component:

\(r_1=\dfrac{0.36}{0.30}=1.2\;\in[0.8,1.2]\;\Rightarrow\;\text{contribution}=1.2\times1.8=2.16\)
\(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:

\(D_{KL}(\pi_{\text{old}}\|\pi_\theta)=\displaystyle\sum_a\pi_{\text{old}}(a)\log\frac{\pi_{\text{old}}(a)}{\pi_\theta(a)}\)
\(=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.

MCQ2025 T2 · Q1955 marks
In PPO the clipped surrogate limits large policy updates by comparing the unclipped term \(rA\) with a clipped counterpart restricting \(r\) to \([1-\epsilon,1+\epsilon]\). Given \(r=0.85\), \(\epsilon=0.2\), \(A=-1.0\), find the value.
  • \(-0.85\)
  • \(-0.80\)
  • \(-0.20\)
  • \(-1.00\)
Reveal answer
\(-0.85\)

\(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)

What is actually minimised in practice \(\displaystyle L_{\mathrm{PPO\text{-}full}}(\theta)=-L_{\mathrm{PPO}}(\theta)+\alpha\,\mathbb E\big[(V_\theta(s_t)-R_t)^2\big]-\beta\,\mathbb E\big[\mathcal H(\pi_\theta)\big]\) Three terms: the negated clipped surrogate (so this is a minimisation); a value-function regression loss training \(V_\theta\) toward the observed returns, which is what supplies the baseline; and an entropy bonus \(\mathcal H(\pi_\theta)\) that is subtracted, i.e. entropy is rewarded, to discourage premature collapse onto one token. \(\theta^*_{\mathrm{ppo}}=\arg\min_\theta L_{\mathrm{PPO\text{-}full}}\).
The sign audit for this expression

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.

16★★ 12 marks in T3

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:

Bradley–Terry — and why it collapses to a sigmoid \(\displaystyle p(y_w\succ y_l)=\frac{e^{r_\phi(x,y_w)}}{e^{r_\phi(x,y_w)}+e^{r_\phi(x,y_l)}}=\sigma\big(r_\phi(x,y_w)-r_\phi(x,y_l)\big),\qquad \sigma(t)=\frac{1}{1+e^{-t}}\) Divide numerator and denominator by \(e^{r_w}\): \(\frac{1}{1+e^{-(r_w-r_l)}}\). Only the difference of rewards matters — the reward is identified only up to an additive constant, which is exactly why an absolute human score is unnecessary.
Train \(r_\phi\) by maximum likelihood on the comparisons \(\displaystyle \mathcal L_{\text{reward}}=\mathbb E_{(x,y_w,y_l)}\Big[\log\sigma\big(r_\phi(x,y_w)-r_\phi(x,y_l)\big)\Big],\qquad \phi^*=\arg\max_\phi \mathcal L_{\text{reward}}\) Papers usually state the per-pair negative log-likelihood to be minimised: \(\mathcal L=-\log\sigma(r_w-r_l)\). Read which sign the question wants.
SA2025 T3 FN · Q16  &  2025 T3 AN · Q163 marks each
Training a reward model with Bradley–Terry. FN: \(r(x,y_w)=1.8\), \(r(x,y_l)=0.7\).  AN: \(r(x,y_w)=2.5\), \(r(x,y_l)=1.0\). Compute \(\mathcal L=-\log\sigma(r_w-r_l)\).
Reveal answer
FN: 0.287   |   AN: 0.201

Take the difference first — it is the only input.

\(\text{FN: }\Delta=1.8-0.7=1.1,\quad \sigma(1.1)=\dfrac{1}{1+e^{-1.1}}=\dfrac{1}{1.3329}=0.7503\)
\(\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:

The per-token reward actually fed to PPO \(\displaystyle R(x,y)=r_\phi(x,y)-\beta\log\frac{\pi_\theta(y|x)}{\pi_{\text{ref}}(y|x)}\) Equivalently \(\mathcal L_{\text{policy}}=\mathbb E_{\pi_\theta}\big[r_\phi(x,y)-\beta D_{KL}(\pi_\theta\|\pi_{\text{ref}})\big]\) in expectation. \(\beta\) trades reward against staying close to the reference: large \(\beta\) = conservative, small \(\beta\) = aggressive and hack-prone.
Two KL penalties, two different jobs — do not conflate them

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.
SA2025 T3 FN · Q15  &  2025 T3 AN · Q153 marks each
In RLHF the reward is \(R(x,y)=r_\phi(x,y)-\beta\log\frac{\pi_\theta(y|x)}{\pi_{\text{ref}}(y|x)}\). FN: \(r_\phi=2.5\), \(\pi_\theta=0.8\), \(\pi_{\text{ref}}=0.2\), \(\beta=0.5\), use \(\ln4\approx1.4\).   AN: \(r_\phi=1.8\), \(\pi_\theta=0.6\), \(\pi_{\text{ref}}=0.3\), \(\beta=0.4\), use \(\ln2\approx0.69\). Compute the total reward.
Reveal answer
FN: 1.8   |   AN: 1.524

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{FN: }R=2.5-0.5\ln\!\frac{0.8}{0.2}=2.5-0.5\ln4=2.5-0.5(1.4)=2.5-0.7=1.8\)
\(\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.

17★★ 6 marks in T3

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:

\(\displaystyle \mathcal L_{\text{policy}}=\mathbb E_{\pi_\theta}\Big[r_\phi(x,y)-\beta D_{KL}\big(\pi_\theta\,\|\,\pi_{\text{ref}}\big)\Big],\qquad \pi^*=\arg\max_\pi \mathcal L_{\text{policy}}\)

Step 1 — the closed-form optimum

This objective has an exact solution \(\displaystyle \pi^*(y|x)=\frac{1}{Z(x)}\,\pi_{\text{ref}}(y|x)\,\exp\!\left(\frac{1}{\beta}r_\phi(x,y)\right)\)
\(\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 \log\pi^*(y|x)=\log\pi_{\text{ref}}(y|x)-\log Z(x)+\frac{1}{\beta}r_\phi(x,y)\)
\(\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

★ The DPO objective

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:

\(\displaystyle \pi_\theta^*=\arg\max_\theta\;\mathbb E_{(x,y_w,y_l)}\left[\log\sigma\!\left(\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)}\right)\right]\)

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.

MCQ2025 T3 FN · Q63 marks
DPO eliminates the explicit reward model by defining an implicit reward \(r^*(x,y)\) from the optimal policy \(\pi^*\) and reference policy \(\pi_{\text{ref}}\). Given \(\pi^*(y|x)=0.5\), \(\pi_{\text{ref}}(y|x)=0.05\) and \(\beta=0.1\), calculate the implicit reward.
  • \(0.10\)
  • \(0.23\)
  • \(0.45\)
  • \(1.00\)
Reveal answer
\(0.23\)

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):

\(r^*=0.1\ln\!\frac{0.5}{0.05}=0.1\ln10=0.1(2.3026)=0.2303\)

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.

MCQ2025 T3 AN · Q63 marks
The gradient of the DPO loss is scaled by a weight \(w\) depending on the model's current confidence: \(\nabla_\theta L_{\mathrm{DPO}}=-\sigma(\hat r_l-\hat r_w)\big[\nabla\log\pi(y_w)-\nabla\log\pi(y_l)\big]\). The term \(\sigma(\hat r_l-\hat r_w)\) is the estimated probability that the loser is better than the winner (the error probability). If the implicit reward for the winner is 4.0 and for the loser is 4.0 (the model is indifferent), what is the gradient scaling factor?
  • \(0.0\)
  • \(0.5\)
  • \(1.0\)
  • Undefined
Reveal answer
\(0.5\)

\(\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.

18★ 6 marks in T3

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

Continuous-time SSM (with \(D\) dropped, since a skip connection realises it) \(x'(t)=Ax(t)+Bu(t)\)
\(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)\).
MethodDiscretised parametersWhere 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
The discrete recurrence — a seq-to-seq map through the state \(x_k=\bar Ax_{k-1}+\bar Bu_k,\qquad y_k=\bar Cx_k\)
SA2025 T3 FN · Q17  &  2025 T3 AN · Q173 marks each
A continuous-time SSM has scalar state parameter \(A\) (representing decay), discretised with step size \(\Delta\) by ZOH: \(\bar A=\exp(\Delta A)\). FN: \(A=-3.0\), \(\Delta=0.25\).  AN: \(A=-2.0\), \(\Delta=0.5\). Compute \(\bar A\).
Reveal answer
FN: 0.472   |   AN: 0.368
\(\text{FN: }\bar A=e^{0.25\times(-3.0)}=e^{-0.75}=0.4724\)
\(\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:

\(x_0=\bar Bu_0,\quad x_1=\bar A\bar Bu_0+\bar Bu_1,\quad x_2=\bar A^2\bar Bu_0+\bar A\bar Bu_1+\bar Bu_2,\;\dots\)
\(\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\).
★ The SSM convolutional kernel — the key structural fact
\(\displaystyle \bar K=\big(\bar C\bar B,\;\bar C\bar A\bar B,\;\bar C\bar A^2\bar B,\;\dots,\;\bar C\bar A^{L-1}\bar B\big)\in\mathbb R^L,\qquad y=\bar K*u\)

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

\(\displaystyle \hat K_L(z)=\bar C\,(I-\bar Az)^{-1}\bar B\) One matrix inverse instead of \(L\) powers. Its cost then depends entirely on the structure imposed on \(\bar A\).
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 learnableThe 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 initialisationIn 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.

★ Mamba: selective state-space models

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:

\(x_{k+1}=A(u_k)\,x_k+B(u_k)\,u_k,\qquad y_k=C(u_k)\,x_k\)

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.

19★★ 13 marks/paper in T1

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.

Slot2026 T1 FN2026 T1 ANMarks
1KL divergence properties (MSQ)Numeric \(D_{KL}(P\|Q)\) over a small discrete space2
2GAN properties (MSQ)GAN vs VAE: encoders and blurriness (MSQ)2–3
3Optimal discriminator, numericELBO term-by-term reasoning (MSQ)3
4GMM responsibility, numericOptimal discriminator, numeric2–3
5\(\beta\)-VAE: effect of increasing \(\beta\)GMM responsibility, numeric3

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.

★ The two formulas that carry these marks
\(\displaystyle D^*(x)=\frac{p_{\text{data}}(x)}{p_{\text{data}}(x)+p_g(x)}\qquad\qquad \gamma(z_k)=\frac{\pi_k\,\mathcal N(x;\mu_k,\sigma_k^2)}{\sum_j\pi_j\,\mathcal N(x;\mu_j,\sigma_j^2)}\)

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.

SA2026 T1 FN · Q4  &  2026 T1 AN · Q53 + 2 marks
(a) FN: A GAN's training set has three times as many car images as bike images. The generator has learned to produce only high-quality car images, indistinguishable from real ones. \(D\) outputs the probability that an input is real. What is the optimal output of \(D\) given a car image? (2 d.p.)
(b) AN: For a data point \(x\), \(p_{\text{data}}(x)=\tfrac14\) and \(p_G(x)=\tfrac34\). What probability does \(D^*\) assign to \(x\) being generated? (2 d.p.)
Reveal answer
(a) 0.43   |   (b) 0.75

(a) is the harder of the two, because you must read the densities out of a word problem.

\(p_{\text{data}}(\text{car})=\tfrac{3}{3+1}=0.75,\qquad p_g(\text{car})=1\)
\(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.

SA2026 T1 FN · Q5  &  2026 T1 AN · Q63 marks each
A GMM has two components with priors \(\pi_1,\pi_2\) and 1-D Gaussian parameters. Compute the responsibility \(\gamma(z_1)\) of component \(C_1\) for the data point \(x\) (3 d.p.).
FN: \(\pi_1=0.7,\pi_2=0.3\); \(\mu_1=2,\sigma_1^2=1\); \(\mu_2=6,\sigma_2^2=9\); \(x=4\).    AN: \(\pi_1=0.6,\pi_2=0.4\); \(\mu_1=5,\sigma_1^2=1\); \(\mu_2=10,\sigma_2^2=4\); \(x=7\).
Reveal answer
FN: 0.542   |   AN: 0.556

Compute the two weighted densities, then divide. Do not normalise anything early.

\(\text{FN: }\pi_1\mathcal N_1=0.7\cdot\dfrac{1}{\sqrt{2\pi}}e^{-\frac{(4-2)^2}{2}}=0.7(0.39894)e^{-2}=0.037794\)
\(\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\)
\(\text{AN: }\pi_1\mathcal N_1=0.6(0.39894)e^{-\frac{4}{2}}=0.6(0.05399)=0.032395\)
\(\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.

MSQ2026 T1 AN · Q3–43 + 3 marks
(a) Which statements are correct?   (b) For the VAE ELBO \(\mathbb E_{q_\phi(z|x)}[\log p_\theta(x|z)]-D_{KL}(q_\phi(z|x)\|p(z))\), which statements are correct?
  • 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
Options 1, 3, 5 (the AN key also credits "ignoring the KL term makes \(z\) deterministic parameters")

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.

MCQ2026 T1 FN · Q63 marks
In a \(\beta\)-VAE with loss \(\mathcal L=\text{Reconstruction Loss}+\beta\cdot\text{KL Divergence}\) and prior \(\mathcal N(0,I)\), as \(\beta\) increases from 0, what happens to the learned latent representations?
  • \(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
\(q_\phi(z|x)\) approaches \(\mathcal N(0,I)\) but reconstructions become worse

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.

20Understand, don't memorise

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

Prove \(\displaystyle \nabla_\theta J(\theta)=\mathbb E_{\tau\sim p_\theta}\Big[\textstyle\sum_t\nabla_\theta\log\pi_\theta(a_t|s_t)\,A^{\pi_\theta}(s_t,a_t)\Big]\)
  1. \(\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.
  2. \(\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.
  3. \(\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.
  4. \(\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.
  5. \(\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\).
  6. \(\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.
  7. \(\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.
  8. \(\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.
  9. \(\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.

Derivation 2 — the score identity via Tweedie's formula

Prove \(\displaystyle \nabla_{x_t}\log p(x_t)=-\frac{1}{\sqrt{1-\bar\alpha_t}}\,\epsilon_t\)
  1. \(\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.
  2. \(\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\).
  3. \(\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.
  4. \(\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\).
  5. \(\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.
  6. \(\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

Prove \(\displaystyle \pi_\theta^*=\arg\max_\theta\mathbb E\left[\log\sigma\!\left(\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)}\right)\right]\)
  1. \(\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.
  2. \(\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.
  3. \(\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.
  4. \(\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.
  5. \(\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.
  6. \(\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.
21Final hour

Formula cheat sheet

Everything you might need to plug numbers into, on one screen.

Score from noise
\(\nabla_{x_t}\log p(x_t)=-\frac{\epsilon_t}{\sqrt{1-\bar\alpha_t}}\)

square root; minus sign; variance not \(\bar\alpha\)

Tweedie
\(\mathbb E[\mu_z|z]=z+\Sigma_z\nabla_z\log p(z)\)

the route to the score identity

Classifier guidance
\(\nabla\log p(x_t|y)=\)
\(\nabla\log p(x_t)+\nabla\log p(y|x_t)\)

\(\nabla\log p(y)=0\)

Classifier-free guidance
\(\tilde\epsilon=\epsilon_u+s(\epsilon_c-\epsilon_u)\)

difference first; extrapolates past \(\epsilon_c\)

DDIM sampler (\(\sigma_t=0\))
\(x_{t-1}=\sqrt{\bar\alpha_{t-1}}\hat x_0+\sqrt{1-\bar\alpha_{t-1}}\,\hat\epsilon_\theta\)

\(\hat x_0=\frac{x_t-\sqrt{1-\bar\alpha_t}\hat\epsilon_\theta}{\sqrt{\bar\alpha_t}}\)

DDIM \(\eta\)
\(\sigma_\eta^2=\eta^2\tilde\beta_t\)

\(\eta{=}0\) DDIM, \(\eta{=}1\) DDPM

DDPM posterior coefficients
\(c_1=\frac{\sqrt{\bar\alpha_{t-1}}\beta_t}{1-\bar\alpha_t},\;c_2=\frac{\sqrt{\alpha_t}(1-\bar\alpha_{t-1})}{1-\bar\alpha_t}\)

\(c_1+c_2\approx1\) — use as a check

AR factorisation
\(p_\theta(x)=\prod_{t=1}^{T}p_\theta(x_t|x_{<t})\)

exact; no ELBO, no gap

Attention
\(A=\mathrm{softmax}\!\big(\frac{QK^\top}{\sqrt{d_k}}\big),\;Z=AV\)

row-wise softmax; \(A\in\mathbb R^{T\times T}\)

Projections
\(Q=XW^Q,\;K=XW^K,\;V=XW^V\)

rows = tokens; \((QK^\top)_{ij}=q_i\!\cdot\!k_j\)

Causal mask
\(M_{ij}=0\;(j\le i),\;-\infty\;(j>i)\)

added; diagonal kept; row \(i\) has \(i\) survivors

Multi-head
\(d_k=d_m/h,\;\;h\cdot\frac{d_m^2}{h}=d_m^2\)

same parameter count as single-head

Parameter counts
\(D\to D\text{ layer}=D^2+D\)

output tensor \(=B\times L\times d_m\); \(|A|=N^2\)

LayerNorm
\(\gamma\odot\frac{x-\mu}{\sqrt{\sigma^2+\epsilon}}+\beta\)

divide by \(d_m\) (biased); per token

Residual + norm
\(\mathrm{LayerNorm}(x+\mathrm{sublayer}(x))\)

variance grows \(\times(1+c)\) per layer

Sinusoidal PE
\(\mathrm{PE}(j,2i)=\sin\!\big(\frac{j}{10000^{2i/d_m}}\big)\)

odd slots cos; added; fixed, not learned

AR loss
\(\mathcal L=-\sum_{t}\log\hat y_{t,x_t}\)

teacher forcing; \(=-\log p_\theta(x)\)

Top-\(k\) / top-\(p\)
\(p_k(v_i)=\frac{p(v_i)}{\sum_{j\le k}p(v_j)}\)

always renormalise; top-\(p\) overshoots \(p\)

Beam search
\(\text{score}=\sum_t\log p_t\)

add log-probs; pool across beams; keep top \(k\)

Temperature
\(\hat y=\mathrm{softmax}(z/T)\)

\(T<1\) sharper, \(T>1\) flatter

Return & reward-to-go
\(R_t=r_t+\gamma R_{t+1},\quad R(\tau)=R_0\)

recurse backwards; discounting restarts at \(t\)

Advantage
\(\hat A_t=R_t-V^\pi(s_t)\)

\(A^\pi=Q^\pi-V^\pi\); unbiased one-sample estimate

Policy gradient
\(\hat g=\sum_t\nabla_\theta\log\pi_\theta(a_t|s_t)\,\hat A_t\)

ascent: \(\theta\leftarrow\theta+\alpha\hat g\)

Baseline identity
\(\mathbb E_{a\sim\pi}[\nabla\log\pi(a|s)\,b(s)]=0\)

state-only baselines are free

Importance sampling
\(\mathbb E_p[f]=\mathbb E_q\big[\frac{p}{q}f\big]\)

\(r_t=\pi_\theta/\pi_{\theta_{\text{old}}}\), sampled action only

TRPO constraint
\(\mathbb E_{s\sim\rho}\big[D_{KL}(\pi_{\text{old}}\|\pi_\theta)\big]\le\delta\)

average KL, in distribution space

PPO clip
\(\min\big(r_tA_t,\,\mathrm{clip}(r_t,1{-}\epsilon,1{+}\epsilon)A_t\big)\)

interval closed; inside ⇒ just \(r_tA_t\)

PPO full loss
\(-L_{\mathrm{PPO}}+\alpha\mathbb E(V_\theta-R_t)^2-\beta\mathbb E\mathcal H(\pi_\theta)\)

reward up, value error down, entropy up

Bradley–Terry
\(p(y_w\succ y_l)=\sigma(r_w-r_l)\)

\(\mathcal L=-\log\sigma(\Delta)=\log(1+e^{-\Delta})\); \(\Delta{=}0\Rightarrow0.693\)

RLHF reward
\(R=r_\phi-\beta\log\frac{\pi_\theta}{\pi_{\text{ref}}}\)

ratio \(>1\Rightarrow\) penalty subtracts

DPO optimum & implicit reward
\(\pi^*\propto\pi_{\text{ref}}e^{r/\beta},\quad r^*=\beta\log\frac{\pi^*}{\pi_{\text{ref}}}\)

\(Z(x)\) cancels in the difference

DPO objective
\(\log\sigma\!\big(\beta\log\frac{\pi_\theta(y_w)}{\pi_{\text{ref}}(y_w)}-\beta\log\frac{\pi_\theta(y_l)}{\pi_{\text{ref}}(y_l)}\big)\)

gradient weight \(=\sigma(\hat r_l-\hat r_w)\)

SSM discretisation
\(\bar A=\exp(\Delta A)\)  (ZOH)

bilinear: \((I-\tfrac{\Delta}{2}A)^{-1}(I+\tfrac{\Delta}{2}A)\)

SSM kernel
\(\bar K=(\bar C\bar B,\bar C\bar A\bar B,\dots),\;y=\bar K*u\)

\(\hat K(z)=\bar C(I-\bar Az)^{-1}\bar B\)

Optimal discriminator
\(D^*(x)=\frac{p_{\text{data}}}{p_{\text{data}}+p_g}\)

"generated" \(=1-D^*\)

GMM responsibility
\(\gamma(z_k)=\frac{\pi_k\mathcal N_k}{\sum_j\pi_j\mathcal N_j}\)

keep the \(\frac{1}{\sqrt{2\pi\sigma^2}}\); \(\sigma^2\) is the variance

22Night before

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

GenAI End-Term Study Guide. Built from the Week 9–12 lecture notes, the instructor's handwritten note sets (Part 8: DDIMs, Part 9: AR Models), and all six past end-term papers (2025 T2 FN/AN, 2025 T3 FN/AN, 2026 T1 FN/AN). Every example question is reproduced from those sources with its official answer key, and every number in this guide was recomputed independently — all 22 scored answers in each 2026 T1 paper reproduce exactly. Where a paper's key is inconsistent with the taught formula — the 2025 T3 FN Q2 score vector and Q3 CFG second coordinate, both verified against the arithmetically clean AN twins — the discrepancy is flagged in place so you trust the method rather than a possibly-typo'd number. Good luck.

© 2026 Pulkit Mangal  ·  github.com/PulkitMangal09  ·  All study guides