MoonSay /Tutorials/Machine Learning Interview #6
Contents
  1. 01Introduction
  2. 02Two ways to learn
  3. 03Bayes’ theorem
  4. 04What generative models create
  5. 05What discriminative models do
  6. 06Who wins? Small data versus big data
  7. 07Beyond accuracy
  8. 08Side by side
  9. 09Interview questions and model answers
  10. 10Summary
  11. References

04What generative models create

A model of p(x) is far more than a classifier: sampling from it creates new data. Modern generative models differ mainly in how they turn a simple source of randomness into a sample. We look at four classic ideas, and at real pictures for two of them.

4.1Text and sound, one piece at a time

Any distribution over a sequence x=(x_1,\dots,x_T), of words or audio samples, can be written exactly by applying the product rule repeatedly:

p(x_1,\dots,x_T)=p(x_1)\,p(x_2\mid x_1)\,p(x_3\mid x_1,x_2)\cdots=\prod_{t=1}^Tp(x_t\mid x_{<t}). \tag{10}

An autoregressive model learns each factor, the distribution of the next piece given everything before it. Taking the logarithm, the maximum likelihood objective is \sum_t\log p(x_t\mid x_{<t}), so training is next-word (next-token) prediction with the cross-entropy loss. To generate, sample x_1, then x_2 given x_1, and so on. Shannon (1948) did exactly this with letter and word statistics; GPT, the generative pre-trained transformer, is such a model built from a neural network (Radford et al., 2018). WaveNet uses the same factorization (10) for raw audio (van den Oord et al., 2016), where a second of sound has at least 16{,}000 samples, each predicted from the ones before. A video model has to keep frames consistent over time, which is why video generation is harder still.

4.2Diffusion models: learn to remove noise

The forward process. A diffusion model starts from the opposite direction: it destroys data, step by step, by adding Gaussian noise, and learns to undo it (Sohl-Dickstein et al., 2015; Ho et al., 2020). With a noise schedule \beta_1,\dots,\beta_T and \alpha_t=1-\beta_t, each forward step is

x_t=\sqrt{\alpha_t}\,x_{t-1}+\sqrt{1-\alpha_t}\,\epsilon_t,\qquad \epsilon_t\sim\mathcal N(0,I), \tag{11}

where here x_0 is the clean picture and x_T is pure noise. The forward process has no parameters; nothing is learned in it.

Jumping to any step in one go. Two steps of (11) give

x_t=\sqrt{\alpha_t\alpha_{t-1}}\,x_{t-2}+\Big(\sqrt{\alpha_t(1-\alpha_{t-1})}\,\epsilon_{t-1}+\sqrt{1-\alpha_t}\,\epsilon_t\Big).

The bracket is a sum of two independent zero-mean Gaussians, hence Gaussian with variance \alpha_t(1-\alpha_{t-1})+(1-\alpha_t)=1-\alpha_t\alpha_{t-1}. Repeating the argument down to x_0 (induction on t), with \bar\alpha_t=\prod_{s=1}^t\alpha_s:

x_t=\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\epsilon,\qquad\epsilon\sim\mathcal N(0,I), \tag{12}

that is, q(x_t\mid x_0)=\mathcal N(\sqrt{\bar\alpha_t}\,x_0,(1-\bar\alpha_t)I) (Ho et al., 2020, eq. 4). The picture fades as \sqrt{\bar\alpha_t} while the noise grows as \sqrt{1-\bar\alpha_t}, Figure 5(a). Ho et al. (2020) use T=1000 steps with \beta_t increasing linearly from 10^{-4} to 0.02; then \bar\alpha_T=4.0\times10^{-5}, so only \sqrt{\bar\alpha_T}=0.6\% of the picture is left and x_T is, for all purposes, pure noise.

Training: predict the noise. A neural network \epsilon_\theta(x_t,t) is trained to tell which noise was added. Pick a training picture x_0, a step t and a noise \epsilon, form x_t by (12), and minimize

L_{\text{simple}}(\theta)=\mathbb E_{x_0,\,t,\,\epsilon}\Big\|\epsilon-\epsilon_\theta\big(\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\epsilon,\;t\big)\Big\|^2 \tag{13}

(Ho et al., 2020, eq. 14). This is plain least-squares regression; Ho et al. (2020) obtain it as a simplified form of the maximum likelihood (variational) bound. Knowing the noise is the same as knowing the picture: rearranging (12) gives the model’s current guess of the clean picture,

\hat x_0=\frac{x_t-\sqrt{1-\bar\alpha_t}\,\epsilon_\theta(x_t,t)}{\sqrt{\bar\alpha_t}}. \tag{14}

Sampling: run it backwards. Start from pure noise x_T\sim\mathcal N(0,I) and remove a little predicted noise at each step,

x_{t-1}=\frac1{\sqrt{\alpha_t}}\Big(x_t-\frac{1-\alpha_t}{\sqrt{1-\bar\alpha_t}}\,\epsilon_\theta(x_t,t)\Big)+\sigma_t z,\qquad z\sim\mathcal N(0,I), \tag{15}

