Skip to content
Skip to lesson
Back to Topics
LearnTransformer & Multimodal ArchitecturesDiffusion Models: Images & Text
HardMultimodal Models15 min read

Diffusion Models: Images & Text

How diffusion models turn pure Gaussian static into coherent images and text: forward schedules, reverse DDPM/DDIM solvers, score and flow matching, U-Net vs. DiT, CFG, and latent diffusion.

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]

Latent diffusion inference pipeline. Text embeddings steer iterative denoiser passes over compact latents before the VAE decoder renders RGB pixels.

One pixel under a forward noise schedule

Track a single normalized brightness value x0=1.0x_0 = 1.0 mixed with one Gaussian draw ϵ=−0.4\epsilon = -0.4. Under a variance-preserving schedule with cumulative signal retention αˉt∈(0,1)\bar{\alpha}_t \in (0, 1), the noisy state is:

xt=αˉt x0+1−αˉt ϵx_t = \sqrt{\bar{\alpha}_t} \, x_0 + \sqrt{1 - \bar{\alpha}_t} \, \epsilon

Why square roots? If x0x_0 and ϵ\epsilon are independent with unit variance, then Var⁡(xt)=(αˉt)2+(1−αˉt)2=1\operatorname{Var}(x_t) = (\sqrt{\bar{\alpha}_t})^2 + (\sqrt{1-\bar{\alpha}_t})^2 = 1. Linear blending αˉtx0+(1−αˉt)ϵ\bar{\alpha}_t x_0 + (1-\bar{\alpha}_t)\epsilon would shrink variance mid-schedule; square-root weights keep activation scale constant across all timesteps.

αˉt\bar{\alpha}_tSignal αˉt x0\sqrt{\bar{\alpha}_t}\,x_0Noise 1−αˉt ϵ\sqrt{1-\bar{\alpha}_t}\,\epsilonNoisy state xtx_tSNR=αˉt/(1−αˉt)\mathrm{SNR} = \bar{\alpha}_t/(1-\bar{\alpha}_t)
0.9000.949-0.1260.8229.000
0.5000.707-0.2830.4241.000
0.0010.032-0.400-0.3680.001

At αˉt=0.5\bar{\alpha}_t = 0.5, the signal keeps 0.5≈70.7%\sqrt{0.5} \approx 70.7\% of its amplitude because variance scales with amplitude squared, placing signal and noise at equal variance (SNR=1.0\mathrm{SNR} = 1.0). The same formula corrupts a full tensor in one vectorized op:

adding-noise-gradually.py
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}")
Output
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.001

By αˉt=0.001\bar{\alpha}_t = 0.001, the first coordinate swings from +1.0+1.0 to −0.368-0.368, 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:

DimensionGANsVAEsDiffusion Models
ObjectiveAdversarial minimaxEvidence Lower Bound (ELBO)Supervised MSE / score or flow matching
Sample QualitySharp; sensitive to tuningSmooth; prone to blurHigh detail and global coherence
Mode CoverageProne to mode collapseHigh coverageBroad coverage, minimal collapse
Inference Cost1 forward pass1 decoder pass4 to 50 iterative passes

The forward Markov chain and noise schedules

From a clean sample x0x_0, the forward Markov chain adds Gaussian noise at each step t∈{1,…,T}t \in \{1, \dots, T\} under variance schedule βt∈(0,1)\beta_t \in (0, 1):[3]

q(xt∣xt−1)=N ⁣(xt; 1−βt xt−1, βtI)q(x_t \mid x_{t-1}) = \mathcal{N}\!\left(x_t;\, \sqrt{1-\beta_t}\,x_{t-1},\, \beta_t \mathbf{I}\right)
Variance-preserving forward diffusion across four stages. Signal amplitude decays while noise variance rises to hold total variance constant.

