4.5.15 · D2Generative Models

Visual walkthrough — Latent diffusion (Stable Diffusion)

2,540 words12 min readBack to topic

Step 1 — What is an image, really? (a grid of numbers)

WHAT. Before any maths, pin down the object we are manipulating. A colour image is a grid of tiny squares (pixels). Each pixel stores three numbers: how much Red, Green, Blue it glows. So a photo is a stack of three number-grids.

WHY. Everything downstream is "shuffling these numbers around." We must first count them, because the whole story is about that count being too big.

PICTURE. Look at the figure. The left board shows one grid, one pixel zoomed to reveal its three chalk-blue numbers . Multiply it out:

Each factor is doing a plain job: rows count how tall, columns how wide, and the is "one number per colour." That product — call it the dimension of the image, meaning "how many independent knobs describe it" — is our enemy.

Figure — Latent diffusion (Stable Diffusion)

Step 2 — Why is that number our enemy? (the cost of denoising)

WHAT. Diffusion generates images by starting from pure static and cleaning it up over many steps with a network called a U-Net. The expensive part is the U-Net's self-attention, where every spatial location "talks to" every other location.

WHY this matters. "Everyone talks to everyone" means: if there are locations, there are conversations. This is the single reason pixel-space diffusion is slow. We introduce the tool of counting pairs precisely because attention's cost is a count of pairs.

PICTURE. The figure draws dots and every arrow between them: arrows. Then dots: arrows. Double the dots, quadruple the work — that is what "" looks like.

Here is the number of spatial squares, and squaring it counts the ordered pairs that attention must compute. For a grid, , so is astronomical.

Figure — Latent diffusion (Stable Diffusion)

Step 3 — The escape: compress first, denoise later

WHAT. Instead of denoising the giant pixel grid, we first squeeze the image through an autoencoder into a much smaller grid called the latent , denoise there, then expand back.

WHY a VAE and not a zip file? A zip file gives back exact bytes but its output is a jumble — you cannot smoothly slide between two zipped files. Diffusion needs to travel continuously from noisy to clean, so it needs a latent world where nearby points decode to nearby images. The VAE's extra training term (we meet it in Step 5) forces exactly that smoothness.

PICTURE. The figure is a funnel: the big pixel grid enters the encoder , becomes the tiny latent grid , and the decoder pushes back out to a reconstructed image .

  • — the original image (dimension 786,432).
  • — the encoder network; read the script-E as "the squeezer."
  • — the latent, the compressed grid we will actually work with.
  • — the decoder network, "the un-squeezer."
  • (x-with-a-hat) — the rebuilt image; the hat means "an estimate of," and means "roughly equals."
Figure — Latent diffusion (Stable Diffusion)

Step 4 — How big is the shrink? (the book-keeping)

WHAT. Stable Diffusion uses a downsampling factor : each side of the grid is divided by , and the compressed grid carries learned channels (not the original 3 colours).

WHY and ? These are the numbers that keep the picture perceptually intact while giving the biggest safe reduction. Let us just do the arithmetic so the payoff is concrete.

PICTURE. The figure shows the block shrinking to a block, with both totals chalked underneath.

Now compare the two worlds:

and — the part that really matters — the number of spatial locations drops from to , a factor of . Feeding that into the rule from Step 2:

Each symbol: = pixel-grid locations, = latent-grid locations, the square is the "pairs" from Step 2, and the ratio is how many times cheaper the attention becomes.

Figure — Latent diffusion (Stable Diffusion)

Step 5 — Why the latent world is smooth (the KL guardrail)

WHAT. The VAE is trained with two pulls at once: (1) rebuild the image accurately, (2) keep every latent close to a standard bell-curve (a Gaussian centred at 0 with spread 1).

WHY. Pull (1) alone would let the encoder scatter latents anywhere it likes, leaving holes — regions that decode to garbage. Pull (2), written with the reconstruction-plus-KL recipe, herds all latents into one soft blob with no holes. We need the KL tool specifically because it measures how far a distribution is from the target bell-curve and can be minimised.

PICTURE. Left board: a plain autoencoder — latents in scattered islands, arrows into empty "holes" produce chalk-scribble garbage. Right board: the VAE — latents packed into one smooth cloud; every point in between decodes to something sensible.

  • — squared error, "how wrong is the rebuild" — small = faithful.
  • — the spread of latents the encoder assigns to image .
  • — the target: a standard Gaussian, our "no-holes" reference.
  • — the KL divergence, a number that is when the two distributions match and grows as they drift apart.
Figure — Latent diffusion (Stable Diffusion)

Step 6 — Diffusion inside the small world (add noise, learn to remove it)

WHAT. In the latent grid we corrupt the clean latent by mixing in random static, over tiny steps, until nothing remains but static. A U-Net then learns to predict the static so we can subtract it back off.

WHY predict the noise, not the image? The forward corruption is a clean linear blend, so the noise is a fixed known target during training — easy to learn against. This is the same DDPM objective, just living in the 16k-dimensional latent instead of 786k-dimensional pixels.

