4.5.15 · D3Generative Models

Worked examples — Latent diffusion (Stable Diffusion)

3,430 words16 min readBack to topic

This is the "run the numbers" companion to Latent diffusion (Stable Diffusion). The parent note told you why latent diffusion works. Here we grind through every kind of calculation it can throw at you — compression ratios, noise schedules, the reverse-step arithmetic, attention costs, and the degenerate edge cases where formulas quietly break.

Before we compute anything, one promise: every symbol below was defined in the parent, but I re-anchor each one the moment it appears. If you have never seen or a softmax before, you will still be able to follow from line one.


The scenario matrix

Every problem in this topic falls into one of these case classes. The worked examples below are each tagged with the cell they cover, and together they hit all of them.

# Case class What makes it tricky Covered by
A Compression sizing — pick , get latent shape integer division, channel count Ex 1
B Dimension / cost ratio — pixel vs latent linear (conv) vs quadratic (attention) scaling Ex 2
C Forward noising, mid schedule () mixing signal and noise weights Ex 3
D Forward noising, limiting values ( and ) degenerate: pure signal / pure noise Ex 4
E One reverse (denoising) step the scary rescale-and-subtract formula Ex 5
F Reverse step at (last step) , no fresh noise added Ex 6
G Cross-attention shapes & a softmax matrix dimensions must line up; softmax sums to 1 Ex 7
H Classifier-free guidance blend the knob, and large- limits Ex 8
I Real-world word problem — VRAM / time budget translate English into the ratios above Ex 9
J Exam twist — "spot the broken assumption" zero/degenerate input that voids a formula Ex 10

Example 1 — Case A: compression sizing

Forecast: guess the latent height/width and the total element count before reading on.

Step 1 — find latent height and width. Why this step? "Downsampling by " literally means each side is divided by . The symbol (a plain number, here 8) is the shrink factor per spatial axis. We divide, not subtract, because it is a ratio of resolutions.

Step 2 — attach the channel count. The latent has channels (learned features, not RGB). So the latent tensor is Why this step? Spatial size alone is not the full tensor; every one of the grid locations carries a length- vector.

Step 3 — count elements. Why this step? "How many numbers" = product of all three dimensions.

Verify: The input had numbers. Ratio . That matches the "48× fewer dimensions" the parent quotes — a good sanity check that was applied correctly.


Example 2 — Case B: dimension vs cost ratio (linear vs quadratic)

Forecast: the attention ratio is one of these — , , or . Guess which.

Step 1 — spatial-location drop. Why this step? Convolutions touch each spatial location a fixed amount of times, so their cost is linear in . The ratio of costs is just the ratio of : a saving.

Step 2 — attention cost. Self-attention lets every location compare with every other location: queries keys comparisons. So Why this step? The matrix (from the attention formula) is . Its size — and the softmax over it — grows with the square of . That squared scaling is the whole reason latent space is a bigger win for the attention layers than for the convolutions.

Verify: , and exactly. The linear saving () and the quadratic saving () bracket the real speedup, because a U-Net mixes both layer types — consistent with the parent's "order of magnitude or more."


Example 3 — Case C: forward noising, mid-schedule

Forecast: will be closer to or dominated by noise?

Step 1 — recall the forward formula. Why this step? This is the DDPM forward equation the parent stated. is the signal-retention dial. The two square roots are weights: keeps some of the clean value, injects noise. They are chosen so the variance stays controlled (see the figure).

Figure s01 — what it shows: the two curves plot the signal weight (cyan) and the noise weight (amber) across the whole dial . Read left-to-right: at the right edge the cyan curve is high (all signal), at the left edge the amber curve is high (all noise). The dashed white line marks this example's , where the cyan dot sits at and the amber dot at — exactly the weights we use in Step 2.

Figure — Latent diffusion (Stable Diffusion)

Step 2 — compute the two weights. Why this step? was chosen so both roots are clean numbers — it lets us see the blend, signal weight and noise weight. (They don't sum to 1; it's the squares that do, which is what keeps the total variance sensible.)

Step 3 — blend. Why this step? Just plug the weights into the formula.

Verify: ✓ (variance bookkeeping holds). With signal weight the clean part contributes ; noise contributes an equal , so we are near the halfway point of the schedule — signal and noise comparable, exactly the "mid-schedule" regime.


Example 4 — Case D: forward noising, the two limits

Forecast: which one returns the clean value untouched?

Step 1 — case . Why this step? means "keep 100% signal, 0% noise." The noise weight deletes entirely. So passes through unchanged — the degenerate "no noise yet" case.

Step 2 — case . Why this step? means "keep 0% signal, 100% noise." The signal weight vanishes; is pure noise, carrying zero memory of . This is why generation starts from : at the end of the forward process the original image is gone.

Verify: At , exactly (recoverable). At , exactly (all noise). The dial behaves monotonically between the two, matching Ex 3's midpoint.


Example 5 — Case E: one reverse (denoising) step

Forecast: should move toward the clean value (closer to ) or away?

Step 1 — write the DDPM reverse step. Why this step? is the per-step signal factor (one timestep), while is the cumulative one. The bracket subtracts the predicted noise, the rescales back up, and re-injects a little randomness for diversity.

Figure s02 — what it shows: it lays out the reverse step as a left-to-right pipeline of boxes. Box 1 is the noisy input . The first arrow ("peel predicted noise") lands on box 2, where we have subtracted to get . The second arrow ("restore scale") multiplies by to reach . The third arrow ("diversity") adds to reach the final . The italic caption at the bottom ties it back to Ex 3/4/6 so you see the same coordinate travel clean → noised → denoised.