Define αt=1−βt\alpha_t = 1 - \beta_t and αˉt=∏s=1tαs\bar{\alpha}_t = \prod_{s=1}^t \alpha_s. Because sums of independent Gaussians remain Gaussian with additive variances, we jump straight from x0x_0 to any step tt in closed form:

q(xt∣x0)=N ⁣(xt; αˉt x0, (1−αˉt)I)q(x_t \mid x_0) = \mathcal{N}\!\left(x_t;\, \sqrt{\bar{\alpha}_t}\,x_0,\, (1 - \bar{\alpha}_t)\mathbf{I}\right)

That closed-form jump makes training fast: each step samples a random t∼U(1,T)t \sim \mathcal{U}(1, T) per example, computes xtx_t in one vectorized op, and backpropagates without unrolling the chain. Schedule shape sets how SNR(t)=αˉt/(1−αˉt)\mathrm{SNR}(t) = \bar{\alpha}_t / (1 - \bar{\alpha}_t) decays. Linear βt\beta_t schedules destroy signal too fast, wasting late steps near zero SNR; cosine schedules decay αˉt\bar{\alpha}_t smoothly so capacity spans global layout (low SNR) and surface detail (high SNR).

Variance-preserving signal and noise amplitudes across diffusion timesteps under a cosine schedule. Signal amplitude sqrt(alpha_bar) declines smoothly from 1.00 to 0.03 while noise amplitude sqrt(1 - alpha_bar) rises from 0.00 to 1.00, crossing at t = 500 where alpha_bar = 0.5 and SNR = 1.0. Shaded bands mark high-SNR detail, midway structure, and low-SNR global layout regimes.
Signal amplitude decays smoothly while noise amplitude rises. At alpha-bar=0.5, signal variance equals noise variance.

Reverse process: DDPM training, targets, and sampling

Reversing the chain requires q(xt−1∣xt)q(x_{t-1} \mid x_t), which is intractable because it integrates over all clean images x0x_0 consistent with xtx_t. Conditioning on the known training image x0x_0 makes Bayes' rule exact, giving a closed-form Gaussian posterior q(xt−1∣xt,x0)q(x_{t-1} \mid x_t, x_0):

μ~t=αˉt−1 βt1−αˉtx0+αt(1−αˉt−1)1−αˉtxt,β~t=1−αˉt−11−αˉtβt\tilde{\mu}_t = \frac{\sqrt{\bar{\alpha}_{t-1}}\,\beta_t}{1-\bar{\alpha}_t}x_0 + \frac{\sqrt{\alpha_t}(1-\bar{\alpha}_{t-1})}{1-\bar{\alpha}_t}x_t, \qquad \tilde{\beta}_t = \frac{1-\bar{\alpha}_{t-1}}{1-\bar{\alpha}_t}\beta_t

Substituting x0=(xt−1−αˉt ϵ)/αˉtx_0 = (x_t - \sqrt{1-\bar{\alpha}_t}\,\epsilon)/\sqrt{\bar{\alpha}_t} reduces predicting μ~t\tilde{\mu}_t to predicting the injected noise ϵ\epsilon. Dropping the ELBO step weights produces Ho et al.'s simple MSE objective:[2]

Lsimple=Et,x0,ϵ[∥ϵ−ϵθ(xt,t)∥2]\mathcal{L}_{\text{simple}} = \mathbb{E}_{t, x_0, \epsilon}\left[\|\epsilon - \epsilon_\theta(x_t, t)\|^2\right]

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:

ddpm-training.py
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}")
Output
iter=  0  mse_loss=0.9679
iter= 50  mse_loss=0.2613
iter=200  mse_loss=0.1999
iter=400  mse_loss=0.2208

Prediction targets and reverse DDPM sampling

