One Batch, Many Noise Levels

Diffusion ModelsMedium+20 XP+20

One Batch, Many Noise Levels

Training a diffusion model repeats one recipe on every batch. For each clean image: pick a step ttt, jump straight to that noise level with the closed formula while keeping the noise you added, ask the network to predict that noise, and score its guess with squared error.

The schedule is a list β1,β2,…,βT\beta_1, \beta_2, \dots, \beta_Tβ1​,β2​,…,βT​. The share of signal left at step ttt is

αˉt=(1−β1)(1−β2)⋯(1−βt)\bar\alpha_t = (1-\beta_1)(1-\beta_2)\cdots(1-\beta_t)αˉt​=(1−β1​)(1−β2​)⋯(1−βt​)

and each pixel of the noisy image at step ttt is

xt=αˉt  x0+1−αˉt  ϵx_t = \sqrt{\bar\alpha_t}\;x_0 + \sqrt{1-\bar\alpha_t}\;\epsilonxt​=αˉt​​x0​+1−αˉt​​ϵ

where x0x_0x0​ is the clean pixel and ϵ\epsilonϵ is the noise drawn for it. Within one batch, every image gets its own step, so a single batch mixes nearly clean images with nearly pure noise.

Task: write noise_prediction_loss(images, noises, steps, betas, model).

  • images: the clean images, each a list of pixel values, all the same length.
  • noises: the noise drawn for each image, with the same shape as images.
  • steps: one step ttt per image, counting from 1.
  • betas: the schedule. betas[0] is β1\beta_1β1​, and the list may be longer than any step used.
  • model: the network, as a function. model(x_t, t) takes one noisy image (a list) and its step, and returns the predicted noise as a list of the same length.

An image's loss is the mean, over its pixels, of (predicted noise−ϵ)2(\text{predicted noise} - \epsilon)^2(predicted noise−ϵ)2. The batch loss is the mean of the image losses.

Return a tuple (per_image, batch): the list of image losses in order, and the batch loss. Round every value to 4 decimal places, averaging the unrounded image losses.

In real training, noises and steps are drawn at random every time; they are passed in here so the result can be checked. The test models are small stand-in functions such as lambda x, t: [0.5 * v for v in x].

input
↓ network
?

The network does not output an image. It outputs the noise it thinks was added — which is a surprisingly convenient thing to predict.

Examples

noise_prediction_loss([[0.8, -0.4], [0.1, 0.6]], [[0.5, -1.0], [1.2, 0.3]], [1, 3], [0.1, 0.2, 0.3], lambda x, t: [0.5 * v for v in x])
returns ([0.2135, 0.2754], 0.2445)
noise_prediction_loss([[1.0, 0.0, -1.0]], [[0.2, -0.7, 0.9]], [2], [0.05, 0.15, 0.25, 0.35], lambda x, t: [0.0 for v in x])
returns ([0.4467], 0.4467)

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run