Conditioning, guidance and latent diffusion

Image analysis

About this lecture

How do we ask for a particular kind of image, what does pushing harder do, and why do most image generators work in a compressed space?

  • A conditional denoiser takes the label as an extra input.
  • Classifier-free guidance: one network, label dropped at random during training; at sampling time push from “no label” towards “this label” with a weight w.
  • What w does: more typical samples, less diversity, and with large w samples more extreme than any real example.
  • Latent diffusion: diffusion in the latent space of an autoencoder (the VAE day); cheaper, and the finest detail comes from the decoder.

Slides titled The math give the formulas and proofs; the ideas are complete without them.

Recall: conditioning and guidance

From Diffusion models and generated detail: a conditional score = unconditional score + the score of the condition (Bayes). Guidance w > 0 pushes harder: samples crowd where the condition is most certain.

Conditional denoisers and two kinds of guidance

The label (a class, a treatment, a text, an image) is an extra input of the denoiser, learned from labelled pairs.

  • Classifier guidance: train a separate classifier that works on noisy images and add its gradient to the score. Needs a second network trained at every noise level.
  • Classifier-free guidance: train one network, and drop the label at random (say 10 % of the time), so it learns both the conditional and the unconditional denoiser. At sampling time, extrapolate:

\hat{\boldsymbol\varepsilon} = (1+w)\,\hat{\boldsymbol\varepsilon}(\mathbf x, y) - w\,\hat{\boldsymbol\varepsilon}(\mathbf x, \varnothing).

  • Example: \hat\varepsilon_\text{uncond} = 0.2, \hat\varepsilon_\text{cond} = 0.5, w = 3: 4 \cdot 0.5 - 3 \cdot 0.2 = 1.4. The guided prediction overshoots the conditional one, away from the unconditional.

Number line of the predicted noise for one pixel: without the label 0.2, with the label 0.5, guided with w = 3 at 1.4. The guided value lies beyond the conditional one, 3 times the step from no label to label further on.

Guided sampling as pseudocode

x = a random draw from N(0, 1)                     # pure noise
for every noise level, from high to low:
    ε_c = network(x, level, label)
    ε_u = network(x, level, no label)
    ε = (1 + w) · ε_c − w · ε_u                    # guidance
    x̂0 = clean estimate from x and ε
    x = step to the next level (as without guidance)
  • Two network evaluations per step; everything else is the sampler of the last unit.

The math: what classifier-free guidance targets

Scores combine like the predicted noises (each is -\hat{\boldsymbol\varepsilon}/\sqrt{1-\bar\alpha}):

(1+w)\nabla\log p(\mathbf x\mid y) - w\nabla\log p(\mathbf x) = \nabla\log\big[p(\mathbf x\mid y)^{1+w}p(\mathbf x)^{-w}\big].

By Bayes, p(\mathbf x\mid y) = p(y\mid\mathbf x)p(\mathbf x)/p(y), so

p(\mathbf x\mid y)^{1+w}p(\mathbf x)^{-w} \propto p(\mathbf x\mid y)\,p(y\mid\mathbf x)^{w}:

the class density sharpened by the classifier’s confidence. For two classes \mathcal N(\pm1, 1) with equal weights, p(A\mid x) = 1/(1+e^{-2x}) for the class at +1: points beyond the class mean get extra weight.

Caveat: applying the combination at every noise level is not the same as sampling this sharpened density (the noised version of a sharpened density is not the sharpened noised density). The demo shows both.

What w does

  • It sharpens the class towards points where the label is most certain, i.e. farthest from the other classes, not the most typical members.
  • Moderate w: cleaner, more typical-looking samples, less diversity: recall drops (the class’s border regions are no longer generated).
  • Large w: samples beyond the class mean, more extreme than almost any real example; in images: saturated contrast, caricatures.
  • Numbers (classes \mathcal N(\pm1, 1)): the sharpened density of the class at +1 compares x = 2 with its mean x = 1 as 0.61 (w = 0), 0.94 (w = 4), 1.45 (w = 8). From w = 4.6 on, a point beyond the mean is more likely than the mean itself.

The density of class A (Gaussian at +1, next to class B at −1) sharpened by p(A given x) to the power w, for w = 0, 4 and 8. With growing w it gets narrower and moves beyond the class mean; the density at x = 2 relative to x = 1 is 0.61, 0.94 and 1.45.