for t=T,\dots,1 (with z=0 in the last step) (Ho et al., 2020, Alg. 2). With 1000 network evaluations per picture this is slow; deterministic samplers such as DDIM produce good pictures in far fewer steps, 10 to 50 times faster in wall-clock time (Song et al., 2021a). On unconditional CIFAR-10 images, Ho et al. (2020) reported a Fréchet inception distance (FID) of 3.17, then the best published value.

Diffusion on real pictures. (a) The forward process (12) applied to a picture, for decreasing \bar\alpha (cosine schedule). (b) Stable Diffusion v1.4 (Rombach et al., 2022), sampled in 50 deterministic steps (Song et al., 2021a): the state x_t after selected steps and the model’s guess \hat x_0 of the clean picture, (14). The model works in a compressed latent space; each picture shows the decoder’s view of it. Computed for this tutorial; the same pictures as in the companion video.
Figure 5. Diffusion on real pictures. (a) The forward process (12) applied to a picture, for decreasing \bar\alpha (cosine schedule). (b) Stable Diffusion v1.4 (Rombach et al., 2022), sampled in 50 deterministic steps (Song et al., 2021a): the state x_t after selected steps and the model’s guess \hat x_0 of the clean picture, (14). The model works in a compressed latent space; each picture shows the decoder’s view of it. Computed for this tutorial; the same pictures as in the companion video.

Figure 5(b) shows a real model at work. The state x_t looks like static for most of the run, but the guess \hat x_0 forms early and coarse to fine: after one step an orange blob, after five a blurry cat, after ten the pose and the window, and the remaining steps add fur and detail. Large text-to-image systems run the same process in a compressed latent space, conditioned on the prompt: latent diffusion (Rombach et al., 2022).

4.3Flow matching: straight lines from noise to data

The path. Flow matching (Lipman et al., 2023) and the closely related rectified flow (Liu et al., 2023) replace the noise schedule by the simplest possible path. In their convention t runs from 0 (noise) to 1 (data). Pair a noise sample x_0\sim\mathcal N(0,I) with a data point x_1 and move along the straight line

x_t=(1-t)\,x_0+t\,x_1,\qquad \frac{dx_t}{dt}=x_1-x_0. \tag{16}

The velocity along each line is constant: every point moves straight to its partner at constant speed. Figure 6(c) shows the path between a noise image and a picture.

Training: regress the velocity. A network v_\theta(x,t) learns the velocity field by least squares on random pairs and times,

L_{\text{FM}}(\theta)=\mathbb E_{t\sim U[0,1],\,x_0,\,x_1}\big\|v_\theta(x_t,t)-(x_1-x_0)\big\|^2. \tag{17}

Many lines pass through the same point x at time t, with different directions. What does the network learn there? For any random target Z and input X, \mathbb E\|f(X)-Z\|^2=\mathbb E\|f(X)-\mathbb E[Z\mid X]\|^2+\mathbb E\|Z-\mathbb E[Z\mid X]\|^2 (the cross term vanishes because Z-\mathbb E[Z\mid X] has mean zero given X), so the least-squares optimum is the conditional mean:

v^\star(x,t)=\mathbb E\big[x_1-x_0\;\big|\;x_t=x\big], \tag{18}

the average direction of all lines through x at time t. Lipman et al. (2023) and Liu et al. (2023) show that following this averaged field, dx/dt=v^\star(x,t), carries the noise distribution exactly to the data distribution. Lipman et al. also show that diffusion paths are a special, curved case of their framework, and that straight (optimal-transport) paths train faster and sample with fewer steps.

Sampling: follow the arrows. Start from noise and take Euler steps, x_{t+h}=x_t+h\,v_\theta(x_t,t). In the two-moons example of Figure 6, 170 noise points are paired with 170 data points so that the lines do not cross, a velocity field is fitted to the lines, and 28 new noise points reach the moons in only 4 Euler steps (median distance to the nearest data point 0.07). Stable Diffusion 3 is trained with this rectified-flow objective (Esser et al., 2024).

Flow matching. (a) Training pairs on two-moons data: noise samples x_0 (grey) are paired with data points x_1 (blue) so that the lines do not cross (60 of 170 lines shown). (b) The learned velocity at t=0.5 (arrows) and 28 new samples carried from noise to the moons in 4 Euler steps. (c) The straight path (16) between a noise image and a picture. Computed for this tutorial, with the same data as the companion video.
Figure 6. Flow matching. (a) Training pairs on two-moons data: noise samples x_0 (grey) are paired with data points x_1 (blue) so that the lines do not cross (60 of 170 lines shown). (b) The learned velocity at t=0.5 (arrows) and 28 new samples carried from noise to the moons in 4 Euler steps. (c) The straight path (16) between a noise image and a picture. Computed for this tutorial, with the same data as the companion video.

4.4Why straight paths need fewer steps

Euler’s method assumes that the velocity stays constant over a step. Its error per step is about \tfrac12h^2\,\|\ddot x\|, where \ddot x=d^2x/dt^2 is the acceleration: it grows with the curvature of the path. On a straight path traversed at constant speed, \ddot x=0, and one step is exact. Diffusion’s paths, by contrast, bend: written as an ordinary differential equation, the probability-flow ODE of Song et al. (2021b), a sample hardly moves at first and then turns sharply towards the data near the end.

