What Are Diffusion Models and How Do They Work?
Diffusion models are generative models that learn to reverse a process that gradually adds noise to data. During training, a neural network learns to estimate the noise in corrupted examples; during generation, a sampler starts from random noise and repeatedly uses the network to produce a new sample. Stable Diffusion applies this process in a compressed image representation and can guide it with a text prompt.

Diffusion is one of several types of generative AI models. The labels describe different properties, so they can overlap. For example, large language models describe a family of language systems, while autoregression describes a way to factor a probability distribution. A GPT-style model belongs to both groups: it generates a sequence by predicting each token given the preceding tokens.
| Model family | How it learns | How it generates |
|---|---|---|
| Diffusion model | Learns a reverse process from noisy examples, often by predicting added noise. | Iteratively updates a noisy image, audio representation, or latent tensor. |
| Generative adversarial network | A generator and discriminator train against each other. | Maps a random latent to an output, often in one generator pass. |
| Variational autoencoder | Balances reconstruction with a penalty that shapes a probabilistic latent space. | Samples a latent from a prior and decodes it into data. |
| Autoregressive model | Learns conditional probabilities for successive elements. | Samples one element at a time, such as a text or audio token. |
A diffusion denoiser can update every spatial position of an image latent in one network pass, then repeat at the next noise level. An autoregressive image model instead follows an ordering over elements such as image tokens. Both procedures can model dependencies across an image, but their sequential costs come from different loops: denoising steps versus generated elements.
What Is the Forward Noise Process in Diffusion Models?
Consider a denoising diffusion probabilistic model, or DDPM. Let x_0 be a clean training example, such as a tensor of normalised pixels. The forward process defines a fixed Markov chain from step 1 to step T. At each step it scales the previous state and adds independent standard Gaussian noise of the same shape. A variance schedule specifies how strongly each step corrupts the data.
For each step, define beta_t as the added noise variance, with 0 < beta_t < 1, and set alpha_t = 1 - beta_t. A single transition is:
x_t = sqrt(alpha_t) * x_(t-1) + sqrt(beta_t) * z_t, where z_t ~ N(0, I).
The square roots matter because alpha_t and beta_t scale variance, whereas a multiplier on a sample scales its standard deviation. Define alpha_bar_t = alpha_1 * alpha_2 * ... * alpha_t. Expanding the recurrence gives a clean component multiplied by sqrt(alpha_bar_t) plus a weighted sum of independent Gaussian draws. Their variances add to 1 - alpha_bar_t, so the entire sum can be represented by one Gaussian draw:
x_t = sqrt(alpha_bar_t) * x_0 + sqrt(1 - alpha_bar_t) * epsilon, where epsilon ~ N(0, I).
This is the distribution at one chosen timestep given x_0. Training can jump directly to step 700 without simulating steps 1 through 699. If you independently use this shortcut at two timesteps, you obtain valid samples at each noise level, but the pair does not necessarily follow one trajectory of the forward Markov chain.
At early steps, the clean component usually dominates. At later steps, the accumulated product becomes small, suppressing structure from x_0 and making the distribution of x_T close to a standard Gaussian. That is why the reverse sampler can begin with a random tensor instead of a training image. The forward schedule should leave little signal at the last step if the sampler assumes a Gaussian starting distribution.
How Are Diffusion Models Trained to Predict Noise?
A common DDPM training objective uses noise prediction. For each clean example, sample a timestep t and a Gaussian tensor epsilon. Construct x_t with the direct formula, then pass x_t and t to a neural network. A conditional model also receives a signal c, such as embeddings of an image caption. The network output has the same shape as the noise target.
L = E[mean((epsilon - epsilon_theta(x_t, t, c))^2)]
The expectation is over training examples, timesteps, and Gaussian draws. In practice, a minibatch approximates it and backpropagation updates the network parameters theta. The sampled noise provides the supervision: no one has to label how an image should be cleaned. For text conditioning, however, the model still needs corresponding text or another source of paired conditioning data.
The timestep tells the model how to interpret what it sees. For an image with little noise, nearby pixels contain strong evidence about edges and colours. When the noise level is high, the same network has less evidence and must rely more on patterns learned from the dataset and, if present, the prompt. A common implementation projects a timestep embedding into the network's feature blocks so that one set of weights can handle many noise levels.
Squared error makes the ideal predictor the conditional mean of the noise given the network inputs. Different clean examples and noise draws can produce the same observed x_t, so even an ideal predictor cannot recover the exact noise draw in every case. This distinction matters when debugging: a nonzero loss on highly corrupted examples is not by itself evidence of a broken implementation.
Noise prediction is one parameterisation. Other checkpoints can predict the clean sample directly or use a velocity target that mixes the clean sample and noise. When loading a model, match the scheduler's prediction type to the training target. Applying a noise-prediction update to a velocity prediction changes the numerical meaning of the network output.
How Does Reverse Denoising Generate a New Sample?
At inference, start with x_T ~ N(0, I). At timestep t, the network estimates the noise in the current state. The sampler converts that estimate into a proposed state at a lower noise level. It repeats the operation with the same network weights and a new timestep input. Unlike training, inference usually has no clean x_0 available for comparison.
For an adjacent DDPM step with a noise-predicting network, the reverse mean is:
mu_theta = (x_t - beta_t * epsilon_theta(x_t, t, c) / sqrt(1 - alpha_bar_t)) / sqrt(alpha_t)
One fixed-variance DDPM choice uses variance_t = beta_t * (1 - alpha_bar_(t-1)) / (1 - alpha_bar_t), with alpha_bar_0 = 1. Sample x_(t-1) = mu_theta + sqrt(variance_t) * z using a fresh standard Gaussian z for t > 1. At t = 1, this variance is zero, so the final output is the mean. Intermediate steps can therefore add fresh noise even though the overall trajectory moves toward cleaner samples.
The denoiser provides a learned prediction, while the scheduler selects inference timesteps and implements the numerical update. The adjacent-step formula above assumes a transition from t to t - 1. To run fewer steps, use a sampler whose update supports the chosen spacing. Skipping indices in that formula without changing the update does not implement a valid large step.
DDIM supports a deterministic update given the initial latent and conditioning when its stochasticity parameter is zero. Other samplers use different numerical methods or introduce noise along the trajectory. For a controlled comparison, hold the model, prompt, initial latent, and resolution fixed, then vary the scheduler or step count. Fewer network evaluations tend to reduce latency, but the effect on image quality depends on the model and sampler. Some solvers can also use more than one network evaluation per step.
Worked Example: How Do Forward Noise and Reverse Denoising Change a Number?
Take a scalar clean value x_0 = 2. Set beta_1 = beta_2 = 0.2, so alpha_1 = alpha_2 = 0.8 and alpha_bar_2 = 0.64. Use a sampled aggregate noise value of epsilon = -0.5. The direct forward equation gives x_2 = 0.8 * 2 + 0.6 * (-0.5) = 1.3.
To isolate the reverse update, suppose the denoiser predicts exactly -0.5. The reverse mean at step 2 is (1.3 - 0.2 * (-0.5) / 0.6) / sqrt(0.8) = 1.6398 after rounding. The reverse variance is 0.2 * (1 - 0.8) / (1 - 0.64) = 0.1111. With a fresh draw z = 0.3, the sampled previous state is approximately 1.6398 + sqrt(0.1111) * 0.3 = 1.7398.
The reverse sample at step 1 is still noisy. You can separately estimate the clean value from the step 2 prediction: x_0_hat = (1.3 - 0.6 * (-0.5)) / 0.8 = 2. It matches the original only because this example supplied a perfect noise prediction. The following PyTorch code computes both quantities using different noise variables for forward corruption and reverse sampling.
import torch
beta = torch.tensor([0.2, 0.2], dtype=torch.float64)
alpha = 1 - beta
# Padding makes array indices match the mathematical timesteps.
alpha_bar = torch.cat([torch.ones_like(alpha[:1]), alpha.cumprod(0)])
t = 2
x0 = torch.tensor(2.0, dtype=beta.dtype)
epsilon = torch.tensor(-0.5, dtype=beta.dtype)
signal = alpha_bar[t].sqrt()
noise_scale = (1 - alpha_bar[t]).sqrt()
xt = signal * x0 + noise_scale * epsilon
epsilon_hat = epsilon # Oracle for the worked example; no model trained.
x0_hat = (xt - noise_scale * epsilon_hat) / signal
mean = (xt - beta[t - 1] * epsilon_hat / noise_scale) / alpha[t - 1].sqrt()
variance = beta[t - 1] * (1 - alpha_bar[t - 1]) / (1 - alpha_bar[t])
z = torch.tensor(0.3, dtype=beta.dtype)
x_prev = mean + variance.sqrt() * z
assert torch.allclose(x0_hat, x0)
print(f"x_2={xt.item():.4f}, reverse_mean={mean.item():.4f}")
print(f"x_1 sample={x_prev.item():.4f}, x_0 estimate={x0_hat.item():.4f}")
Try changing only z. The reverse mean and clean estimate stay fixed, while the sampled previous state changes. Then change only epsilon_hat: both estimates change because the denoiser's output influences the direction of the update. This two-step schedule is for checking the arithmetic; it leaves too much signal at step 2 to illustrate a Gaussian starting point for generation.
How Does Stable Diffusion Generate an Image from Text?
Stable Diffusion is a model family. The classic Stable Diffusion 1.x pipeline illustrates latent diffusion: a VAE maps images to compact spatial latents, a text encoder supplies prompt embeddings, and a timestep-conditioned U-Net denoises the latents. Newer family members can use different text encoders, denoiser architectures, and training targets, so check the system's configuration before reusing assumptions from 1.x.