Try it: guidance in 1D, exactly

Guidance trades coverage for typicality

Conditioning on an image

The condition can be a measured image: a blurred or noisy image, another channel, a low-resolution image. The denoiser gets it as extra input and is trained on pairs (measurement, target).

  • Same rules as with a label: strong guidance gives confident, typical, possibly wrong detail.
  • This is the bridge to the next unit: restoration and “virtual staining” as conditional generation.
  • Text conditioning (image generators from a prompt) feeds text tokens into the network through attention between image patches and text tokens (recall attention).

Latent diffusion

An image of 256 \times 256 \times 3 = 196\,608 numbers; a latent of 32 \times 32 \times 4 = 4\,096: 48 times fewer.

  1. Train an autoencoder first (the VAE day).
  2. Run diffusion on the latent codes of the training images.
  3. Generate a latent by reverse diffusion, then decode it.
  • Each step is much cheaper; the diffusion model spends its capacity on layout and content, not on imperceptible pixel detail.
  • The latent codes of the training set form a cloud. Diffusion learns that cloud instead of assuming the VAE’s round Gaussian prior, so samples land where real codes are (fixing the VAE’s “nonsense far from the data”, VAE generation).

Diagram. 1: an autoencoder's encoder maps a 256×256×3 image to a 32×32×4 latent code, 48 times fewer numbers; the codes of the training images form a cloud. 2: generation runs diffusion from noise of size 32×32×4 to a new code, and the decoder turns it into a 256×256×3 image, whose finest detail comes from the decoder's habits.

Who draws the finest detail?

  • The decoder. It outputs a mean (VAE day): whatever the latent cannot represent is filled in by the decoder’s habits, learned from the training images, not by any measurement or by the diffusion model.
  • A crisp one-pixel membrane in a generated cell: the latent said “a cell of this shape here”; the decoder drew the membrane the way membranes looked in its training set.
  • Guidance in a latent model acts on the latent: strong guidance pushes codes to the extreme of the class (caricatures), and the decoder renders them faithfully.

Try it: latent diffusion on cell shapes

The math: guided Gaussians and the latent score

Guided Gaussian. p(x\mid y) = \mathcal N(m, s^2), p(x) = \mathcal N(0, 1). Then p(x\mid y)^{1+w}p(x)^{-w} \propto \exp\big(-\frac{(1+w)(x-m)^2}{2s^2} + \frac{w x^2}{2}\big): a Gaussian with precision \frac{1+w}{s^2} - w and mean \frac{(1+w)m/s^2}{(1+w)/s^2 - w}, normalisable only if s^2 < \frac{1+w}{w}. Example m = 1, s^2 = 0.5, w = 1: precision 3, variance 1/3, mean 4/3: narrower, and beyond the class mean.

Latent diffusion’s target. The encoder maps training image i to q(\mathbf z\mid\mathbf x_i) = \mathcal N(\boldsymbol\mu_i, \operatorname{diag}\boldsymbol\sigma_i^2); the codes form the aggregate posterior

q(\mathbf z) = \frac1N\sum_{i=1}^N\mathcal N(\mathbf z; \boldsymbol\mu_i, \operatorname{diag}\boldsymbol\sigma_i^2).

Noised to level σ it is again a mixture with variances \boldsymbol\sigma_i^2 + \sigma^2, and its score is the mixture score of the introduction: \sum_i r_i(\mathbf z)\,(\boldsymbol\mu_i - \mathbf z)/(\boldsymbol\sigma_i^2 + \sigma^2) (elementwise), with responsibilities r_i. A network learns this from the codes; the demo uses it exactly. Tiny \boldsymbol\sigma_i: the perfect model of a finite set of codes copies them.

Summary

  • Conditioning: the label is an extra input. Classifier-free guidance uses one network with the label dropped at random: (1+w)\cdotconditional - w\cdotunconditional.
  • It sharpens the class by the classifier’s confidence: more typical, less diverse (recall drops), and with large w more extreme than real data. Guided sampling does not even sample the sharpened density exactly.
  • An image can be the condition: restoration as conditional generation (next unit).
  • Latent diffusion learns the cloud of an autoencoder’s codes: 48× fewer numbers per step; the decoder draws the finest detail from its training habits.