PICTURE. A left-to-right filmstrip: (clear latent), progressively noisier , ending at (pure static). Underneath, the exact mixing rule.

  • — the step number, from (clean) up to (all static).
  • ("alpha-bar") — a scheduled number sliding from near (early, mostly signal) to near (late, mostly noise).
  • — the surviving fraction of the real latent.
  • — the injected fresh noise; the two square-roots are chosen so signal-power + noise-power stays balanced.
  • — standard Gaussian noise, one independent draw per latent number.

The U-Net is trained to output exactly that :

Here = the network's weights, = the text instruction (next step), and the squared bars again mean "how far off the guess is."

Figure — Latent diffusion (Stable Diffusion)

Step 7 — Steering with words (cross-attention to CLIP)

WHAT. So far denoising is blind — it would produce some plausible image. To obey "a corgi in a spacesuit," we feed the U-Net a text embedding from the CLIP encoder and let each latent square look up which words to obey via cross-attention.

WHY attention here? Different regions of the image need different words: the head must attend to "spacesuit," the body to "corgi." Attention is precisely the tool that lets each location choose what to listen to, with a weight for every word.

PICTURE. The latent grid on the left; the word tokens on the right. Chalk-pink arrows of varying thickness (attention weights) run from one grid square to the words it "reads." Thick arrow = strong influence.

  • (query) — comes from the image latent: "what am I, and what do I need?"
  • (key) — comes from the text: "what does each word offer?"
  • (value) — the text content actually pulled in once a match is found.
  • — every square-to-word match score.
  • — divides by the square-root of the feature size to keep the scores from blowing up.
  • — turns raw scores into positive weights summing to (a proper "how much to listen" mix).

To dial the obedience up, classifier-free guidance blends the with-text and without-text predictions — but that is a separate knob; here the machinery is the cross-attention itself.

Figure — Latent diffusion (Stable Diffusion)

Step 8 — Walking the noise back off (one reverse step)

WHAT. Generation runs the corruption backwards: from static , at each step subtract the predicted noise and rescale, landing at the clean latent .

WHY this exact formula? The forward mix in Step 6 is a known linear equation; algebraically inverting "signal + noise" for one step gives precisely the rule below. Each piece undoes one piece of the forward blend.

PICTURE. One reverse hop drawn as a vector diagram: start at , the chalk-yellow arrow removes the predicted-noise component, the whole thing is rescaled, and a small chalk-blue wobble adds diversity — arriving at , a little cleaner.

  • — the U-Net's noise guess for this step.
  • — the per-step signal-retention (single step, no bar).
  • — exactly the slice of noise added at step , peeled off.
  • — restores the scale the forward step had shrunk.
  • — a fresh Gaussian nudge; set and you get the deterministic DDIM variant.

Edge cases, walked explicitly:

  • First step (): is pure static, , so almost the whole bracket is "remove noise" — the model makes a bold first guess of the image's shape.
  • Last step (): we set (no wobble at the very end) so the final is crisp, not re-noised.
  • everywhere: fully deterministic — same seed, same image (DDIM).
  • Text dropped (): the machinery still runs; it just produces some unconditioned image with no steering.
Figure — Latent diffusion (Stable Diffusion)

Finally, decode once: — the small clean latent is blown back up to the full picture.


The one-picture summary

Everything above is one loop. Text becomes a guide ; random static enters the small latent world; the U-Net (steered by ) removes noise over reverse steps; the decoder expands the clean back to pixels. All the heavy lifting happens in the -number world, never the -number one — that is the entire idea.

Figure — Latent diffusion (Stable Diffusion)
Recall Feynman retelling — say it like you'd explain to a friend

A photo is just a huge pile of numbers — over three-quarters of a million of them. Cleaning noise off that pile is slow, mostly because the "everyone-looks-at-everyone" step costs the square of how many spots there are. So we cheat: a squeezer network folds the photo down to a tiny grid — sixteen thousand numbers instead of seven-hundred-thousand — a grid that's been trained (with a bell-curve guardrail so there are no garbage holes) to keep only the meaning, not the exact pixels. We do the whole noisy-to-clean cleanup in that little world, where the squared-cost is thousands of times smaller, and we let each little grid-cell read the text prompt through attention so it knows whether to become fur or metal. Each cleanup step just subtracts the network's best guess of the leftover static, rescales, and adds a pinch of randomness for variety — turning the randomness pinch off at the very end for a sharp finish. When the little grid is clean, an un-squeezer network blows it back up to a full picture. Small world for the hard work, big world only at the very end.


Prompt of the corgi
shows the full pipeline: CLIP-encode text → sample → denoise 50 steps → decode .
Why dominates
self-attention compares every spatial location with every other, so cost grows as the square of the location count.
What the KL term buys us
a hole-free, smooth latent space so denoising never wanders into garbage regions.
Why predict not
the forward mix is linear, making the added noise a clean, fixed learning target.
Effect of
deterministic DDIM sampling — same seed gives the same image.