Figure — Latent diffusion (Stable Diffusion)

Step 2 — the noise-removal coefficient. Why this step? This coefficient scales how much of the predicted noise to peel off. is small (only one step's worth of noise came in), so we remove only a sliver.

Step 3 — subtract inside the bracket. Why this step? The U-Net's job was to estimate the noise sitting in . Multiplying that estimate by the coefficient from Step 2 tells us how much noise this single step is responsible for; subtracting it removes exactly that slice, leaving a slightly cleaner latent. We subtract (not add) because we are undoing the forward noising.

Step 4 — rescale. Why this step? Removing noise shrinks the vector's magnitude; the factor restores the expected scale.

Step 5 — add stochasticity.

Verify: In Ex 3 this same coordinate was noised to from clean . One reverse step nudged it to ; the deterministic part alone () moved toward relative to the noise-inflated — correct direction. The final wiggle up is the injected term, as designed.


Example 6 — Case F: the final step ()

Forecast: will the answer equal the deterministic part of Ex 5?

Step 1 — reuse the deterministic bracket from Ex 5. Why this step? Nothing changed except ; the noise-removal and rescale are identical.

Step 2 — drop the stochastic term. Why this step? At the very end we want a clean, deterministic latent to hand to the VAE decoder . Any leftover random would smear the final image, so by construction. This is the degenerate edge case of the reverse formula.

Verify: equals exactly the deterministic core of Ex 5 with the noise removed. So Ex 5's answer ✓ — internally consistent.


Example 7 — Case G: cross-attention shapes and a softmax

Forecast: how big is — is it or ?

Step 1 — line up the shapes. comes from the image latent: . comes from text: (after projecting the 768-dim tokens to ). Then Why this step? Matrix product has shape (rows of ) (rows of ) . Each latent location (row) gets a similarity score against each of the 77 text tokens (column). That is literally "which words does this patch attend to."

Step 2 — softmax one row. The softmax of scores is . Why this step? Softmax turns raw scores into a probability distribution over tokens: exponentiate (so larger scores dominate, and everything is positive) then normalize (so it sums to 1). The in the attention formula would divide scores first; here we softmax the given post-scaling scores directly.

Verify: The three weights sum to ✓ — a valid probability distribution. The highest-score token (the "2") gets the largest weight, as it must.


Example 8 — Case H: classifier-free guidance blend and its limits

Forecast: which ignores the text prompt entirely?

Step 1 — case . Why this step? multiplies the "push toward the prompt" term by zero, deleting it. What remains is the unconditional prediction — the image ignores the text. This is the degenerate no-guidance case.

Step 2 — case . Why this step? At the blend algebraically collapses to . So is just ordinary text conditioning — no extra amplification, the plain prompt-following prediction.

Step 3 — case . Why this step? pushes past along the same direction "away from unconditional, toward the prompt," exaggerating it. This is why the SD default gives strongly prompt-faithful (sometimes over-saturated) images: we overshoot the conditioned prediction on purpose.

Verify: As a linear function of , . Check: , , all lie on that line ✓. Monotone increasing in , matching "more guidance = stronger prompt pull."


Example 9 — Case I: real-world VRAM / time word problem

Forecast: will the pixel version fit in a 24 GB consumer GPU?

Step 1 — pixel-space attention matrix bytes. Convert: GiB. Why this step? The matrix is ; storing it costs entries bytes. This is the quadratic blow-up from Ex 2 turned into concrete memory.

Step 2 — latent-space attention matrix bytes. Why this step? Same formula, smaller . Because the memory grows as , a smaller shrinks the matrix by .

Step 3 — reduction factor. Why this step? Same from Ex 2 — now interpreted as memory, not FLOPs.

Verify: GiB GB, so pixel-space attention at this resolution cannot fit on a consumer GPU — while MiB fits trivially. The reduction is exactly the quadratic ratio of Ex 2 ✓. This is why latent diffusion made high-res text-to-image possible on ordinary hardware.


Example 10 — Case J: exam twist — spot the broken assumption

Forecast: guess the one line that becomes impossible.

Step 1 — evaluate the noise weight. Why this step? The square root of a negative number is not a real value — the noise weight is undefined. The forward formula silently assumes .

Step 2 — derive the valid range. We need both weights real: (so is real) and (so the noise weight is real). Together: Why this step? Recall with each , so every factor is in and their product always lands in . The value proves at least one — an invalid schedule that leaves the box.

Verify: At the two legal endpoints the formula gave clean, finite answers in Ex 4. At it produces , non-real — so the range is exactly the safe domain, and the misconfigured schedule is the true bug. The formula was never wrong; the input violated its assumption.


Recall Self-test

, feed : latent spatial size? ::: , so . : signal weight ? ::: . gives ? ::: pure noise (all signal weight vanishes). Attention cost scales like? ::: (quadratic in spatial locations). What is ? ::: the small positive per-step noise-variance fraction; . CFG with gives? ::: the plain conditioned prediction . Valid range of ? ::: ; outside it a square root goes non-real.

See also: Denoising Diffusion Probabilistic Models (DDPM) for the forward/reverse formulas, U-Net Architecture for where the attention lives, CLIP Text Encoder and Attention Mechanisms for Ex 7, Variational Autoencoders (VAE) for the encode/decode ends, and DDIM Sampling for the deterministic () variant hinted at in Ex 6.