Monday , November 30 2026
How diffusion models like Stable Diffusion work: forward noising in tested NumPy, denoising training, text conditioning, guidance, latent diffusion and diffusers code.

Diffusion Models Explained: How AI Image Generation Works

Updated: 29 November 2026Level: AdvancedReading time: about 10 minutesNumPy · tested

Diffusion models generate images, video and audio by learning to remove noise. They power Stable Diffusion, DALL·E, Midjourney, Imagen and most video generators. The idea: gradually add noise to real data, then train a network to reverse the process step by step.

What You Will Learn

  • Forward process: adding noise
  • Reverse process: denoising
  • The noise schedule in NumPy
  • How text guides the image (conditioning)
  • Latent diffusion and Stable Diffusion with diffusers

Prerequisites

Introduction to Generative AI, Autoencoders.

Forward Process

At each of T steps a little Gaussian noise is added. A neat property lets us jump straight to any step t: xt = √ᾱt · x0 + √(1 − ᾱt) · ε, where ε is random noise.

Example
import numpy as np
np.set_printoptions(precision=3, suppress=True)
T = 1000
betas = np.linspace(1e-4, 0.02, T)          # linear noise schedule (DDPM)
alpha_bar = np.cumprod(1 - betas)
for t in [0, 100, 250, 500, 999]:
    print(t, round(np.sqrt(alpha_bar[t]), 3), round(np.sqrt(1 - alpha_bar[t]), 3))
Output
0 1.0 0.01
100 0.946 0.324
250 0.722 0.692
500 0.279 0.96
999 0.006 1.0

Explanation: The first column is how much of the original signal remains, the second how much noise. By step 500 the data is mostly noise; by step 999 it is pure noise.

Example
rng = np.random.default_rng(0)
x0 = np.array([1.0, -1.0, 0.5, 0.0])        # a tiny "image" of 4 pixels
for t in [0, 250, 999]:
    eps = rng.normal(size=4)
    print(t, (np.sqrt(alpha_bar[t]) * x0 + np.sqrt(1 - alpha_bar[t]) * eps).round(3))
Output
0 [ 1.001 -1.001  0.506  0.001]
250 [ 0.352 -0.472  1.263  0.655]
999 [-0.697 -1.272 -0.62   0.041]

Reverse Process and Training

  1. Pick a real image x₀, a random step t and random noise ε.
  2. Create the noisy xt with the formula above.
  3. A neural network (usually a U-Net or a transformer) predicts ε from xt and t.
  4. Loss = mean squared error between true and predicted noise.

To generate, start from pure noise and apply the network about 20–50 times (with modern samplers), removing a little predicted noise at each step until an image appears.

Text-to-Image

  • Conditioning: the prompt is turned into embeddings by a text encoder (e.g. CLIP or T5) and fed to the denoiser through cross-attention.
  • Classifier-free guidance: the model predicts noise with and without the prompt and pushes the result towards the prompt; a guidance scale around 5–8 is common.
  • Latent diffusion: Stable Diffusion runs the process in a compressed latent space from an autoencoder (e.g. 64×64×4 instead of 512×512×3), making it fast enough for consumer GPUs.
Hugging Face diffusers (not run here – needs a GPU)
# pip install diffusers transformers accelerate torch
import torch
from diffusers import AutoPipelineForText2Image
pipe = AutoPipelineForText2Image.from_pretrained("stabilityai/sdxl-turbo",
                                                 torch_dtype=torch.float16).to("cuda")
img = pipe("a watercolor painting of the Golden Temple at sunrise",
           num_inference_steps=1, guidance_scale=0.0).images[0]
img.save("temple.png")

Explanation: SDXL-Turbo is a distilled model that generates in a single step. Standard models use 20–50 steps and a guidance scale above 1. Check each model’s licence before commercial use.

Diffusion vs GANs vs VAEs

Diffusion GAN VAE
Quality / diversity Excellent / high Sharp / can mode-collapse Blurrier / high
Training Stable Unstable Stable
Generation speed Slower (many steps) Fast (one pass) Fast

More on GANs.

Note: Use generated media responsibly: label AI images, do not create misleading images of real people, and respect artists’ rights.

Series

Generative AI series: Intro to GenAI · LLM Fundamentals · Tokenization · Embeddings · Prompt Engineering · RAG · Vector DBs · Function Calling · AI Agents · Agent Frameworks · MCP · Hallucinations · Run LLMs Locally · Diffusion Models

Interview Questions

Q: How do diffusion models generate images?
They start from random noise and repeatedly apply a trained denoising network until an image emerges.

Q: What does the network predict during training?
The noise that was added to the image at a random timestep.

Q: What is latent diffusion?
Running diffusion in an autoencoder’s compressed latent space for efficiency.

Practice Exercises

  1. Plot √ᾱ and √(1−ᾱ) against t for the linear schedule and a cosine schedule.
  2. Generate four images with different guidance scales and compare.

Summary

Diffusion models learn to reverse gradual noising. Text conditioning, guidance and latent spaces make modern text-to-image and video generation possible.

Next: Multimodal AI · Generative AI

About Machine Learning

Check Also

Model Context Protocol (MCP) Explained: Build an MCP Server in Python

What the Model Context Protocol (MCP) is, hosts, clients and servers, a Python MCP server example, the 2026-07-28 stateless spec and security tips.