Besides noise ϵ\epsilon, a denoiser can predict clean data x0x_0 or velocity v=αˉt ϵ−1−αˉt x0v = \sqrt{\bar{\alpha}_t}\,\epsilon - \sqrt{1 - \bar{\alpha}_t}\,x_0. Recovering x0x_0 via x0=αˉt xt−1−αˉt vx_0 = \sqrt{\bar{\alpha}_t}\,x_t - \sqrt{1-\bar{\alpha}_t}\,v avoids dividing by tiny αˉt\sqrt{\bar{\alpha}_t} at extreme noise and stabilizes step distillation.[4] Never mismatch target and sampler: feeding a vv-prediction checkpoint into an ϵ\epsilon formula explodes x^0\hat{x}_0.

To sample with DDPM, draw xT∼N(0,I)x_T \sim \mathcal{N}(0, \mathbf{I}) and step backward from TT to 00, adding fresh noise z∼N(0,I)z \sim \mathcal{N}(0, \mathbf{I}) at every step except the final transition to x0x_0:

xt−1=1αt(xt−βt1−αˉtϵθ(xt,t))+σtzx_{t-1} = \frac{1}{\sqrt{\alpha_t}} \left(x_t - \frac{\beta_t}{\sqrt{1-\bar{\alpha}_t}} \epsilon_\theta(x_t, t)\right) + \sigma_t z

Because every reverse step depends sequentially on xtx_t, 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 (T→∞T \to \infty), forward diffusion becomes a stochastic differential equation (SDE) whose reverse SDE depends only on the score function ∇xtlog⁡pt(xt)\nabla_{x_t} \log p_t(x_t), proportional to optimal noise prediction: ϵ∗(xt,t)=−1−αˉt ∇xtlog⁡pt(xt)\epsilon^*(x_t, t) = -\sqrt{1-\bar{\alpha}_t}\,\nabla_{x_t}\log p_t(x_t). Every diffusion SDE also admits a deterministic probability flow ODE sharing identical marginals pt(xt)p_t(x_t) at every tt, 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 x1∼N(0,I)x_1 \sim \mathcal{N}(0, \mathbf{I}) directly to data x0x_0.[5] Rectified Flow connects pairs along straight paths xτ=(1−τ)x0+τx1x_\tau = (1 - \tau)x_0 + \tau x_1 for τ∈[0,1]\tau \in [0, 1] and regresses against the constant velocity x1−x0x_1 - x_0:[6]

LFM=Eτ,x0,x1[∥vθ(xτ,τ)−(x1−x0)∥2]\mathcal{L}_{\text{FM}} = \mathbb{E}_{\tau, x_0, x_1}\left[\|v_\theta(x_\tau, \tau) - (x_1 - x_0)\|^2\right]

Straight paths have minimal curvature, so simple Euler ODE steps xτ−Δτ=xτ−Δτ vθ(xτ,τ)x_{\tau - \Delta\tau} = x_\tau - \Delta\tau\, v_\theta(x_\tau, \tau) 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 x0x_0 along a straight trajectory:

rectified-flow-euler.py
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)
Output
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.

U-shaped multi-scale U-Net denoiser architecture: the encoder downsamples noisy latents from 64x64 (320 channels) through 32x32 (640 channels) to a 16x16 (1280 channels) global self-attention bottleneck, while horizontal skip connections pass matching spatial scales to the upsampling decoder. Timestep FiLM/AdaGN and text cross-attention condition every level.
U-Net denoiser layout. Timestep embeddings modulate ResNet layers while cross-attention injects prompt tokens at multiple spatial scales.

Classifier-free guidance (CFG)

Classifier-free guidance (CFG) steers conditional generation without training a separate noisy-image classifier.[10] During training, the prompt cc is randomly replaced with a null embedding ∅\emptyset 10% to 20% of the time so one network learns both ϵθ(xt,c)\epsilon_\theta(x_t, c) and ϵθ(xt,∅)\epsilon_\theta(x_t, \emptyset). At inference, the sampler extrapolates along the prompt direction by weight ww:

