On this page
How does a neural network conjure a sharp 512x512 photograph of an oak dining table in morning light from 786,432 independent draws of Gaussian static? Mapping unstructured noise directly to coherent pixels in one forward pass forces a single network to solve composition, lighting, perspective, and fine texture simultaneously.
Diffusion models break that leap into gentle denoising steps. A forward process gradually buries real data in Gaussian noise until only static remains; a learned denoiser then predicts small reverse updates while a numerical solver marches from noise back to structure. Compressing pixels into a 64x smaller spatial latent space shrinks self-attention work by 4,096x, while straight-line flow matching and deterministic ODE solvers collapse 1,000 reverse passes down to 4 to 25 steps. The same iterative refinement idea extends to discrete text canvases, where a bidirectional transformer fills and revises masked tokens in parallel.[1]
One pixel under a forward noise schedule
Track a single normalized brightness value mixed with one Gaussian draw . Under a variance-preserving schedule with cumulative signal retention , the noisy state is:
Why square roots? If and are independent with unit variance, then . Linear blending would shrink variance mid-schedule; square-root weights keep activation scale constant across all timesteps.
| Signal | Noise | Noisy state | ||
|---|---|---|---|---|
| 0.900 | 0.949 | -0.126 | 0.822 | 9.000 |
| 0.500 | 0.707 | -0.283 | 0.424 | 1.000 |
| 0.001 | 0.032 | -0.400 | -0.368 | 0.001 |
At , the signal keeps of its amplitude because variance scales with amplitude squared, placing signal and noise at equal variance (). The same formula corrupts a full tensor in one vectorized op:
import numpy as np
def forward_diffuse(x0: np.ndarray, alpha_bar: float, eps: np.ndarray) -> tuple[np.ndarray, float]:
xt = np.sqrt(alpha_bar) * x0 + np.sqrt(1.0 - alpha_bar) * eps
return xt, alpha_bar / (1.0 - alpha_bar)
x0 = np.array([1.0, 0.8, -0.5])
eps = np.array([-0.4, 0.2, 0.1])
for ab in [0.9, 0.5, 0.001]:
xt, snr = forward_diffuse(x0, ab, eps)
print(f"alpha_bar={ab:<5} xt={np.round(xt, 3).tolist()} SNR={snr:.3f}")alpha_bar=0.9 xt=[0.822, 0.822, -0.443] SNR=9.000
alpha_bar=0.5 xt=[0.424, 0.707, -0.283] SNR=1.000
alpha_bar=0.001 xt=[-0.368, 0.225, 0.084] SNR=0.001By , the first coordinate swings from to , nearly pure static. Generation runs this corruption backward.[2]
Why iterative denoising displaced one-shot generators
GANs attempt one-shot generation through an adversarial minimax game, yielding single-pass speed at the cost of training instability and mode collapse. VAEs optimize a stable variational lower bound (ELBO) in one decoder pass, but likelihood averaging blurs fine texture. Diffusion models trade single-pass latency for supervised MSE regression over gradual cleanup steps, gaining stable optimization and broad mode coverage:
| Dimension | GANs | VAEs | Diffusion Models |
|---|---|---|---|
| Objective | Adversarial minimax | Evidence Lower Bound (ELBO) | Supervised MSE / score or flow matching |
| Sample Quality | Sharp; sensitive to tuning | Smooth; prone to blur | High detail and global coherence |
| Mode Coverage | Prone to mode collapse | High coverage | Broad coverage, minimal collapse |
| Inference Cost | 1 forward pass | 1 decoder pass | 4 to 50 iterative passes |
The forward Markov chain and noise schedules
From a clean sample , the forward Markov chain adds Gaussian noise at each step under variance schedule :[3]
Define and . Because sums of independent Gaussians remain Gaussian with additive variances, we jump straight from to any step in closed form:
That closed-form jump makes training fast: each step samples a random per example, computes in one vectorized op, and backpropagates without unrolling the chain. Schedule shape sets how decays. Linear schedules destroy signal too fast, wasting late steps near zero SNR; cosine schedules decay smoothly so capacity spans global layout (low SNR) and surface detail (high SNR).

