Roadmap / Diffusion & Multimodal Models

✓

The Diffusion Forward Process

easydiffusionmultimodal

The problem

A diffusion model learns to make images by learning to undo noise. First we need the forward process: adding noise to an image, a little at a time, in TT steps. You will write the schedule of how much noise is added at each step, and the function that jumps straight to any step. This is the DDPM (Denoising Diffusion Probabilistic Models) schedule.

The schedule

At step tt a small amount of noise of variance βt\beta_t is added. Two derived quantities:

αt=1−βt,αˉt=∏s=1tαs\alpha_t = 1 - \beta_t, \qquad \bar\alpha_t = \prod_{s=1}^{t} \alpha_s

where αt\alpha_t is the share of the signal that survives step tt, and αˉt\bar\alpha_t ("alpha bar") is the product of the survivals up to step tt: the share of the original image still in the sample. DDPM's β\beta grows linearly from 10−410^{-4} to 0.020.02.

Example. T=4T = 4, β=(0.1,0.2,0.3,0.4)\beta = (0.1, 0.2, 0.3, 0.4).

  • α=1−β=(0.9,0.8,0.7,0.6)\alpha = 1 - \beta = (0.9, 0.8, 0.7, 0.6).
  • αˉ\bar\alpha: running product: 0.90.9, then 0.9⋅0.8=0.720.9 \cdot 0.8 = 0.72, then 0.72⋅0.7=0.5040.72 \cdot 0.7 = 0.504, then 0.504⋅0.6=0.30240.504 \cdot 0.6 = 0.3024.

Jumping to step tt

You do not need to add noise tt times: the sum of many small Gaussian noises is one Gaussian noise, so

xt=αˉt x0+1−αˉt ϵx_t = \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1 - \bar\alpha_t}\, \epsilon

where x0x_0 is the clean data, ϵ\epsilon is standard Gaussian noise (given in the tests, shaped like x0x_0), and the two coefficients say how much of the signal and how much of the noise are in xtx_t.

Example. Same schedule, x0=2x_0 = 2, noise ϵ=1\epsilon = 1, step t=2t = 2 (αˉ2=0.72\bar\alpha_2 = 0.72): x2=0.72⋅2+0.28⋅1=1.697+0.529=2.226x_2 = \sqrt{0.72} \cdot 2 + \sqrt{0.28} \cdot 1 = 1.697 + 0.529 = 2.226. In the code, αˉ2\bar\alpha_2 is abar[1]: the array is indexed from 0.

The training loss

The network predicts the noise that was added; the loss is the mean squared error between its prediction and the true noise.

Example. The true noise is (1,0,−1)(1, 0, -1) and the prediction (0.5,0,−1)(0.5, 0, -1): squared errors (0.25,0,0)(0.25, 0, 0), mean 0.0830.083.

What to implement

  • linear_betas(T, beta_1=1e-4, beta_T=0.02): TT values increasing linearly from beta_1 to beta_T. Element t - 1 is βt\beta_t.
  • alpha_bars(betas): αˉt\bar\alpha_t for t=1,…,Tt = 1, \dots, T, same indexing.
  • q_sample(x0, t, noise, abar): xtx_t for an integer step t∈[1,T]t \in [1, T], using abar[t - 1].
  • simple_loss(eps_pred, noise): the mean squared error between the predicted and the true noise, over all elements.

Requirements

  • Steps are numbered from 1 as in the paper; arrays are indexed from 0. Mind the shift.
  • No loops: np.cumprod computes the running product.
solution.py
Python idle

Press Run (⌘/Ctrl + Enter) to test your code.