Figure 7 computes this exactly in one dimension, with data from two narrow Gaussians at \pm1.5 and closed-form velocities. The diffusion trajectories (a) are flat and then bend; the flow-matching trajectories (b) are much straighter; and if each noise point is paired with the endpoint of its own trajectory, the paths become exactly straight (c), the “reflow” idea of Liu et al. (2023). With equal Euler steps, panel (d), flow matching’s error is less than half of diffusion’s with two to four steps (0.118 against 0.307 with four), while with many steps both converge and the difference disappears (0.008 and 0.006 with 64). The advantage is in the few-step regime, exactly where speed matters.

Curved and straight paths from noise to data, for data from two Gaussians at \pm1.5 (standard deviation 0.2, shaded) and Gaussian noise. (a) Trajectories of the diffusion probability-flow ODE (variance-preserving, \beta from 0.1 to 20). (b) Trajectories of flow matching with the straight path (16). (c) Straight lines from each noise point to the endpoint of its trajectory in (b). (d) Mean distance between Euler’s endpoint and the exact one, against the number of equal steps. Computed for this tutorial.
Figure 7. Curved and straight paths from noise to data, for data from two Gaussians at \pm1.5 (standard deviation 0.2, shaded) and Gaussian noise. (a) Trajectories of the diffusion probability-flow ODE (variance-preserving, \beta from 0.1 to 20). (b) Trajectories of flow matching with the straight path (16). (c) Straight lines from each noise point to the endpoint of its trajectory in (b). (d) Mean distance between Euler’s endpoint and the exact one, against the number of equal steps. Computed for this tutorial.
Try itCurved paths need more steps

The same example as Figure 7: Euler's method with equal steps on the diffusion probability-flow ODE (left) and on flow matching (right). Grey lines are the exact trajectories, coloured lines Euler's approximation. Change the number of steps and compare where the samples land.

One step of plain flow matching is a special case worth remembering. At t=0 the noise x_0 tells nothing about its partner x_1, so (18) gives v^\star(x,0)=\mathbb E[x_1]-x, and a single Euler step sends every sample to the data mean \mathbb E[x_1] (here 0): with images, one blurry average picture. Paired, non-crossing lines remove this problem, which is why rectified flows can sample in one or a few steps (Liu et al., 2023).

4.5Generative adversarial networks: a painter and a critic, trained together

A generative adversarial network (Goodfellow et al., 2014) puts the painter and the critic of Section 1 in one system. A generator G turns noise z into a sample G(z); a discriminator D(x)\in(0,1) is a binary classifier that outputs the probability that x is real. They play the two-player game

\min_G\max_D\;V(D,G)=\mathbb E_{x\sim p_{\text{data}}}[\log D(x)]+\mathbb E_{z\sim p_z}[\log(1-D(G(z)))]. \tag{19}

The optimal critic. For a fixed generator with sample density p_g,

V(D,G)=\int\big[p_{\text{data}}(x)\log D(x)+p_g(x)\log(1-D(x))\big]\,dx.

The function y\mapsto a\log y+b\log(1-y) has derivative a/y-b/(1-y), which vanishes at y=a/(a+b), so pointwise

D^\star(x)=\frac{p_{\text{data}}(x)}{p_{\text{data}}(x)+p_g(x)} \tag{20}

(Goodfellow et al., 2014, Prop. 1). This is Bayes’ theorem (2) for the two classes “real” and “fake” with equal priors: the best discriminator is the exact posterior p(\text{real}\mid x). Inserting D^\star gives V=-\log4+2\,\mathrm{JSD}(p_{\text{data}}\,\|\,p_g), where JSD is the Jensen–Shannon divergence, so the generator’s best move is p_g=p_{\text{data}}, where D^\star=\tfrac12 everywhere (Goodfellow et al., 2014, Thm. 1). A GAN is a generative model; its discriminator is a discriminative model used as a training signal and thrown away afterwards.

4.6Four families side by side

How it generatesTraining objectiveSteps per sample
Autoregressiveone piece at a time, (10)next-piece cross-entropy (exact likelihood)one per word or audio sample
Diffusionremoves noise step by step, (15)predict the added noise, (13)many (1000; tens with fast samplers)
Flow matchingfollows a velocity field, Euler stepsregress the velocity x_1-x_0, (17)few (straighter paths)
GANone pass of the generatoradversarial game with a discriminator, (19)one
Table 2. Classic families of generative models. Sources: Shannon (1948); van den Oord et al. (2016); Ho et al. (2020); Song et al. (2021a); Lipman et al. (2023); Liu et al. (2023); Goodfellow et al. (2014).

Pause and think. In (12), why is it so useful that x_t can be sampled from x_0 directly, without running t forward steps?

Show the answer

Training draws a random t for each picture. With (12) the noisy input for any t costs one line of arithmetic, so every training example teaches the network about a random noise level at no extra cost; simulating up to 1000 steps per example would be far too slow.