Reverse process: DDPM training, targets, and sampling
Reversing the chain requires , which is intractable because it integrates over all clean images consistent with . Conditioning on the known training image makes Bayes' rule exact, giving a closed-form Gaussian posterior :
Substituting reduces predicting to predicting the injected noise . Dropping the ELBO step weights produces Ho et al.'s simple MSE objective:[2]
Below, an eight-parameter linear denoiser (four weights per output coordinate) trains under a cosine schedule on a 2D cluster, cutting MSE from 0.9679 to ~0.20:
import numpy as np
rng = np.random.default_rng(42)
T = 200
steps = np.linspace(0, 1, T + 1)
f = np.cos((steps + 0.008) / 1.008 * np.pi / 2) ** 2
alpha_bars = np.clip(f[1:] / f[0], 1e-4, 0.999)
x0_data = np.array([1.0, -0.5]) + 0.15 * rng.standard_normal((256, 2))
W = np.zeros((2, 4))
for it in range(401):
t = rng.integers(0, T, size=len(x0_data))
ab = alpha_bars[t, None]
eps = rng.standard_normal(x0_data.shape)
xt = np.sqrt(ab) * x0_data + np.sqrt(1.0 - ab) * eps
feats = np.column_stack([xt, t / T, np.ones(len(x0_data))])
err = feats @ W.T - eps
W -= 0.2 * (err.T @ feats) / len(x0_data)
if it in (0, 50, 200, 400):
print(f"iter={it:3d} mse_loss={float(np.mean(err ** 2)):.4f}")iter= 0 mse_loss=0.9679
iter= 50 mse_loss=0.2613
iter=200 mse_loss=0.1999
iter=400 mse_loss=0.2208Prediction targets and reverse DDPM sampling
Besides noise , a denoiser can predict clean data or velocity . Recovering via avoids dividing by tiny at extreme noise and stabilizes step distillation.[4] Never mismatch target and sampler: feeding a -prediction checkpoint into an formula explodes .
To sample with DDPM, draw and step backward from to , adding fresh noise at every step except the final transition to :
Because every reverse step depends sequentially on , running 1,000 stochastic DDPM steps is slow. Continuous-time formulations fix that bottleneck.
Score matching, flow matching, and Rectified Flow
In the continuous-time limit (), forward diffusion becomes a stochastic differential equation (SDE) whose reverse SDE depends only on the score function , proportional to optimal noise prediction: . Every diffusion SDE also admits a deterministic probability flow ODE sharing identical marginals at every , turning sampling into numerical ODE integration.
Curved variance-preserving paths still require small solver steps to stay on track. Flow matching skips the diffusion schedule and learns a velocity field transporting noise directly to data .[5] Rectified Flow connects pairs along straight paths for and regresses against the constant velocity :[6]
Straight paths have minimal curvature, so simple Euler ODE steps follow them accurately in ~20 to 30 steps for base flow models such as Stable Diffusion 3 and Flux, and in 4 to 8 evaluations after reflow or step distillation.[7] Watch how four equal Euler steps carry a noisy state cleanly to along a straight trajectory:
import numpy as np
x0_target = np.array([1.0, -0.5])
x1_noise = np.array([-0.6, 0.9])
velocity = x1_noise - x0_target # constant velocity along the straight path
x = x1_noise.copy()
dt = 0.25
for step in range(4):
x = x - dt * velocity
tau = 1.0 - (step + 1) * dt
print(f"tau={tau:.2f} x={np.round(x, 3).tolist()}")
assert np.allclose(x, x0_target)tau=0.75 x=[-0.2, 0.55]
tau=0.50 x=[0.2, 0.2]
tau=0.25 x=[0.6, -0.15]
tau=0.00 x=[1.0, -0.5]Denoiser backbones: U-Net vs. Diffusion Transformers
A denoiser must maintain global scene layout and crisp micro-texture simultaneously across all noise levels.
- Convolutional U-Net: a downsampling encoder captures wide spatial context while horizontal skip connections pass fine local features directly to matching decoder blocks; cross-attention layers inject prompt embeddings at multiple scales.[8]
- Diffusion Transformers (DiT and MM-DiT): DiT patchifies the noisy latent into tokens processed by standard transformer blocks, delivering smooth compute scaling laws that steadily lower FID.[9] MM-DiT gives text and image streams separate linear projections while running joint self-attention across both modalities in every block.[7]
- Timestep conditioning: sinusoidal embeddings pass through an MLP to produce per-channel scale and shift vectors (FiLM / AdaGN in U-Nets; AdaLN-Zero in DiT), modulating normalized features as . Zero-initializing the residual gate in AdaLN-Zero stabilizes deep training.

