Add noise to an image in one jump: q(x_t | x_0)

Diffusion training needs noisy versions of clean data at random noise levels. You do not have to add noise step by step: with alpha_bar_t the product of (1 - beta) up to step t,

x_t = sqrt(alpha_bar_t) * x_0 + sqrt(1 - alpha_bar_t) * noise

Write noisy_sample(x0, betas, t, noise) where betas is the noise schedule (index 0 is step 1) and t is 1-based. Return x_t.

Signaturedef noisy_sample(x0, betas, t, noise)

Understand the idea

Diffusion models train on clean data mixed with noise at many levels. Adding small Gaussian noise many times in a row is still Gaussian, so you can jump straight to any step t in one formula. alpha_bar_t is the product of (1 - beta) for all steps up to t; it is the share of signal power left. Like diluting juice with water several times: you can compute the final strength directly from the product of the dilutions. Worked example: betas [0.1, 0.2], t = 2. alpha_bar = 0.9 x 0.8 = 0.72. sqrt(0.72) = 0.849 and sqrt(1 - 0.72) = sqrt(0.28) = 0.529. With x0 = 1 and noise = 0.5: x_t = 0.849 x 1 + 0.529 x 0.5 = 1.113. Using only beta at step 2 would give sqrt(0.8) = 0.894 for the signal, which is wrong. Rule: alpha_bar_t = product over steps 1..t of (1 - beta); x_t = sqrt(alpha_bar_t) x0 + sqrt(1 - alpha_bar_t) noise, with betas[0] being step 1. Stable Diffusion training samples noisy images this way.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: t = 1noisy_sample(_x0, _b, 1, _e)
  • Sample 2: t = 500noisy_sample(_x0, _b, 500, _e)
  • Test 3: t = 1000 is almost pure noisenoisy_sample(_x0, _b, 1000, _e)