Course contents 30 / 34

30 / 34 · Diffusion Models

Latent diffusion and Stable Diffusion

Run diffusion in the latent space of an autoencoder instead of on pixels, condition it on text, steer it with classifier and classifier-free guidance, sample it in tens of steps, and edit images with the same model.

On this page 9

A diffusion model is a VAE with a fixed encoder: the noising chain plays the encoder, and the many-step denoiser is the decoder (VAE note). It generates sharp and diverse images, and it is slow. Every step runs a network over every pixel, and a 512×512512 \times 512 colour image has 512⋅512⋅3=786,432512 \cdot 512 \cdot 3 = 786{,}432 of them. Most of that work goes into detail nobody looks at, such as the exact grain of grass or the noise of a camera sensor.

Latent diffusion (Rombach et al., 2022) trains the diffusion model in the latent space of an autoencoder instead. In Stable Diffusion the latent of that image is 64×64×464 \times 64 \times 4, which is 16,38416{,}384 numbers, 48 times fewer. The latent is also kept close to a simple distribution by the autoencoder’s own training, which may make it easier for diffusion to model (Конспект курса «Байесовские методы в анализе данных», 2026, лекция 6). Stable Diffusion is this design with a text encoder attached; the sizes in this note are those of its versions 1.x and 2.x.

Two kinds of compression#

A trained image model compresses in two senses. Perceptual compression throws away high-frequency detail that changes many bits of an image and almost nothing that a person perceives. Semantic compression keeps the layout and content: which objects, where, in what style. A likelihood-based model in pixel space is charged for every bit, and Rombach et al. find that most of those bits belong to the perceptual part. Latent diffusion gives each part to a model suited to it: an autoencoder for the first, a diffusion model for the second.

The savings are larger still for attention. Self-attention over the 64×6464 \times 64 latent grid compares 40962≈1.7⋅1074096^2 \approx 1.7 \cdot 10^7 pairs of positions; over the 512×512512 \times 512 pixels it would compare 262,1442≈6.9⋅1010262{,}144^2 \approx 6.9 \cdot 10^{10}, 4096 times more. Pixel-space diffusion models therefore attend only at coarse resolutions. Even in the latent, one attention map of 1.7⋅1071.7 \cdot 10^7 entries takes 67 MB in 32-bit floats, per head and per image, which is why libraries offer to compute attention in slices at some cost in speed.

The autoencoder#

The first stage is trained once and then frozen. Its loss has three parts. A reconstruction term compares the output with the image. A perceptual loss compares deep features of the two, as LPIPS does. A patch-based adversarial loss has a discriminator judge small patches, so that reconstructions stay sharp instead of averaging into blur.

The latent is kept near a simple distribution in one of two ways: a slight KL penalty toward N(0,I)\mathcal N(0, I), as in a VAE with a very small weight on the KL term, or a vector-quantization layer, as in VQ-VAE. Unlike a VAE used as a generator, this autoencoder is not asked to make good samples from its prior: the diffusion model is the prior. Because the KL penalty is weak, the latents do not have unit variance, and Stable Diffusion multiplies them by a fixed constant so that diffusion starts from data of roughly unit variance.

The downsampling factor ff, the ratio of image side to latent side, sets the split between the two models. With f=1f = 1 the diffusion model still does all the perceptual work and trains slowly; with f=32f = 32 the autoencoder loses information that the decoder cannot restore. Rombach et al. find ff between 4 and 16 a good balance, and f=4f = 4 and f=8f = 8 best.

Diffusion in the latent#

Write E\mathcal E for the encoder, D\mathcal D for the decoder, z0=E(x)z_0 = \mathcal E(x) for the latent of an image xx, and τ(y)\tau(y) for the encoded condition yy, such as a prompt. Training is the DDPM objective with zz in place of xx:

L=Ez0, ε, t∥ε−εθ(zt,t,τ(y))∥2,zt=αˉt z0+1−αˉt ε.\begin{aligned} \mathcal L &= \mathbb E_{z_0,\, \varepsilon,\, t}\big\lVert \varepsilon - \varepsilon_\theta\big(z_t, t, \tau(y)\big)\big\rVert^2 , \\ z_t &= \sqrt{\bar\alpha_t}\, z_0 + \sqrt{1 - \bar\alpha_t}\,\varepsilon . \end{aligned}

