Chapter 20 — Lab: Generative Models
Lab Overview¶
You will write, in NumPy, the formulas at the heart of the three families: the VAE’s sampling and KL term, the GAN’s losses, and the diffusion model’s noise schedule, noising and denoising steps.
| Exercise | Topic | Points |
|---|---|---|
| 1 | The reparameterisation trick | 10 |
| 2 | The KL term of a VAE | 15 |
| 3 | The GAN losses | 15 |
| 4 | A noise schedule | 10 |
| 5 | Noising in one step | 15 |
| 6 | One DDPM denoising step | 15 |
| 7 | One DDIM step | 10 |
| 8 | Counting covered clusters | 10 |
| Challenge | Classifier-free guidance | +10 |
How it works. Each exercise has a function to complete where you see # TODO. Run the check cell under it: ✅ means your function is right, ❌ tells you what is wrong. Use NumPy only. Do not change the check cells.
import numpy as np
def check(name, test):
"""Run one self-check: test() must return True; any exception or False is reported."""
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
rng = np.random.default_rng(0)
print('Setup complete')def reparameterise(mu, logvar, eps):
# TODO
raise NotImplementedErrorcheck('sigma = 1 when logvar = 0', lambda: np.allclose(reparameterise(np.array([1.0, -2.0]), np.zeros(2), np.array([0.5, 0.5])), [1.5, -1.5]))
check('logvar = log 4: sigma = 2', lambda: np.allclose(reparameterise(np.zeros(1), np.log([4.0]), np.ones(1)), [2.0]))
def moments():
z = reparameterise(np.full(100000, 3.0), np.full(100000, np.log(0.25)), rng.normal(size=100000))
return abs(z.mean() - 3) < .01 and abs(z.std() - .5) < .01
check('samples have mean mu and standard deviation sigma', moments)Exercise 2: The KL Term (15 points)¶
kl_normal(mu, logvar) returns , summed over the last axis (one value per row).
def kl_normal(mu, logvar):
# TODO
raise NotImplementedErrorcheck('zero when the code is already N(0, 1)', lambda: np.allclose(kl_normal(np.zeros((3, 4)), np.zeros((3, 4))), 0))
check('mu = 0.5, logvar = 0: 0.125', lambda: np.isclose(kl_normal(np.array([[0.5]]), np.array([[0.0]]))[0], 0.125))
check('one value per row', lambda: kl_normal(rng.normal(size=(5, 3)), rng.normal(size=(5, 3))).shape == (5,))
check('never negative', lambda: (kl_normal(rng.normal(size=(1000, 2)), rng.normal(size=(1000, 2))) >= -1e-12).all())Exercise 3: The GAN Losses (15 points)¶
The discriminator outputs logits (before the sigmoid). Write the mean binary cross-entropy losses:
d_loss(l_real, l_fake): real labelled 1, fake labelled 0: ;g_loss(l_fake): the non-saturating generator loss .
Use the stable forms and , written with np.logaddexp(0, ...).
def d_loss(l_real, l_fake):
# TODO
raise NotImplementedError
def g_loss(l_fake):
# TODO
raise NotImplementedErrorcheck('a discriminator that cannot tell: 2 ln 2', lambda: np.isclose(d_loss(np.zeros(4), np.zeros(4)), 2 * np.log(2)))
check('a perfect discriminator: close to 0', lambda: d_loss(np.full(4, 20.0), np.full(4, -20.0)) < 1e-6)
check('stable for very large logits (no overflow)', lambda: np.isfinite(d_loss(np.array([-1000.0]), np.array([1000.0]))))
check('the generator loss is large when D rejects its samples', lambda: g_loss(np.full(3, -5.0)) > 4.9 and np.isclose(g_loss(np.zeros(2)), np.log(2)))Exercise 4: A Noise Schedule (10 points)¶
alpha_bar(betas) returns for every (an array of the same length as betas).
def alpha_bar(betas):
# TODO
raise NotImplementedErrorbetas = np.linspace(1e-4, 0.1, 100)
ab = alpha_bar(betas)
check('the first value is 1 − beta_1', lambda: np.isclose(ab[0], 1 - 1e-4))
check('it decreases', lambda: (np.diff(ab) < 0).all())
check('the chapter\'s schedule ends with sqrt(abar) = 0.075', lambda: np.isclose(np.sqrt(ab[-1]), 0.075, atol=1e-3))Exercise 5: Noising in One Step (15 points)¶
q_sample(x0, t, eps, ab) returns , where t is an array of step indices (one per row of x0) into ab.
def q_sample(x0, t, eps, ab):
# TODO
raise NotImplementedErrorx0, e = rng.normal(size=(3, 2)), rng.normal(size=(3, 2))
check('at abar = 1, no noise', lambda: np.allclose(q_sample(x0, np.array([0, 0, 0]), e, np.array([1.0, .5])), x0))
check('each row uses its own step', lambda: np.allclose(q_sample(x0, np.array([0, 1, 1]), e, np.array([1.0, .25]))[1], .5 * x0[1] + np.sqrt(.75) * e[1]))
def variance():
z = q_sample(np.zeros((100000, 1)), np.full(100000, 1), rng.normal(size=(100000, 1)), np.array([1.0, 0.36]))
return abs(z.std() - 0.8) < .01
check('from x0 = 0, the noise has standard deviation sqrt(1 − abar)', variance)Exercise 6: One DDPM Step (15 points)¶
ddpm_step(x, t, eps_hat, betas, ab, z) returns one reverse step
where t is a single integer and z is the fresh noise (the caller passes zeros at the last step).
def ddpm_step(x, t, eps_hat, betas, ab, z):
# TODO
raise NotImplementedErrorb2, ab2 = np.array([0.1, 0.2]), alpha_bar(np.array([0.1, 0.2]))
x, eh = np.array([[1.0, -1.0]]), np.array([[0.5, 0.5]])
want = (x - 0.2 / np.sqrt(1 - ab2[1]) * eh) / np.sqrt(0.8)
check('without fresh noise', lambda: np.allclose(ddpm_step(x, 1, eh, b2, ab2, np.zeros_like(x)), want))
check('the fresh noise is scaled by sqrt(beta_t)', lambda: np.allclose(ddpm_step(x, 1, eh, b2, ab2, np.ones_like(x)), want + np.sqrt(0.2)))
def exact():
# if eps_hat is the true noise, one step from x_1 gives back the mean of x_0's posterior; with t = 0, x_0 itself
x0 = rng.normal(size=(4, 2)); e = rng.normal(size=(4, 2)); xt = q_sample(x0, np.zeros(4, int), e, ab2)
return np.allclose(ddpm_step(xt, 0, e, b2, ab2, np.zeros_like(xt)), x0)
check('at t = 0, the true noise gives back x0 exactly', exact)Exercise 7: One DDIM Step (10 points)¶
ddim_step(x, t, s, eps_hat, ab) estimates and returns . When s is None, use (the final step to the data).
def ddim_step(x, t, s, eps_hat, ab):
# TODO
raise NotImplementedErrorx0, e = rng.normal(size=(5, 2)), rng.normal(size=(5, 2))
xt = np.sqrt(ab[80]) * x0 + np.sqrt(1 - ab[80]) * e
check('with the true noise, a jump to step 20 lands exactly on x_20', lambda: np.allclose(ddim_step(xt, 80, 20, e, ab), np.sqrt(ab[20]) * x0 + np.sqrt(1 - ab[20]) * e))
check('and the final step returns x0', lambda: np.allclose(ddim_step(xt, 80, None, e, ab), x0))Exercise 8: Counting Covered Clusters (10 points)¶
coverage(samples, centres, radius) returns (clusters, share): how many centres have at least one sample within radius, and the share of samples within radius of some centre.
def coverage(samples, centres, radius=0.3):
# TODO
raise NotImplementedErrorC = np.array([[0.0, 0], [5, 0], [0, 5]])
smp = np.array([[0.1, 0], [0, 0.1], [5.1, 0], [2, 2]])
check('2 clusters covered, 3 of 4 samples near one', lambda: coverage(smp, C) == (2, 0.75))
check('a collapsed generator covers one cluster', lambda: coverage(np.tile([[5.0, 0.05]], (10, 1)), C)[0] == 1)def guide(eps_cond, eps_uncond, w):
# TODO
raise NotImplementedErrorec, eu = rng.normal(size=(3, 4)), rng.normal(size=(3, 4))
check('w = 0: the conditional prediction', lambda: np.allclose(guide(ec, eu, 0), ec))
check('w = 3: pushed away from the unconditional one', lambda: np.allclose(guide(ec, eu, 3) - ec, 3 * (ec - eu)))Lab Report¶
Submit this notebook with:
every check cell showing ✅,
one paragraph: Exercise 3 asks for the non-saturating generator loss. Using your
g_lossand the saturating form , compare their slopes with respect to at (a discriminator that easily rejects the generator’s samples). Which one gives the generator something to learn from?