ϵ~θ(xt,c)=ϵθ(xt,∅)+w⋅(ϵθ(xt,c)−ϵθ(xt,∅))\tilde{\epsilon}_\theta(x_t, c) = \epsilon_\theta(x_t, \emptyset) + w \cdot \left(\epsilon_\theta(x_t, c) - \epsilon_\theta(x_t, \emptyset)\right)
Classifier-free guidance extrapolation in score space paired with guided vector norms. Starting from unconditional prediction w = 0, extrapolating along the prompt delta to w = 4.0-7.5 sharpens prompt alignment, while w >= 12 explodes norm and clips colors.
CFG linear extrapolation in score space. Moderate weights (4.0 to 7.5) sharpen prompt adherence; extreme weights overshoot into saturated colors and clipping.

Setting w=0w = 0 ignores the prompt, w=1w = 1 gives standard conditional sampling, w∈[4.0,7.5]w \in [4.0, 7.5] sharpens alignment, and w>12w > 12 explodes prediction norms and clips colors:

cfg-guidance-formula.py
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}")
Output
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.931

Ordinary CFG doubles compute per step because it evaluates both branches. Guidance distillation folds ww 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 q(xt∣x0)q(x_t \mid x_0) as DDPM, letting any pretrained DDPM checkpoint sample deterministically (η=0\eta = 0) along an ODE.[11] Without fresh noise, DDIM leaps from step tt to an earlier step ss by estimating x^0\hat{x}_0 and re-projecting onto αˉs\bar{\alpha}_s:

x^0=xt−1−αˉt ϵθ(xt,t)αˉt,xs=αˉs x^0+1−αˉs ϵθ(xt,t)\hat{x}_0 = \frac{x_t - \sqrt{1 - \bar{\alpha}_t}\,\epsilon_\theta(x_t, t)}{\sqrt{\bar{\alpha}_t}}, \qquad x_s = \sqrt{\bar{\alpha}_s}\,\hat{x}_0 + \sqrt{1 - \bar{\alpha}_s}\,\epsilon_\theta(x_t, t)

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 ϵ↔v\epsilon \leftrightarrow v recovery:

ddim-known-noise-check.py
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()}")
Output
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:

Per-image denoiser network evaluation counts on a log scale across four diffusion sampling strategies: ancestral DDPM (1,000 evals), DDIM with 2-branch CFG (100 evals), DPM-Solver++ with CFG (50 evals), and distilled single-branch flow models (6 evals).
Per-image denoiser budgets across sampling strategies. Higher-order ODE solvers and distilled flow models slash 1,000 DDPM steps down to single-digit 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 z0z_0 at 8x lower spatial resolution, the denoiser iterates entirely in latent space, and the VAE decoder runs once at the end.[8]

Latent diffusion training pipeline: a frozen VAE compresses a 512x512x3 RGB image by 48x into a 64x64x4 continuous latent z0, closed-form forward noising mixes Gaussian noise eps at random timestep t, and a UNet or DiT denoiser predicts eps_hat conditioned on prompt embeddings c under MSE loss.
Latent diffusion pipeline. A frozen VAE compresses pixels into continuous latents so the denoiser pays far less memory and compute per step.

Downsampling each spatial axis by 8x cuts positions by 82=64×8^2 = 64\times and quadratic self-attention entries by 642=4,096×64^2 = 4,096\times:

latent-work-state.py
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")
Output
scalars: 786,432 -> 16,384 (48x smaller)
spatial positions: 262,144 -> 4,096 (64x smaller)
self-attention entries: 4,096x smaller

Continuous 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 c∈RL×dtextc \in \mathbb{R}^{L \times d_{\text{text}}}. Inside each cross-attention block, noisy spatial patches emit queries Q=WQztQ = W_Q z_t while prompt tokens supply keys K=WKcK = W_K c and values V=WVcV = W_V c, 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.

Autoregressive left-to-right decoding contrasted with bidirectional masked text diffusion, where confident tokens unmask and revise in parallel.

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 1×11 \times 1 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 W0W_0 and injects a low-rank update ΔW=BA\Delta W = B A (with rank r≪dr \ll d) 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 W0W_0 when serving a single specialization.