Generation draws zT∼N(0,I)z_T \sim \mathcal N(0, I), runs a sampler in the latent space and decodes once at the end, x^=D(z0)\hat x = \mathcal D(z_0). The network is a U-Net, convolutional, with attention layers at the lower resolutions.

Figure

Latent diffusion: Stable Diffusion at 512×512

Training and generation in the latent spaceTraining: a 512×512 image is encoded into a 64×64×4 latent, noise is added, and a U-Net learns to predict that noise, receiving the text through cross-attention. Generation: a latent drawn from normal noise goes through 20–50 U-Net steps with a scheduler and classifier-free guidance, and the decoder turns the result into an image.image512×512×3encoder E÷8 per sidelatent z₀64×64×4add noiseup to step tU-Netpredicts the noise εprompttexttext encoder77 vectorspure noiseN(0, I), step TU-Net + scheduler20–50 steps, CFGz₀64×64×4decoder D×8 per sideimage512×512×3cross-attentiontraininggenerationTraining and generation in the latent spaceTraining: a 512×512 image is encoded into a 64×64×4 latent, noise is added, and a U-Net learns to predict that noise, receiving the text through cross-attention. Generation: a latent drawn from normal noise goes through 20–50 U-Net steps with a scheduler and classifier-free guidance, and the decoder turns the result into an image.image512×512×3encoder E÷8 per sidelatent z₀64×64×4add noiseup to step tU-Netpredicts the noise εprompttexttext encoder77 vectorspure noiseN(0, I), step TU-Net + scheduler20–50 steps, CFGz₀64×64×4decoder D×8 per sideimage512×512×3cross-attentiontraininggeneration
Top, training: the frozen encoder shrinks the image eightfold per side into a 4-channel latent, noise of step t is added, and the U-Net, reading the text through cross-attention, predicts that noise. Bottom, generation: 20–50 guided sampler steps on a latent of noise, then one decoder pass. Diffusion sees 16,384 numbers instead of 786,432.

Conditioning through cross-attention#

The condition enters through cross-attention (if you have taken the NLP course, its attention note is background; the formula below is all this note uses): the queries come from the U-Net features φ(zt)\varphi(z_t) of the latent, flattened over positions, and the keys and values from the encoded condition:

Attention(Q,K,V)=softmax⁡(QK⊤d)V,Q=WQ φ(zt),K=WK τ(y),V=WV τ(y).\begin{aligned} \mathrm{Attention}(Q, K, V) &= \operatorname{softmax}\Big(\frac{Q K^\top}{\sqrt d}\Big) V, \\ Q &= W_Q\, \varphi(z_t), \\ K &= W_K\, \tau(y), \\ V &= W_V\, \tau(y) . \end{aligned}

Every position of the latent attends over the tokens of the prompt, so different regions can follow different words. In Stable Diffusion τ\tau is a frozen text encoder that turns a prompt into 77 token vectors: CLIP ViT-L/14 with 768 dimensions in versions 1.x, OpenCLIP ViT-H/14 with 1024 in versions 2.x. The same mechanism accepts other conditions, such as class labels, segmentation maps or low-resolution images.

Since every token reaches the U-Net as its own vector, a word can be emphasised or toned down after encoding, without retraining. A common rule moves the token’s vector away from, or toward, the vector at the same position for an empty prompt, τ(y)i←τ(∅)i+wi (τ(y)i−τ(∅)i)\tau(y)_i \leftarrow \tau(\varnothing)_i + w_i\,\big(\tau(y)_i - \tau(\varnothing)_i\big), with wi>1w_i > 1 to boost the word. The change acts through cross-attention: the key decides how much the latent attends to the token, the value what it reads from it.

Classifier guidance#

A conditional model sampled as it is follows its condition only loosely. Suppose we have an unconditional diffusion model and want class yy. Bayes’ rule at noise level tt gives pt(z∣y)=pt(y∣z) pt(z)/p(y)p_t(z \mid y) = p_t(y \mid z)\, p_t(z) / p(y). Take the logarithm and the gradient in zz; the term log⁡p(y)\log p(y) does not depend on zz and drops out:

∇zlog⁡pt(z∣y)=∇zlog⁡pt(z)+∇zlog⁡pt(y∣z).\nabla_z \log p_t(z \mid y) = \nabla_z \log p_t(z) + \nabla_z \log p_t(y \mid z) .