What distinguishes Diffusion Transformers (DiT) from convolutional U-Nets?
Answer
DiT patchifies continuous latents into sequence tokens processed by transformer blocks with AdaLN-Zero conditioning, delivering predictable scaling laws and joint text-image attention in MM-DiT.
Classifier-free guidance (CFG)
Classifier-free guidance (CFG) steers conditional generation without training a separate noisy-image classifier.[10] During training, the prompt is randomly replaced with a null embedding 10% to 20% of the time so one network learns both and . At inference, the sampler extrapolates along the prompt direction by weight :

Setting ignores the prompt, gives standard conditional sampling, sharpens alignment, and explodes prediction norms and clips colors:
import numpy as np
eps_uncond = np.array([0.20, -0.10, 0.05])
eps_cond = np.array([0.05, -0.35, 0.20])
for w in [0.0, 1.0, 7.5, 15.0]:
guided = eps_uncond + w * (eps_cond - eps_uncond)
print(f"w={w:4.1f} guided={np.round(guided, 3).tolist()} norm={np.linalg.norm(guided):.3f}")w= 0.0 guided=[0.2, -0.1, 0.05] norm=0.229
w= 1.0 guided=[0.05, -0.35, 0.2] norm=0.406
w= 7.5 guided=[-0.925, -1.975, 1.175] norm=2.477
w=15.0 guided=[-2.05, -3.85, 2.3] norm=4.931Ordinary CFG doubles compute per step because it evaluates both branches. Guidance distillation folds directly into the network as an input, restoring single-branch speed.
Fast sampling schedules: DDIM and ODE solvers
DDIM defines a non-Markovian process sharing the same marginals as DDPM, letting any pretrained DDPM checkpoint sample deterministically () along an ODE.[11] Without fresh noise, DDIM leaps from step to an earlier step by estimating and re-projecting onto :
This collapses 1,000 DDPM steps into 20 to 50 steps without retraining, and running the ODE in reverse gives DDIM inversion (mapping a real image back into noise for editing). Below, we verify both the deterministic DDIM jump and exact recovery:
import numpy as np
x0, eps = np.array([1.0, 0.5]), np.array([-0.4, 0.2])
alpha_t, alpha_s = 0.5, 0.9
xt = np.sqrt(alpha_t) * x0 + np.sqrt(1.0 - alpha_t) * eps
x0_hat = (xt - np.sqrt(1.0 - alpha_t) * eps) / np.sqrt(alpha_t)
xs = np.sqrt(alpha_s) * x0_hat + np.sqrt(1.0 - alpha_s) * eps
assert np.allclose(xs, np.sqrt(alpha_s) * x0 + np.sqrt(1.0 - alpha_s) * eps)
a, b = np.sqrt(alpha_t), np.sqrt(1.0 - alpha_t)
v = a * eps - b * x0
x0_from_v = a * xt - b * v
assert np.allclose(x0_from_v, x0)
print(f"xt={xt.round(3).tolist()} -> x0_hat={x0_hat.round(3).tolist()} -> xs={xs.round(3).tolist()}")
print(f"v={v.round(3).tolist()} -> x0_from_v={x0_from_v.round(3).tolist()}")xt=[0.424, 0.495] -> x0_hat=[1.0, 0.5] -> xs=[0.822, 0.538]
v=[-0.99, -0.212] -> x0_from_v=[1.0, 0.5]Higher-order ODE solvers like DPM-Solver++ cut 2-branch CFG sampling to ~25 steps (50 evaluations), while distilled single-branch flow models need only 4 to 8 evaluations:

Latent diffusion and cross-attention conditioning
Running self-attention over a 512x512 RGB image (262,144 spatial positions) exhausts GPU memory immediately. Latent Diffusion Models (LDMs) decouple perceptual compression from generation: a frozen VAE encodes pixels into a continuous latent at 8x lower spatial resolution, the denoiser iterates entirely in latent space, and the VAE decoder runs once at the end.[8]

Downsampling each spatial axis by 8x cuts positions by and quadratic self-attention entries by :
import numpy as np
pixel_shape, latent_shape = np.array([512, 512, 3]), np.array([64, 64, 4])
pixel_scalars, latent_scalars = int(pixel_shape.prod()), int(latent_shape.prod())
pixel_pos, latent_pos = int(pixel_shape[:2].prod()), int(latent_shape[:2].prod())
print(f"scalars: {pixel_scalars:,} -> {latent_scalars:,} ({pixel_scalars // latent_scalars}x smaller)")
print(f"spatial positions: {pixel_pos:,} -> {latent_pos:,} ({pixel_pos // latent_pos}x smaller)")
print(f"self-attention entries: {(pixel_pos ** 2) // (latent_pos ** 2):,}x smaller")scalars: 786,432 -> 16,384 (48x smaller)
spatial positions: 262,144 -> 4,096 (64x smaller)
self-attention entries: 4,096x smallerContinuous VAE latents preserve smooth gradients for diffusion and flow matching, whereas discrete VQ-VAE codebooks quantize patches into token IDs for autoregressive or masked generators. In both cases, VAE reconstruction caps fine detail: if encode-decode alone blurs 8px text, extra denoising steps cannot fix it.
To condition on text, an encoder (CLIP, T5, or both) produces prompt embeddings . Inside each cross-attention block, noisy spatial patches emit queries while prompt tokens supply keys and values , routing words to matching image regions.
Discrete text diffusion
Autoregressive LLMs commit tokens left to right with no revision. Discrete text diffusion (such as DiffusionGemma) replaces Gaussian noise with token masking, refining a bidirectional canvas in parallel rounds.[1] Each round scores every slot simultaneously, unmasks confident tokens, revises earlier slots once surrounding context clarifies, and stops when mean entropy drops below threshold and the canvas stabilizes.
Spatial control, LoRA, and inference practice
Prompts capture style and subject well but rarely pin exact silhouettes, camera framing, or pose layout. ControlNet solves spatial conditioning by freezing the pretrained denoiser and attaching a trainable copy of its encoder blocks through zero-initialized convolutions whose weights and biases start at exact zero.[12] At optimization step 0, those zero convolutions contribute zero residual signal, so the combined network behaves identically to the pretrained base model; as gradients flow, the side branch smoothly learns to obey Canny edges, depth maps, segmentation masks, or human pose skeletons without corrupting base visual fidelity.
For style, character, or domain specialization without duplicating multi-gigabyte checkpoints, LoRA freezes base weights and injects a low-rank update (with rank ) into the denoiser's attention projections. One base checkpoint stays resident in VRAM while megabyte-scale LoRA and ControlNet adapters hot-swap per request, or merge directly into when serving a single specialization.
Four optimizations make latent diffusion fast in practice:
- BF16/FP16 + compiled kernels: combine half precision, FlashAttention, and
torch.compileto saturate tensor cores. - Cross-attention K/V caching: prompt embeddings are constant across all solver steps, so project text keys and values once per prompt.
- Pre-allocated latent buffers: reuse fixed-shape scratch tensors per resolution bucket to avoid CUDA allocator stalls.
- Overlapped VAE decoding: decode finished latents on a separate CUDA stream while the denoiser processes the next batch.
Common pitfalls
- Treating CFG scale as a probability: is an extrapolation multiplier; pushing overshoots the data manifold and clips colors.
- Decoding predicted noise: the VAE decoder expects clean latent , not raw .
- Blaming the denoiser for VAE blur: run a plain encode-decode sanity check before increasing step count.
- Assuming DiT is always cheaper than U-Net: quadratic self-attention over small high-resolution patches can exceed U-Net FLOPs and memory.