Four optimizations make latent diffusion fast in practice:

  1. BF16/FP16 + compiled kernels: combine half precision, FlashAttention, and torch.compile to saturate tensor cores.
  2. Cross-attention K/V caching: prompt embeddings are constant across all NN solver steps, so project text keys and values once per prompt.
  3. Pre-allocated latent buffers: reuse fixed-shape scratch tensors per resolution bucket to avoid CUDA allocator stalls.
  4. Overlapped VAE decoding: decode finished latents on a separate CUDA stream while the denoiser processes the next batch.

Common pitfalls

  • Treating CFG scale ww as a probability: ww is an extrapolation multiplier; pushing w>12w > 12 overshoots the data manifold and clips colors.
  • Decoding predicted noise: the VAE decoder expects clean latent z0z_0, not raw ϵθ\epsilon_\theta.
  • 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.
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 5 answered
1.Given clean scalar x_0 = 2.0, Gaussian noise epsilon = -1.0, and alpha_bar = 0.64, what are x_t and SNR?
2.With a = 0.6, b = 0.8, and x_t = 1.0, a velocity model predicts v = -0.5. Compare true x_0 from v against mistakenly plugging v into the epsilon formula.
3.An ordinary CFG step has unconditional prediction [0.1, 0.2], conditional prediction [0.3, -0.1], and scale w = 4. What guided vector results?
4.A deterministic DDIM step (eta = 0) at x_t = 0.2, alpha_bar_t = 0.36, epsilon = -0.5 targets alpha_bar_s = 0.81. What are x_0 and x_s?
5.A VAE maps 768x512x3 RGB images to 96x64x8 latents, and plain encode-decode already blurs 8px text. What is the scalar reduction ratio and first diagnostic target?

5 questions remaining.

References

DiffusionGemma

Google · 2026

https://ai.google.dev/gemma/docs/diffusiongemma

Denoising Diffusion Probabilistic Models.

Ho, J., Jain, A., & Abbeel, P. · 2020 · NeurIPS 2020

https://arxiv.org/abs/2006.11239

Deep Unsupervised Learning using Nonequilibrium Thermodynamics.

Sohl-Dickstein et al. · 2015

https://arxiv.org/abs/1503.03585

Progressive Distillation for Fast Sampling of Diffusion Models.

Salimans, T., & Ho, J. · 2022 · ICLR 2022

https://arxiv.org/abs/2202.00512

Flow Matching for Generative Modeling

Lipman, Y., Chen, R. T. Q., Ben-Hamu, H., Nickel, M., & Le, M. · 2022

https://arxiv.org/abs/2210.02747

Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow

Liu, X., Gong, C., & Liu, Q. · 2022

https://arxiv.org/abs/2209.03003

Scaling Rectified Flow Transformers for High-Resolution Image Synthesis

Esser, P., Kulal, S., Blattmann, A., et al. · 2024

https://arxiv.org/abs/2403.03206

High-Resolution Image Synthesis with Latent Diffusion Models.

Rombach, R., et al. · 2022 · CVPR 2022

https://arxiv.org/abs/2112.10752

Scalable Diffusion Models with Transformers.

Peebles, W., & Xie, S. · 2023 · ICCV 2023

https://arxiv.org/abs/2212.09748

Classifier-Free Diffusion Guidance.

Ho, J., & Salimans, T. · 2022 · NeurIPS 2021 Workshop

https://arxiv.org/abs/2207.12598

Denoising Diffusion Implicit Models.

Song, J., Meng, C., & Ermon, S. · 2021 · ICLR 2021

https://arxiv.org/abs/2010.02502

Adding Conditional Control to Text-to-Image Diffusion Models.

Zhang, L., et al. · 2023 · ICCV 2023

https://arxiv.org/abs/2302.05543

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.