The conditional score is the unconditional one plus the gradient of a classifier that sees the noisy input. Classifier guidance (Dhariwal and Nichol, 2021) trains such a classifier pϕ(y∣zt,t)p_\phi(y \mid z_t, t) on noised data and adds its gradient, multiplied by a scale ss, to the score at every sampling step. Through the noise–score relation sθ=−εθ/1−αˉts_\theta = -\varepsilon_\theta / \sqrt{1 - \bar\alpha_t}, the guided noise prediction is

ε^=εθ(zt,t)−s 1−αˉt  ∇zlog⁡pϕ(y∣zt,t).\hat\varepsilon = \varepsilon_\theta(z_t, t) - s\, \sqrt{1 - \bar\alpha_t}\; \nabla_z \log p_\phi(y \mid z_t, t) .

Why scale? Dhariwal and Nichol found that with s=1s = 1 the classifier gave the final samples reasonable probabilities, about 50%, yet the images did not look like the class; larger scales fixed this (§4.3). A scale is an exponent: s ∇log⁡pϕ(y∣z)=∇log⁡pϕ(y∣z)ss\, \nabla \log p_\phi(y \mid z) = \nabla \log p_\phi(y \mid z)^s, and pϕ(y∣z)sp_\phi(y \mid z)^s, renormalized over classes, is a sharper classifier. Guidance with s>1s > 1 follows the score of pt(z) pϕ(y∣z)sp_t(z)\, p_\phi(y \mid z)^s and favours inputs the classifier is very sure of: higher fidelity, less diversity. The cost is a second network, trained on noisy inputs at every noise level, and following its gradient can be read as an adversarial attack on it, so better classifier-based scores need not mean better images (Ho and Salimans, 2022, §1).

Classifier-free guidance#

Classifier-free guidance (Ho and Salimans, 2022) gets the classifier from the diffusion model itself. Bayes’ rule read the other way gives an implicit classifier, ∇log⁡pt(y∣z)=∇log⁡pt(z∣y)−∇log⁡pt(z)\nabla \log p_t(y \mid z) = \nabla \log p_t(z \mid y) - \nabla \log p_t(z). Substitute it into the guided score:

∇log⁡pt(z)+s ∇log⁡pt(y∣z)=∇log⁡pt(z)+s (∇log⁡pt(z∣y)−∇log⁡pt(z))=(1−s) ∇log⁡pt(z)+s ∇log⁡pt(z∣y).\begin{aligned} &\nabla \log p_t(z) + s\, \nabla \log p_t(y \mid z) \\ &\quad= \nabla \log p_t(z) + s\, \big(\nabla \log p_t(z \mid y) - \nabla \log p_t(z)\big) \\ &\quad= (1 - s)\, \nabla \log p_t(z) + s\, \nabla \log p_t(z \mid y) . \end{aligned}

Both scores come from one network. During training the condition is replaced by an empty one, ∅\varnothing, in a fraction of the steps, 10 or 20% in the paper (50% worked worse), so the network learns εθ(zt,t,y)\varepsilon_\theta(z_t, t, y) and εθ(zt,t,∅)\varepsilon_\theta(z_t, t, \varnothing) together. Multiplying the guided score by −1−αˉt-\sqrt{1 - \bar\alpha_t} gives the guided noise prediction:

ε~=εθ(zt,t,∅)+s (εθ(zt,t,y)−εθ(zt,t,∅)).\begin{aligned} \tilde\varepsilon ={}& \varepsilon_\theta(z_t, t, \varnothing) \\ &+ s\,\big(\varepsilon_\theta(z_t, t, y) - \varepsilon_\theta(z_t, t, \varnothing)\big) . \end{aligned}

s=0s = 0 is unconditional, s=1s = 1 the plain conditional model, and s>1s > 1 extrapolates beyond it; Ho and Salimans write s=1+ws = 1 + w. Stable Diffusion 1.x and 2.x are usually sampled with s=7.5s = 7.5. Each step costs two network evaluations, one with the prompt and one without.