- Prepare the latent space. For denoiser training, the VAE encoder maps a training image to a latent representation and the pipeline applies the checkpoint's latent scaling convention. In plain text-to-image inference, the image encoder is unnecessary because generation starts from noise. Image-to-image generation can instead encode a source image and corrupt its latent to a selected noise level.
- Encode the prompt. The tokenizer turns the prompt into token IDs, and a text encoder turns those IDs into contextual embeddings. The text encoder typically runs once per prompt for a generation, while the denoiser reuses its outputs at each step.
- Predict and update. The U-Net processes the noisy latent and timestep. In its cross-attention blocks, latent features provide queries and text embeddings provide keys and values. The scheduler uses the network prediction to update the latent at each inference step.
- Decode the final latent. After the denoising loop, the pipeline reverses any required latent scaling and passes the resulting tensor to the VAE decoder. The decoder maps the compact representation to RGB pixels.
For a 512 by 512 output in a classic 1.x pipeline, the latent typically has shape [1, 4, 64, 64] for one image. That is 16,384 latent values compared with 786,432 values in a three-channel 512 by 512 image tensor. The size difference shows why denoising in latent space can reduce computation. It does not predict a 48-fold speedup because compute also depends on the denoiser architecture, attention operations, step count, and hardware.
Stable Diffusion commonly uses classifier-free guidance. At training time, conditioning is sometimes dropped so the model learns to make both conditioned and unconditioned predictions. For a noise-predicting checkpoint, inference combines them as eps_guided = eps_uncond + s * (eps_cond - eps_uncond). Here s is the guidance scale. The unconditioned branch typically uses an empty prompt; with a negative prompt, that branch instead uses the negative prompt's embedding.
At s = 1, the expression reduces to the conditioned prediction. If one component is eps_uncond = 0.2 and eps_cond = 0.5, then s = 3 gives 1.1. Guidance extrapolates the difference rather than averaging the two outputs. Stronger guidance can improve prompt adherence in some cases, but excessive guidance can introduce artifacts or reduce diversity. The two predictions can be batched into one network call, which still processes both sets of inputs.
Where Are Diffusion Models Used in Image, Audio, and Video Generation?
In multimodal AI, an input and an output may belong to different modalities. Text-to-image generation consumes text and produces pixels. Image captioning consumes pixels and produces text. Both connect language and vision, but the task direction and learning objective differ. Identify what the system is generating before choosing an architecture or evaluation method.
| Modality | Generation example | Related understanding task | Model distinction |
|---|---|---|---|
| Text | Answer “Explain quantum computing in simple terms.” | Identify the topic or answer questions on a supplied document. | GPT-style and Llama language models commonly generate text autoregressively. |
| Image | Create a mountain scene from a prompt or edit a masked region. | Caption an image or detect objects in it. | Stable Diffusion generates or edits images; image understanding has a different output. |
| Audio | Synthesise speech, music, or environmental sound. | Transcribe an audio recording. | Audio diffusion can operate on spectrograms or latents. MusicGen generates audio tokens autoregressively, and Whisper performs speech recognition. |
| Video | Generate a clip from text or animate a reference image. | Describe an event across a sequence of frames. | The original Sora research system used diffusion on spacetime patches. Video generation can also use other approaches. |
For a video generator, plausible individual frames are insufficient if an object's colour or position changes unexpectedly between frames. Video diffusion can model spatial and temporal relationships jointly rather than denoising each frame independently. In audio, a model operating on a spectrogram or a learned latent still needs a decoder or vocoder to produce a playable waveform. In both cases, the denoiser operates on the chosen representation, and the representation determines what the final decoding stage must reconstruct.
Key Takeaways
- The forward DDPM process gradually removes signal and adds Gaussian noise according to a variance schedule.
- The cumulative product
alpha_bar_tlets training sample a noisy state directly at any timestep. - A noise-predicting denoiser uses a noisy sample, a timestep, and optional conditioning to estimate the added noise.
- The scheduler controls the inference trajectory and must interpret the denoiser's output using the correct prediction type.
- Classic Stable Diffusion denoises a compressed latent and uses a VAE decoder to convert it to pixels.
- Diffusion can generate images, audio, and video, but the modality alone does not tell you which generation procedure a system uses.
Frequently Asked Questions
Why does a diffusion model add noise during training?
Adding noise gives the model supervised examples of what corruption looks like at many strengths. Since the training code samples the noise, it knows the target for each example. The model learns how the distribution of plausible clean data changes with the observed noisy input and the timestep.
What is the difference between diffusion models and Stable Diffusion?
Diffusion models are a broad family that learns to generate samples by reversing a corruption process. Stable Diffusion is a specific family of generative models associated with image synthesis. Its classic versions denoise compressed image latents, accept text conditioning, and decode the final latent into an image.
Why does a diffusion model need fewer steps at inference than at training?
Training exposes the model to many noise levels so it can make predictions across the noise schedule. Inference can visit a smaller subset of levels if the sampler is designed to move between them. The useful step count depends on the model, the sampler, and how much quality loss the application can tolerate.
Will the same seed always generate the same Stable Diffusion image?
A seed controls the random draws in a given setup, including the initial noise. Reproducing an image also requires matching the prompt, checkpoint, scheduler, step count, resolution, guidance settings, and any additional inputs. Hardware, numerical precision, library versions, and nondeterministic operations can still cause differences across environments.
Is a diffusion model the same as a VAE?
No. A VAE learns an encoder and decoder around a probabilistic latent space, with an objective that includes reconstruction and latent regularisation. A diffusion model learns a reverse process across noise levels. Latent diffusion can use both: the VAE supplies the representation, and diffusion generates new samples within that representation.