AI Beyond Language Models · Generating Images

Diffusion: Making Images from Noise

Image generators learn one skill: spotting the noise in a noisy picture. Mix noise into a tiny 4-pixel image, then remove it step by step.

diffusion.py

# Diffusion models make images by learning to remove noise, a little at a time.
pixels = ["px 0", "px 1", "px 2", "px 3"]
image = [0.0, 1.0, 1.0, 0.0]        # a tiny 4-pixel image: a bright bar in the middle
noise = [0.8, -0.6, 0.4, -0.9]      # random noise (fixed here so the lesson repeats)

# Training pictures: noise mixed in, more at every step.
picture = image
for t in range(3):
    picture = [round(p + 0.5 * n, 2) for p, n in zip(picture, noise)]
print("noisy:", picture)

# Generating: a trained network predicts the noise in the picture, and part of it is removed each step.
for t in range(3):
    predicted = noise   # a perfect network; real ones are close, not exact
    picture = [round(p - 0.5 * n, 2) for p, n in zip(picture, predicted)]
print("cleaned:", picture)

Step by step

  1. Names for the four pixels.
  2. A tiny image: dark, bright, bright, dark. A bar of light in the middle.
  3. Some random noise. Fixed here so every run is the same.
  4. Start from the clean image.
  5. t is created with the value 0.
  6. Mix in half the noise. The bar is already harder to see.
  7. t changes from 0 to 1.
  8. More noise.
  9. t changes from 1 to 2.
  10. After three steps: [1.2, 0.1, 1.6, −1.35]. The bar is gone; it looks like noise.
  11. Python moves to the next item of the loop: for t in range(3).
  12. It prints noisy: [1.2, 0.1, 1.6, -1.35].
  13. Now generate: run the process backwards.
  14. A trained network looks at the noisy picture and predicts its noise. Here it is perfect; real ones are close.
  15. Remove part of the predicted noise.
  16. t changes from 0 to 1.
  17. Line runs: predicted = noise # a perfect network; real ones are close, not exact.
  18. picture now points to a different list: [0.4, 0.7, 1.2, -0.45].
  19. t changes from 1 to 2.
  20. Line runs: predicted = noise # a perfect network; real ones are close, not exact.
  21. The last of the noise is removed.
  22. Python moves to the next item of the loop: for t in range(3).
  23. The bar is back: [0, 1, 1, 0]. A real generator starts from pure random noise, not a noised photo, so removing noise step by step produces a brand new image. A text prompt guides the noise predictor, which is how "a cat in a hat" becomes a picture.