A score at each noise level, not a target distribution. The identity holds separately at every step: the guided prediction is the score of rt(z)∝pt(z)1−s pt(z∣y)sr_t(z) \propto p_t(z)^{1-s}\, p_t(z \mid y)^{s}. For s=0s = 0 and s=1s = 1 the family rtr_t is the noising of one distribution. For other ss it is in general not the noising of any single distribution, so a sampler driven by the guided score need not end at p1−s p(⋅∣y)sp^{1-s}\, p(\cdot \mid y)^{s}, and the stochastic DDPM sampler and the deterministic DDIM sampler can end at different distributions with the same network (Bradley and Nakkiran, 2024). What the identity fixes is the direction of each step: toward regions that the implicit classifier at that noise level favours.

Worked example. Take the toy pair p=N(0,4)p = \mathcal N(0, 4) and p(⋅∣y)=N(2,1)p(\cdot \mid y) = \mathcal N(2, 1). The tilted density p1−s p(⋅∣y)sp^{1-s}\, p(\cdot \mid y)^{s} is Gaussian with precision (1−s)/4+s(1 - s)/4 + s, the sum of the weighted precisions, and mean 2s2s divided by that precision:

s=3s = 3s=7.5s = 7.5
tilted density: mean, sd2.40, 0.632.55, 0.41
stochastic sampler: mean, sd2.62, 0.522.67, 0.31
deterministic sampler: mean, sd2.99, 0.252.88, 0.01

The samplers use the exact Gaussian scores, so no network error enters, with the continuous version of DDPM’s linear schedule (β\beta from 0.10.1 to 2020, time from 00 for data to 11 for noise) and a start at N(0,1)\mathcal N(0, 1). Each rtr_t is Gaussian, and the clean distribution it would be the noising of has mean 2.402.40 at the last step but 2.582.58 at t=0.2t = 0.2 for s=3s = 3: no single target exists. The samplers agree with the tilted density in direction and go further. Guidance narrows the distribution and pushes it past the conditional mean, away from the unconditional one: samples more typical of the prompt and less diverse, the precision side of the precision and recall trade-off.

Figure

At the last step the guided score points to a narrower, shifted density

Densities at four guidance scaless = 0: unconditional: mean 0.00, sd 2.00; s = 1: conditional: mean 2.00, sd 1.00; s = 3: mean 2.40, sd 0.63; s = 7.5: mean 2.55, sd 0.41.-6-4-20246s = 0: unconditionals = 1: conditionals = 3s = 7.5Densities at four guidance scaless = 0: unconditional: mean 0.00, sd 2.00; s = 1: conditional: mean 2.00, sd 1.00; s = 3: mean 2.40, sd 0.63; s = 7.5: mean 2.55, sd 0.41.-6-4-20246s = 0: unconditionals = 1: conditionals = 3s = 7.5
Toy example: unconditional N(0, 4), conditional N(2, 1). At the last step the guided score at scale s is the score of the Gaussian p(x)^(1−s) p(x | y)^s: standard deviation 0.63 and mean 2.40 at s = 3, 0.41 and 2.55 at s = 7.5. Guided samplers end narrower still, differently for DDPM and DDIM.

Fewer steps#

DDPM samples with as many steps as it was trained with, 1000, because each step undoes one small Gaussian step. Fast samplers use a deterministic description of the same model: the probability-flow ODE, which has the same marginals ptp_t as the noising process at every time. It lives in the continuous time of that note: tt runs over [0,1][0, 1] from data to noise, β(t)\beta(t) is the noise rate and αˉ(t)=exp⁡(−∫0tβ(s) ds)\bar\alpha(t) = \exp\big(-\int_0^t \beta(s)\, ds\big) the signal coefficient, so dαˉ/dt=−β(t) αˉ(t)d\bar\alpha/dt = -\beta(t)\,\bar\alpha(t). DDPM’s step ii of TT sits at time t=i/Tt = i/T, where αˉ(i/T)\bar\alpha(i/T) is the limit of DDPM’s product αˉi\bar\alpha_i (derived there). From here on a subscript means continuous time: zt=z(t)z_t = z(t) and αˉt=αˉ(t)\bar\alpha_t = \bar\alpha(t). With the score replaced by the scaled noise predictor the ODE reads

dzdt=−12 β(t) [z−εθ(z,t)1−αˉt].\frac{dz}{dt} = -\tfrac12\,\beta(t)\,\Big[z - \frac{\varepsilon_\theta(z, t)}{\sqrt{1 - \bar\alpha_t}}\Big] .

Integrating it from z1∼N(0,I)z_1 \sim \mathcal N(0, I) down to t=0t = 0 maps every noise latent to one sample, and a solver that takes large steps needs few network evaluations.

DDIM is Euler’s method in the right coordinates. Divide the latent by its signal coefficient and measure time by the noise-to-signal ratio:

zˉ=zαˉt,σt=1−αˉtαˉt,\begin{aligned} \bar z &= \frac{z}{\sqrt{\bar\alpha_t}} , \\ \sigma_t &= \sqrt{\frac{1 - \bar\alpha_t}{\bar\alpha_t}} , \end{aligned}

so that zˉ=z0+σt ε\bar z = z_0 + \sigma_t\,\varepsilon along the noising path. Differentiate zˉ\bar z by the product rule, substitute the ODE and dαˉt/dt=−βαˉtd\bar\alpha_t/dt = -\beta\bar\alpha_t; the terms in zz cancel:

dzˉdt=1αˉtdzdt+β z2αˉt=β εθ2αˉt (1−αˉt).\begin{aligned} \frac{d\bar z}{dt} &= \frac{1}{\sqrt{\bar\alpha_t}} \frac{dz}{dt} + \frac{\beta\, z}{2\sqrt{\bar\alpha_t}} \\ &= \frac{\beta\, \varepsilon_\theta}{2\sqrt{\bar\alpha_t\,(1 - \bar\alpha_t)}} . \end{aligned}

From σt2=1/αˉt−1\sigma_t^2 = 1/\bar\alpha_t - 1, differentiation gives 2σt dσt/dt=β/αˉt2\sigma_t\, d\sigma_t/dt = \beta/\bar\alpha_t, which is the same factor:

dσtdt=β2αˉt (1−αˉt).\frac{d\sigma_t}{dt} = \frac{\beta}{2\sqrt{\bar\alpha_t\,(1 - \bar\alpha_t)}} .

Dividing the two, the ODE becomes dzˉ/dσ=εθd\bar z/d\sigma = \varepsilon_\theta (Song, Meng and Ermon, 2021, Eq. 14). Euler’s method holds εθ\varepsilon_\theta at its value at σt\sigma_t over the step to an earlier time s<ts < t with its smaller σs\sigma_s, so zˉs=zˉt+(σs−σt) εθ\bar z_s = \bar z_t + (\sigma_s - \sigma_t)\,\varepsilon_\theta. Multiplying back by αˉs\sqrt{\bar\alpha_s} gives the DDIM update (their Eq. 12 without added noise):

z^0=zt−1−αˉt  εθ(zt,t)αˉt,zs=αˉs  z^0+1−αˉs  εθ(zt,t).\begin{aligned} \hat z_0 &= \frac{z_t - \sqrt{1 - \bar\alpha_t}\;\varepsilon_\theta(z_t, t)}{\sqrt{\bar\alpha_t}} , \\ z_s &= \sqrt{\bar\alpha_s}\;\hat z_0 + \sqrt{1 - \bar\alpha_s}\;\varepsilon_\theta(z_t, t) . \end{aligned}

Predict the clean latent, then noise it again to the level of time ss with the same predicted noise. The time ss can be any earlier time, so a 50-step schedule visits every twentieth of DDPM’s 1000 training steps, t=1,0.98,0.96,…t = 1, 0.98, 0.96, \dots DDIM is deterministic and maps each noise latent to one image. Running its update in the other direction, from an image toward noise, gives an approximate inversion: the ideal ODE can be integrated both ways, but each Euler step evaluates εθ\varepsilon_\theta at the start of the step, so the backward pass does not exactly undo the forward one.

Worked example. One-dimensional data N(0,0.52)\mathcal N(0, 0.5^2), the exact noise predictor, DDPM’s discrete linear schedule, z1z_1 (DDPM’s step TT) from its exact distribution and DDIM steps evenly spaced in tt. The samples should have standard deviation 0.50.5:

DDIM steps110501000
sd of the samples0.0020.3700.4710.4985
the point 0.8, inverted and regenerated0.440.710.80

A single step from pure noise returns z^0=E[z0∣z1]\hat z_0 = \mathbb E[z_0 \mid z_1], which is close to the mean of all data, and too few first-order steps shrink the samples toward that mean. The inversion row shows that even an exact noise predictor does not make the round trip exact with few steps.

Higher-order solvers. In λ=−log⁡σ\lambda = -\log\sigma, half the log signal-to-noise ratio, the exact solution of the ODE is an integral of e−λe^{-\lambda} times the noise predictor (Lu et al., 2022a, Eq. 3.4). DPM-Solver expands the noise predictor in a Taylor series in λ\lambda over each step and integrates the exponential weight exactly. Its first-order version is DDIM; the second- and third-order versions spend two or three network evaluations per step and need far fewer steps. DPM-Solver++ (Lu et al., 2022b) applies the idea to the predicted clean latent and reuses the previous step’s evaluation, which keeps it stable at the large guidance scales of text-to-image models. Lu et al. (2022b) report that guided sampling, pixel or latent, needs about 100 to 250 steps to converge with DDIM and 15 to 20 with DPM-Solver++. The network does not change between samplers, only the update rule between its evaluations, which is why diffusion libraries let the sampler, the scheduler, be swapped after training.

Distillation. The other way to cut steps changes the network. Progressive distillation trains a student to reproduce in one DDIM step what the teacher does in two, then repeats with the student as teacher, halving the steps each round; Salimans and Ho (2022) go from thousands of steps to 4. A consistency model (Song et al., 2023) learns a function that maps any point of a probability-flow trajectory directly to the trajectory’s start at t≈0t \approx 0, trained so that all points of one trajectory give the same output; it samples with one network evaluation, or a few for better quality.

Editing with the same model#

Image-to-image (SDEdit, Meng et al., 2022) encodes an existing image, noises it to an intermediate step, zt=αˉt z0+1−αˉt εz_t = \sqrt{\bar\alpha_t}\, z_0 + \sqrt{1 - \bar\alpha_t}\,\varepsilon, and runs the remaining denoising steps with a new prompt. The strength λ∈[0,1]\lambda \in [0, 1] chooses the step: with 40 sampling steps and λ=0.6\lambda = 0.6, the last 24 are run. Low strength keeps the composition; strength 1 ignores the input.

Inpainting changes only a masked region. At every step the latent outside the mask is replaced by the original latent noised to the same step, and only the masked part follows the model:

zt−1←(1−m)⊙zt−1orig+m⊙zt−1∗,zt−1orig=αˉt−1 z0+1−αˉt−1 ε,\begin{aligned} z_{t-1} &\leftarrow (1 - m) \odot z^{\text{orig}}_{t-1} + m \odot z^*_{t-1} , \\ z^{\text{orig}}_{t-1} &= \sqrt{\bar\alpha_{t-1}}\, z_0 + \sqrt{1 - \bar\alpha_{t-1}}\,\varepsilon , \end{aligned}

where mm is the mask downsampled to the latent grid, 11 where the image may change, and zt−1∗z^*_{t-1} is the sampler’s update. With f=8f = 8 the mask acts on 8×88 \times 8 pixel blocks, and the decoder blends the edge. Dedicated inpainting models instead receive the mask and the masked image as extra input channels.

LoRA fine-tunes the attention layers with low-rank updates W+αrBAW + \frac{\alpha}{r} B A (PEFT note) to teach a style or a subject from a few images. For a d×kd \times k weight it trains r(d+k)r(d + k) numbers instead of dkdk: with d=k=1280d = k = 1280 that is 0.6%0.6\% of the layer for r=4r = 4 and 5%5\% for r=32r = 32.

Textual inversion (Gal et al., 2023) freezes everything and learns only the embedding vv of a new token, such as <S*>, from three to five images of a concept. It minimizes the diffusion loss of prompts such as “a photo of <S*>” with vv in place of the token’s embedding (their Eq. 2); the token can then be used in any prompt.

What changed#

Pixel-space diffusionLatent diffusion
Numbers per step at 512×512512 \times 512786,432786{,}43216,38416{,}384, plus one decoder pass per image
Who removes imperceptible detailthe diffusion model, slowlythe autoencoder, once
Attentiononly at coarse resolutionsover the whole latent grid
Conditioning on textpossible, costlycross-attention to a frozen text encoder
Ceiling on detailthe networkthe decoder

The number of steps is set by the sampler in both columns: the same DDIM, DPM-Solver or distilled samplers apply.

Where it breaks#

The decoder sets a ceiling. With f=8f = 8 and four channels, every 8×88 \times 8 block of pixels, 192192 numbers, is described by 44 latent numbers. Detail smaller than a block, such as small printed text, a face a few blocks wide or an exact texture, exists in the output only if the decoder can produce it from those four numbers; the diffusion model cannot add what D\mathcal D cannot express. The same block size limits inpainting, whose mask edges fall on the latent grid.

The text encoder sets another. A frozen CLIP-like encoder with 77 tokens is trained to match images and captions, and struggles with counting, spatial relations and long prompts; cross-attention can only use what τ(y)\tau(y) encodes. Guidance trades diversity for adherence, and the best trade for a metric is not the strongest guidance. On class-conditional ImageNet, Ho and Salimans (2022, §4.1) get the best FID with weak guidance, w=0.1w = 0.1 to 0.30.3, and the best Inception score with w≥4w \ge 4; Stable Diffusion’s usual s=7.5s = 7.5 is far stronger than the best-FID setting. The toy example shows the extreme: at s=7.5s = 7.5 the deterministic sampler leaves a standard deviation of 0.010.01, almost one image.

What you should remember#

  • An autoencoder removes perceptual detail once; diffusion runs in its latent, 48 times smaller than the image in Stable Diffusion.
  • Text enters through cross-attention: queries from the latent, keys and values from the text encoder.
  • Classifier guidance adds s ∇log⁡pϕ(y∣zt)s\,\nabla \log p_\phi(y \mid z_t) to the score; classifier-free guidance gets that gradient as the conditional minus the unconditional score.
  • Guided samplers follow pt1−s pt(⋅∣y)sp_t^{1-s}\, p_t(\cdot \mid y)^{s} step by step, not a fixed target; guidance narrows and shifts the samples.
  • DDIM is Euler’s method for the probability-flow ODE in (zˉ,σ)(\bar z, \sigma); higher-order solvers and distillation cut the steps further.

Notebook#

The advanced diffusion notebook of the HSE-LAMBDA Deep Generative Models repository uses the Hugging Face Diffusers library. It has no saved outputs, so it documents the procedure only; cell numbers count every cell, markdown included, from 1.

  • Text-to-image (cells 5–9) with stabilityai/stable-diffusion-2-1-base in float32, 25 steps and guidance scale 7.5, with attention slicing to lower the peak memory. The markdown gives the text embedding as 77×76877 \times 768, the size for version 1.x; this 2.1 model has a 1024-dimensional encoder.
  • Schedulers (cells 10–12). The ODE in the markdown keeps only the noise term; the probability-flow ODE also has a term in ztz_t and a factor 12\frac12. swap_scheduler replaces the scheduler of the same pipeline object and returns it, so pipe_euler and pipe_dpm are one pipeline, and both images of the side-by-side are produced with DPM-Solver++.
  • Batch generation and prompt weighting with the Compel library (cells 13–16): each + multiplies a token’s weight by 1.1 and each - by 0.9, so ball-- has weight 0.810.81 and forest--- 0.7290.729, applied to the text-encoder output as described above.
  • Image-to-image (cells 17–20) on a 768×768768 \times 768 picture with strength 0.6, which runs 24 of 40 steps, and 1.0.
  • Inpainting (cells 21–22) with the same base checkpoint and 50 steps. Its U-Net has 4 input channels, so the pipeline uses the latent replacement above, not a mask-conditioned model.
  • A pixel-art LoRA in SD-XL fused with scale 0.8 (cells 23–24). The markdown says a LoRA trains about 0.2% of SD-XL’s parameters; this adapter has rank 32 and 85.1 million parameters, about 3.3% of the 2.6-billion-parameter U-Net (Podell et al., 2023).
  • Textual inversion (cells 25–26) with a concept token loaded into runwayml/stable-diffusion-v1-5, a repository now published as stable-diffusion-v1-5/stable-diffusion-v1-5, to which the old id redirects.

Next#

Text, masks and the strength of image-to-image say what should appear and roughly where, but not exactly where a given point of the image should end up. The next note, Point-based image editing: DragGAN and DragDiffusion, makes edits of the form “move this point there”: first by optimizing the latent code of a GAN, then by optimizing the noisy latent of a diffusion model, inverted with DDIM.

References#