KnowML

Diffusion & Video Inference

Follow one prompt, a cat on a mat, through the hundred forward passes it costs, and see which levers cut that bill, which of them cost a training run, and why five seconds of video is a far bigger problem than one picture.

⏱ 31 min readAssumes: the reverse process (12), roofline & arithmetic intensity (23)
Start reading

Type "a cat sitting on a mat" into an image generator and a few seconds later a 1024 by 1024 picture appears. Nothing in it was drawn the way a person draws. It started from a square of random noise and was cleaned up a little at a time, and each cleanup was one run of a large neural network. Chapter 12 explains why that works. This chapter is about what it costs.

Each cleanup is called a step, and a published sampler takes a lot of them: fifty is typical and the original sampler used a thousand. On top of that, the trick that makes the picture follow your prompt runs the network twice per step. So our one cat is roughly a hundred runs of a network with billions of parameters. Now ask for five seconds of that cat walking across the mat, and the same loop takes about half an hour on a single GPU.

We'll follow the cat prompt through that bill. First we count what we're being charged for, then we try the levers in order of what they cost you. A better numerical solver is free. A change to how guidance is applied is free too. Feature caching costs nothing in training and has a ceiling you can work out in advance. Distilling a new model costs a training run and some variety in the pictures, and so does changing the training objective so the paths become straight. After that comes the reason video is so much worse than a stack of images, and the last section is about running all this on a real machine.

You'll want chapter 12 (the reverse process) and chapter 23 (the roofline and arithmetic intensity) behind you. If you need one sentence for an interview, it's this: diffusion serving is compute-bound where LLM serving is bandwidth-bound, and that flips almost every instinct from chapter 31. By the end you should be able to say which of the levers are free, which cost a training run, and which quietly cost you quality.

01The bill, in forward passes

Let's price the cat prompt. The pipeline that turns it into a picture has three parts. A text encoder turns the words into vectors the rest of the system can use, and runs once. Pictures aren't built out of pixels directly. An autoencoder squeezes images into a much smaller grid of numbers called the latent, the denoising happens on that grid, and a decoder turns the final latent back into pixels, once, at the end. In the middle sits the denoiser, the large network that looks at the current noisy latent and says how to improve it. It runs once per step, and twice per step when guidance is on, as section 03 explains. Two of the three parts run once and the third runs dozens of times, so their costs aren't close.

That repetition is the budget. Chapter 12 makes the point in passing, and this chapter starts from it. One run of the network from input to output is a forward pass, and the number of forward passes needed to produce one output is the number of function evaluations, or NFE. NFE is what you're billed for. Most of what follows is a way of lowering it, and the chart below puts every method on one scale.

Every way of cutting the loop, on one log axis
1 10 100 1000 forward passes of the denoiser, per image (log scale, each gridline is 10x) DDPM ancestral, 1000 steps, guided the sampler as published 2000 DDIM, 50 steps, guided same weights, non-Markovian 100 DPM-Solver++, 20 steps, guided same weights, 2nd-order ODE 40 guidance-distilled, 20 steps the x2 folded into the weights 20 step-distilled, 4 steps new weights, a training run 4 one-step distilled new weights, adversarial loss 1 Top to bottom is 2000 passes down to 1, a factor of 2000. Every row below the second is a different kind of intervention, and the last two cost a training run to obtain.
The bars use a log scale, so each gridline is ten times the one before and the bottom bar sits at 1. Read the labels, because the lengths compress the differences. Rows one to three are one checkpoint sampled in different ways, and trying them costs nothing. The bottom three change the weights, which means a training run and a quality argument you have to have first.

Read the chart from the top. As published, the sampler takes 1000 steps, doubled by guidance, so our one cat costs roughly 2000 forward passes. Keep the same weights and swap in a different sampler, and DDIM gets it to 100 with 50 steps, while a second-order solver at 20 steps needs 40. Below those come different models: one with the factor of two folded into its weights, one that takes 4 steps, and one that takes a single step. Two thousand passes down to one is a factor of two thousand. Nobody gets all of it, and the rows aren't interchangeable, but a range that wide is why this is a subject and not a setting.

We'll go down the chart in order, starting with the rows that need no new weights. Our first question is how few steps the same network can get away with, and what one step does.

02What one step buys

Generating the cat means following a path from noise to a picture. Chapter 12 shows that this path is the solution of an ordinary differential equation, or ODE: a rule that says, at every point along the way, which direction to move next. Chapter 12's network supplies that direction, and the sampler follows it by taking small steps. A solver is the recipe for how to take them. Seen this way, the step count isn't a quality dial, and it probably shouldn't be tuned like one. It's how coarsely we chop the path into pieces, and fewer pieces mean a rougher approximation, the way a curve drawn with ten straight segments is rougher than one drawn with a hundred.

A smarter solver gets more out of each segment by also accounting for how the direction is changing, so it can use fewer of them. How many fewer has a clean answer, worked out below. In short, the simplest solver's error shrinks in proportion to the step size, while a solver that cancels one more term of the Taylor expansion shrinks with its square.

Derivation Why a second-order solver needs roughly the square root of the steps

Take the sampling ODE integrated from to in equal steps of size . Assume is smooth enough for a Taylor expansion, which is the usual assumption and the one that fails near .

  1. Why: plain Taylor. An Euler step keeps the first two terms and discards the rest, so it is wrong by on that single step.
  2. Why: you take steps and each contributes its own error. One power of is eaten by the step count, which is the standard result that local order two gives global order one.
  3. Why: a method that also cancels the term is locally wrong by , so the same accounting leaves .
  4. Why this is the payoff: equate the two error budgets and the second-order step count is the square root of the first. Ignore the constants and becomes .
The constants are not one and the smoothness assumption degrades at the ends of the schedule, so treat 32 as an order of magnitude rather than a number. It lands in the right place: DPM-Solver carries "Sampling in Around 10 Steps" in its own title, and reports 10 to 20 evaluations with a 4 to 16 times speedup over training-free samplers, with no change to the weights.

So a thousand steps of the simple solver buys about the same accuracy as thirty-odd steps of a second-order one, give or take constants. As the derivation says, treat 32 as an order of magnitude, and published results agree. DPM-Solver carries "Sampling in Around 10 Steps" in its own title and reports 10 to 20 evaluations, a 4 to 16 times speedup over training-free samplers, with no change to the weights. That's what the second and third rows of the chart are.

DDIM versus ancestral sampling

There's a catch hiding in that argument: it assumes the path we're integrating stays put. The original DDPM sampler doesn't. It injects fresh random noise at every step, which makes it ancestral: the trajectory is stochastic, so skipping steps doesn't approximate the same path more coarsely. It walks a different path.

DDIM removes the injected noise. Now the reverse process is deterministic, so the picture is a function of the starting noise alone, and skipping steps is now ordinary numerical error and no longer a different random walk. Its authors report samples 10 to 50 times faster in wall-clock terms than DDPM. This is why determinism buys steps. Once the path is fixed, a coarse integration is an approximation of one specific answer, so you can measure the error against a fine reference and reduce it with a better solver. With noise injected at every step there's no fixed answer to approximate. Every fast sampler on our chart is therefore deterministic, and the stochastic ones are still the better choice when you want variety more than speed.

Where quality falls off

Suppose we ask for the cat in only five steps. What goes wrong? Truncation error accumulates along the trajectory and not on the output, so under-stepping doesn't hand you a noisy version of the right image. It lands you somewhere else, with a clean version of a slightly different image. Composition drifts, fine texture thins and the match to the prompt weakens, while nothing looks broken. Cutting steps until the picture looks bad is the wrong test, because the picture stops being the right picture well before it stops looking plausible.

For samplers that need no extra training, the practical floor is around ten evaluations. Below that no amount of solver cleverness helps, because the error is no longer dominated by discretisation. Getting lower means changing the weights, and we'll get there in section 04. Before that, there's a factor of two we've been carrying since the opening without saying where it comes from, and it's the other free lever.

03Guidance doubles the count

A diffusion model trained on captioned images follows your prompt only loosely if you sample from it directly. Classifier-free guidance, from Ho and Salimans, tightens that. At every step it evaluates the model twice, once with the prompt ("a cat sitting on a mat") and once with an empty prompt, written , and then extrapolates away from the empty-prompt prediction and toward the prompted one:

Here is the current noisy latent, is the prompt, and is the network's output, its estimate of the noise. The guidance scale is free to choose. Evaluating twice is not free.

So 50 steps with guidance is 100 forward passes, and when a paper quotes a step count for a guided model, the real forward-pass count is double it. That's the most common accounting error in the subject. You can stack the prompted and empty inputs into one batch of two, which saves kernel launches (a kernel is one function launched on the GPU) and nothing else. Section 08 explains why that matters here and wouldn't for an LLM, since the arithmetic stays the same.

Folding the factor of two into the weights

If the second pass is the cost, we can train it away. Meng and colleagues train a student that's conditioned on the guidance scale to reproduce the combined output of both branches in one pass. Here the scale survives as an input and the second forward pass disappears. Guidance distillation seems to be standard in current open checkpoints. The FLUX.1 [dev] model card says the model was "trained using guidance distillation", and HunyuanVideo distils "the combined output for unconditional and conditional inputs into a single student model" and reports roughly 1.9 times acceleration from that alone.

What does the student lose? It can no longer do what the empty branch allowed. A guidance-distilled model has no empty-prompt branch to extrapolate from. Negative prompts, which put a description of what to avoid into that empty slot, stop working the way they did, and the guidance scale becomes a learned input with its own trained range instead of a free multiplier. People tune it anyway, well outside the range it was distilled over, and then report that the model is insensitive to guidance. The model is answering a question about a number it was taught to interpret differently.

The cheaper alternative, if you keep the two branches

If you want to keep both branches, you can at least use them less. Kynkäänniemi and colleagues found that guidance is "clearly harmful toward the beginning of the chain (high noise levels), largely unnecessary toward the end (low noise levels), and only beneficial in the middle". Restricting it to that middle interval improved ImageNet-512 FID from 1.81 to 1.40 in their setting. FID, the Fréchet inception distance, compares the statistics of generated images with those of real ones, and lower is better. Steps outside the interval need one pass instead of two, so the change is cheaper and, in their measurements, better, which is rare.

That's everything we can do without training anything new except guidance distillation. Samplers get us to about ten evaluations, and guidance accounts for the factor of two. To go lower, the network itself has to learn to take bigger jumps.

04Distillation: buying steps with a training run

Below roughly ten evaluations you can't integrate your way out, so we train a new model to take bigger jumps, and we pay for it in something other than compute. Distillation means training a student model to reproduce what a slower teacher model produces. The families below are a different answer each to one question: what should the student be trained to match?

Progressive distillation (Salimans and Ho, 2022) trains a student to take one step that lands where two teacher steps land, then makes that student the teacher and repeats, so each round halves the step count. They take a model from 8192 steps down to 4 and report an FID of 3.0 on CIFAR-10 at 4 steps. Consistency models (Song and colleagues, 2023) ask for something stronger. They train so that every point along a trajectory maps directly to that trajectory's endpoint, and if that holds, one evaluation is enough. They report a one-step FID of 3.55 on CIFAR-10 and 6.20 on ImageNet 64.

Latent consistency models (Luo and colleagues, 2023) apply the same property to an existing latent diffusion model instead of training from scratch, and get 2 to 4 step generation at 768 by 768 from about 32 A100 hours of distillation. Adversarial distillation (Sauer and colleagues, 2023, shipped as SDXL-Turbo) adds a discriminator, a second network that tries to tell the student's images from real ones, so the student is pushed toward looking like a real image as well as toward the teacher's answer. It runs in one to four steps and matches SDXL in four by their evaluation.

Later work mixes these. SDXL-Lightning describes itself as combining "progressive and adversarial distillation to achieve a balance between quality and mode coverage", which names the tradeoff in its own abstract. DMD2 adds a GAN loss to distribution matching and reports a one-step FID of 1.28 on ImageNet 64 and 8.35 zero-shot on COCO.

What a 4-step or 1-step model gives up, concretely

Sharpness isn't what suffers, which surprises people. DMD2's authors put their 4-step student at FID 19.32 and their 1-step student at 19.01, against an SDXL teacher at 19.36 with 50 steps and guidance scale 6. On a distribution metric the student is level with its teacher. Diversity is what moves, and the same paper says so: "our distilled generator experiences a slight degradation in image diversity compared to the teacher models". FID over thousands of samples isn't the metric that would show it.

Gandikota and Bau give the mechanism. They find that "distilled models commit to their final image structure almost immediately at the first timestep, while base models distribute structural decisions across many steps", and that distilled models "possess variational directions needed for diversity yet fail to activate them". Picture our cat prompt with four different seeds. A base model might put the cat in different places and poses. A distilled one decides on a layout in its first evaluation and has nothing left to reconsider it with.

A user will describe this as "every seed gives me the same picture". Seeds still change texture and small details, and it has stopped changing composition, because composition was settled in the first evaluation and there's only one. That matters for a gallery product, where the user regenerates until something surprises them, and far less for an interactive canvas where the user is steering. Decide which one you're building before you pick a step count.

Distillation fixes the step count by retraining the network on the sampler's behaviour. There's another approach: change what the network learns in the first place, so that the path it has to follow is easy to integrate. Straight lines are the easiest paths to integrate.

05Rectified flow: straighten the path, and the steps come free

Integrating a curve needs many steps, while a straight line needs only one at any resolution, because the direction never changes. Rectified flow is built on that observation. Liu, Gong and Liu proposed learning an ODE whose paths are "as straight as possible" between noise and data, and claim that recursively rectifying yields "nearly straight flows that give high quality results even with a single Euler discretization step". (An Euler step is the simplest solver step: move along the current direction for the whole step size.)

What does the straightening deserves a closer look, because it isn't the straight-line training target by itself. Training uses a linear interpolant: pick a noise sample and a data point, and draw the straight line between them. That sounds like it should produce straight paths, but it doesn't, for a subtle reason. Many different noise-to-data pairs pass through any given location in the noise, each heading to a different data point. Its best guess is the average direction over all of them, called the marginal velocity field, and following an averaged field curves. The pairing of noise samples with data points is called the coupling, and because it's random, the paths cross.

Reflow fixes the coupling. You run the learned ODE to see where each noise sample lands, then retrain on those pairs. Now each noise sample has one destination, the paths stop crossing, and the field they induce is straight by construction.

We can watch this happen in one dimension. Our code builds a small flow from noise to a three-point data set, [-2.0, 0.5, 3.0], on the linear interpolant. v_indep is the averaged field you get when noise is paired with data at random: the softmax-like weights in w work out how likely each data point is given where we are, and m is the expected endpoint. Solving that ODE once on a grid gives the coupling, the map from each starting noise value to where it lands. v_reflow then re-pairs the same starting points and endpoints along straight lines. Finally it measures how far each version's Euler solution with n steps is from a fine 2000-step answer, and the arc length of each path against the straight-line distance between its endpoints.

Try it Curved path, straight path, and the Euler error at one step
import numpy as np

# A 1-D flow from noise (t=0) to a 3-point data set (t=1), on the
# linear interpolant x_t = (1-t)z + t*x0 that rectified flow uses.
data = np.array([-2.0, 0.5, 3.0])

def v_indep(x, t):        # marginal velocity, z drawn independently
    s = max(1.0 - t, 1e-6)
    lp = -0.5 * ((x[:, None] - t * data[None, :]) / s) ** 2
    w = np.exp(lp - lp.max(1, keepdims=True))
    m = (w * data[None, :]).sum(1) / w.sum(1)      # E[x0 | x_t = x]
    return (m - x) / s

def euler(x0, n, v):
    x = x0.copy()
    for i in range(n):
        x = x + v(x, i / n) / n
    return x

grid = np.linspace(-6, 6, 4001)          # solve the ODE on a grid once
endp = euler(grid, 2000, v_indep)        # z -> x1(z), the coupling

def v_reflow(x, t):       # same endpoints, re-paired: straight by
    g = (1 - t) * grid + t * endp        # construction
    o = np.argsort(g)
    z = np.interp(x, g[o], grid[o])
    return np.interp(z, grid, endp) - z

rng = np.random.default_rng(0)
z = rng.normal(size=6000)
ref = euler(z, 2000, v_indep)

print("Euler steps    mean |error| vs the 2000-step solution")
print("               independent coupling   after reflow")
for n in (1, 2, 4, 8, 16):
    a = np.abs(euler(z, n, v_indep) - ref).mean()
    b = np.abs(euler(z, n, v_reflow) - ref).mean()
    print(f"{n:>7}                 {a:>8.4f}       {b:>8.4f}")

for name, v in (("independent", v_indep), ("reflowed", v_reflow)):
    x, L = z.copy(), 0.0                 # arc length of the path
    for i in range(2000):
        s = v(x, i / 2000) / 2000
        L += np.abs(s).mean()
        x = x + s
    print(f"{name:>12}: arc length {L:.4f}, endpoint distance "
          f"{np.abs(x - z).mean():.4f}")
The right-hand column does not move. After reflow one Euler step is as accurate as sixteen, because no curvature is left to discretise: arc length 1.1292 against an endpoint distance of 1.1292. The left column halves its error each time the steps double, matching section 02's . The interpolant is linear in both columns. Only the pairing differs.

Look at the table first. The left column halves its error each time the steps double, matching the behaviour from section 02, so it needs many steps to get small. The right column is flat at 0.0019 from one step to sixteen. After reflow, one Euler step does as well as sixteen. The last two lines say why. The independent flow's path has length 1.3503 but its endpoints are only 1.1294 apart, so it curves, and a straight Euler step can't follow a curve. The reflowed path has arc length 1.1292 and an endpoint distance of 1.1292, so it's a straight line and there's nothing to discretise. The linear interpolant is the same in both columns. Only the pairing differs.

Scaling Rectified Flow Transformers, the Stable Diffusion 3 paper, is what settled the argument in practice. Esser and colleagues report that rectified flow "surpasses conventional diffusion methods for high-resolution text-to-image" at scale, and the formulation is now what current open image and video models train under. HunyuanVideo states plainly that it uses "Flow Matching for model training".

So far every lever has attacked the number of passes. There's one more that attacks the cost of each pass, and it works because neighbouring steps do almost the same work.

06Feature caching, and the ceiling you can derive

Run the denoiser on step 30 of our cat and then on step 31, and most of what happens inside the network is the same. The inputs barely changed, so most of the intermediate numbers (the features) didn't either. DeepCache is the canonical version of exploiting that for UNets, the convolutional denoisers used by the Stable Diffusion family. It uses what its authors call "the inherent temporal redundancy observed in the sequential denoising steps", reusing high-level features across adjacent steps while updating the low-level ones cheaply. It needs no retraining. They report 2.3 times on Stable Diffusion v1.5 for a 0.05 drop in CLIP score, and 4.1 times on LDM-4-G for a 0.22 rise in FID on ImageNet. CLIP score measures how well an image matches its prompt.

How big a win can this be? Say we run the full network on one step in every , and a cheap partial path costing a fraction of a full pass on the other . Then the speedup is:

The interval you choose is a knob. The reuse fraction sets a ceiling, and no setting of the knob gets past it.

The code below tabulates the formula for a few intervals and reuse fractions, and then uses it in reverse. DeepCache reports 2.30 times at an interval of 5, and solving the formula for r tells us what their cheap path must cost. The last table puts caching next to the earlier levers, counting NFE and then "full-pass equivalents", meaning the cost once cached steps are discounted. Note that 10**7 stands in for an interval going to infinity.

Try it The cache reuse model, its ceiling, and why it stops helping
# Uniform feature caching: run the full network on 1 step in every N,
# reuse cached features on the other N-1 at a fraction r of the cost.
# Cost per step = (1 + (N-1)*r) / N, so the speedup is:
speedup = lambda N, r: N / (1 + (N - 1) * r)

print("         r=0.10  r=0.20  r=0.29  r=0.40")
for N in (2, 3, 5, 10, 20, 10**7):
    row = "  ".join(f"{speedup(N, r):6.2f}"
                    for r in (.10, .20, .29, .40))
    print(f"{('N -> inf' if N > 100 else 'N = %d' % N):>8} {row}")
print("  the last row is the 1/r ceiling: the interval cannot")
print("  buy you more than the cheap path already costs")

# Invert it. DeepCache report 2.30x on Stable Diffusion v1.5 at N=5.
N, s = 5, 2.30
r = (N / s - 1) / (N - 1)
print(f"\n{s}x at N={N} implies a cheap path costing r = {r:.3f}")
print(f"which caps that configuration at 1/r = {1/r:.2f}x")

# Caching composes with step reduction, and that is the catch: the
# interval can never exceed the number of steps you have left.
print("\nsteps  cfg  cache   NFE   full-pass equivalents")
for steps, cfg, on in ((50, 2, 0), (50, 2, 1), (20, 1, 0),
                       (4, 1, 0), (4, 1, 1)):
    frac = (1 + (steps - 1) * r) / steps if on else 1.0
    print(f"{steps:>5} {cfg:>4}x  {'on ' if on else 'off':>5}"
          f" {steps*cfg:>5}   {steps*cfg*frac:>8.1f}")
The N -> inf row is the point. Push the interval as far as you like and the speedup stops at 1/r, because the cheap path is still paid on nearly every step. Inverting DeepCache's 2.30x at N=5 gives r = 0.293, capping that configuration at 3.41x. In the last table, 4 steps leave almost no interval to skip over.

The N -> inf row is the point. However far you push the interval, the speedup stops at 1/r, because the cheap path is still paid for on nearly every step. Inverting DeepCache's 2.30x at N=5 gives r = 0.293, which caps that configuration at 3.41x. A reuse scheme is therefore characterised by how cheap its cheap path is, and a single measurement at any interval pins down both the cost and the ceiling. The last table shows the awkward part: at 4 steps there's barely an interval to have, and caching only takes the cost from 4.0 to 1.9.

Where the artefacts appear

DeepCache's own reading of its results is that below an interval of 5 "there is only a slight reduction in the quality", while at an interval of 20 the degradation is "non-negligible". What changes at that point is specific, and it tells you what to look for. They describe "subtle details such as the color of clothing and the shape of the cat" being modified. That's drift and not corruption. The image stays coherent and stops being the image the uncached sampler would have produced. A quick look at the output won't catch that.

Uniform intervals are the wrong shape

Reusing features on a fixed schedule treats every step alike, and they aren't. TeaCache starts from the observation that "differences among model outputs are not uniform across timesteps". Some neighbouring steps change the output a great deal and some barely at all, so spacing the full evaluations evenly spends effort in the wrong places. It estimates how much the output will change from the timestep embedding, which exists before the expensive part runs, and skips adaptively. Its authors report up to 4.41 times on Open-Sora-Plan for a 0.07 percent drop in VBench score.

One caution before you stack everything. Caching and step distillation harvest the same redundancy, the fact that consecutive steps agree, and a 4-step model has already spent most of it. There are only three steps to skip, the interval can't exceed the step count, and the remaining steps disagree with each other far more than 50 steps of the base model did. Expect the two to be substitutes, and measure the combination instead of assuming the speedups multiply.

Everything so far was about one picture. Our cat is about to start moving, and the numbers change completely.

07Video is not images times frames

A natural guess is that five seconds of video costs roughly the same as 129 images. It costs far more, and the arithmetic that shows it is four lines long. A modern video model is a diffusion transformer, a denoiser built from the attention blocks of chapter 08, running over a three-dimensional latent. A causal autoencoder compresses the clip in space and in time, the latent is cut into small blocks called patches, and every patch becomes one token in a single flat sequence in which every token attends to every other.

HunyuanVideo publishes every number needed to price that. Its autoencoder uses a temporal factor of 4, a spatial factor of 8 and 16 latent channels. The transformer is 13B parameters, 3072 wide, with 20 dual-stream and 40 single-stream blocks, and its documented 720p configuration is 129 frames at 1280 by 720 in 50 steps.

The code below prices a clip from those constants. tokens turns a clip size into a token count, attn counts the floating-point operations in the two attention matrix multiplications (4 * N**2 * D), and the later lines compare joint attention with attending to each frame separately, and then with a version that skips temporal compression. A FLOP is one floating-point operation, and a PFLOP is 1015 of them. Memory is counted in bf16, a 16-bit number format, so two bytes per value.

Try it Price a five-second 720p clip from the published constants
# HunyuanVideo's published 720p configuration, from its paper and repo:
W, H, F, STEPS = 1280, 720, 129, 50
CS, CT, CH = 8, 4, 16        # VAE: 8x spatial, 4x temporal, 16 chans
PS, PT = 2, 1                # patch size on the latent, spatial/temp
D, BLOCKS = 24 * 128, 20 + 40   # width 3072, 60 attention blocks
PARAMS = 13e9

def tokens(w, h, f, ct=CT):
    lf = (f - 1) // ct + 1 if ct > 1 else f
    return lf * (h // CS // PS) * (w // CS // PT // PS), lf

N, LF = tokens(W, H, F)
print(f"latent grid: {LF} x {H//CS} x {W//CS}, patched -> {N:,} tokens")
print(f"pixels per latent value: {CT*CS*CS*3/CH:.0f}x compression")

attn = 4 * N**2 * D          # QK^T and AV, summed over heads
print(f"attention matmuls: {attn/1e12:,.1f} TFLOP per block, "
      f"{attn*BLOCKS/1e15:,.2f} PFLOP per step")
clip = attn * BLOCKS * STEPS
print(f"{STEPS} steps -> {clip/1e15:,.0f} PFLOP of attention alone")
print(f"the repo reports 1904 s on one GPU, so {clip/1904/1e12:,.0f}"
      " TFLOP/s sustained on that term")

# Why video is not images times frames.
one, _ = tokens(W, H, 1, ct=1)
print(f"\none 720p frame is {one:,} tokens; {LF} of them held jointly")
print(f"is {N//one}x the tokens and {(N/one)**2:,.0f}x the attention,")
print(f"so {(N/one)**2/(N/one):,.0f}x more attention work per frame")

flat, _ = tokens(W, H, F, ct=1)      # drop temporal compression
print(f"\nno temporal compression: {flat:,} tokens, "
      f"{(flat/N)**2:.1f}x the attention cost")

act = N * D * 2
print(f"\nweights in bf16: {PARAMS*2/1e9:.0f} GB; one full-width "
      f"activation: {act/1e6:.0f} MB")
print(f"Q, K, V and output at once: {4*act/1e9:.1f} GB, before any"
      " of the MLP")
Three numbers worth carrying. 118,800 tokens for five seconds, longer than many LLM context windows, and it is the output and not the prompt. 1,089x the attention of one frame for 33 latent frames, so 33x more work per frame than generating them separately. And 15.3x, what temporal compression is worth before the transformer runs at all.

The first line of output is the key one: a latent grid of 33 by 90 by 160, which becomes 118,800 tokens for five seconds of video. That's longer than many LLM context windows, and it's the output and not the prompt. Next, 33 latent frames held jointly give 1,089 times the attention of one frame, so 33 times more attention work per frame than generating the frames separately. Then the third number, 15.3 times, is what the autoencoder's temporal compression is worth before the transformer runs at all. The 520 PFLOP line is the attention cost of the whole clip, and dividing it by the repo's reported 1904 seconds gives 273 TFLOP/s sustained on that term alone.

The rule that makes video expensive

Why 33 times? Split tokens into per-frame groups and attend within each group. That costs . Attend over all of them jointly and it costs . The ratio is exactly :

Here is the number of latent frames and not output frames, and that's what the autoencoder is for.

So temporal coherence is expensive. It costs a factor equal to the latent frame count, on the dominant term, on every step, and it's the price of making a video a video and not a flipbook. It also explains where the engineering effort has gone. Temporal compression divides and attention is quadratic in the number of tokens, so the 4 times compression in the autoencoder is worth about 15 times on attention. No sampler change is worth 15 times.

Frame count scaling and the memory wall

Doubling the clip length doubles , doubles the token count, and quadruples attention. A ten-second clip isn't two five-second clips, and a capacity plan built at five seconds doesn't survive the product asking for ten. Memory follows the same shape. The weights are a fixed 26 GB in bf16, but one full-width activation at 118,800 tokens is 730 MB, and the attention inputs and output alone are 2.9 GB before the MLP. HunyuanVideo's repository asks for 60 GB at this configuration.

One caveat on the 520 PFLOP figure: it counts the two attention matrix multiplications and nothing else, so it's a floor on the cost of a step and not an estimate of it, so real steps cost more than it suggests. The projections, the MLPs and the normalisations all sit on top. Even so, it's most of the time. Sliding Tile Attention measured where the time goes and found that when generating "a 5-second 720P video, attention alone takes 800 out of 945 seconds of total inference time". At that ratio, halving the step count can't help you as much as making attention sub-quadratic.

That's what the recent work does. Sparse VideoGen separates spatial from temporal heads and reports 2.28 and 2.33 times end to end on CogVideoX-v1.5 and HunyuanVideo. Radial Attention exploits spatiotemporal energy decay for an scheme, reporting up to 3.7 times on inference.

If you've read chapter 31, you might now ask why we don't cache and share work between requests the way an LLM server does. Prefix caching works for an LLM because the sequence is the prompt: it arrives fixed, it's often shared between users, and its keys and values can be computed once and kept. In a diffusion transformer the sequence is the output. Every token changes at every step, so there's no prefix, no KV cache, and nothing to share between two users asking for different videos. The redundancy that does exist is across timesteps, and that's section 06's caching, a much smaller prize.

We now have every lever and the reason video is its own problem. What's left is putting the model on a machine, and that's where people arriving from LLM serving get surprised.

08Serving diffusion, and why it is not LLM serving

Chapter 31 taught that batching is nearly free and bandwidth is the enemy. Both halves of that invert here, and one line of arithmetic shows why. Repeat chapter 31's roofline count for one denoiser pass. A model with parameters in bf16 moves bytes of weights. It does about two floating-point operations per parameter per token, over tokens per sample and samples in the batch:

Same derivation as decode, with one extra factor. For LLM decode and the intensity is . Here is the whole latent.

Intensity is operations per byte moved, and a GPU is limited by memory when that's below its ridge point and by arithmetic when it's above. A 1024 pixel image with an 8 times autoencoder and a patch size of 2 is 4,096 tokens, and that's our cat. The five-second clip above is 118,800. An H100 SXM lists 989 bf16 TFLOP/s against 3.35 TB/s, which puts its ridge point near 295 operations per byte. So a diffusion step is past the ridge at batch 1, by a factor of roughly 14 for the image and 400 for the clip. Argus, a text-to-image serving system, states the consequence directly: these models are "highly compute-bound".

Four things follow, and each contradicts an instinct from chapter 31. First, batching buys much less. The arithmetic units were already saturated at batch 1, so a larger batch mostly adds latency, and there's no equivalent of the decode batching cliff because you aren't waiting on memory. Second, there's no KV cache to run out of. No per-request state grows with time, so capacity is weights plus activations, and activations scale with resolution and clip length and not with how long a user has been talking.

Third, scaling out means splitting one sample. More GPUs can't serve more requests per second at the same latency if one request already fills the device, so video inference reaches for sequence parallelism, which splits one sample's tokens across several GPUs, before it reaches for more concurrency. Fourth, quantisation pays differently. Weight-only quantisation is the standard LLM win because it cuts bytes moved, and bytes moved isn't the constraint here. You need low-precision arithmetic, meaning FP8 activations as well as weights, or you get nothing.

One thing is easier. Requests in a diffusion batch all run the same number of steps and finish together, so the ragged-completion problem that makes continuous batching essential for an LLM barely exists. Generation length is a server setting and not something the model decides. The scheduling problem that replaces it is admission: one request can occupy the whole device for minutes, and there's no chunking trick that makes a denoising step interruptible. The hardware conclusion is to choose on arithmetic throughput per pound and not bandwidth per pound. A card that wins on LLM decode because of its memory system can lose here, and a ranking carried over from a serving benchmark will be the wrong ranking.

What goes wrong with these levers doesn't show up as an error. It shows up as quality, quietly.

09What breaks

Almost none of these failures are crashes. They're quality regressions that no dashboard is watching for, and most of them come from one of the levers above being pulled without checking what it cost. Caching drift passes a casual look: details move and the image stays plausible, so nobody notices in review, and the only way to see it is to diff against an uncached reference at a fixed seed. A distilled model benchmarked at 4 steps against a base model at 50 measures the distillation and not the checkpoint, and that's how a worse model wins an evaluation. And diversity collapse arrives as a support ticket, because FID over thousands of samples is a distribution distance and won't show it, while per-prompt pairwise distance will.

Some mistakes come from carrying a number across contexts. A step count tuned on one sampler and copied to another isn't portable, since twenty steps of a second-order solver and twenty of DDIM aren't the same amount of integration. A guidance scale that stopped doing anything usually means the checkpoint is guidance-distilled, the scale is now a trained input with a range, and it's being driven outside it. A negative prompt that quietly stopped applying has the same cause: it was a second conditional in the empty slot, and the model no longer evaluates that slot.

The last two come from planning with the wrong arithmetic. A video memory plan made at five seconds breaks because attention is quadratic in clip length: doubling the duration roughly quadruples the dominant term and the budget was linear. And batch size raised to improve throughput only raised latency, because as section 08 showed, the arithmetic units were busy already.

10Where you meet this in the wild

The same budget gets spent on different things depending on who's waiting for the picture. Here are four products, and which levers each one pulls.

A hosted image API

Throughput per GPU is the unit economics, and nobody is watching a progress bar. Every free lever gets pulled and the paid ones get a quality review.

Guidance-distilled checkpoint, a second-order solver in the 20s, caching on, FP8 arithmetic.

An interactive canvas

The user is drawing and the image updates as they move. A latency budget under a couple of hundred milliseconds leaves room for one to four evaluations and nothing else.

Use a distilled few-step model. The diversity loss costs nothing here, because the user is the source of variation.

A video product

Minutes per clip on one GPU. The step count is already low and attention is most of the remaining bill, so the work is in the attention kernel and in splitting one sample across devices.

Sparse or tiled attention, sequence parallelism, the most aggressive autoencoder you can tolerate.

More concurrency does not help, because one request already owns the device.

On-device generation

On a phone or a laptop the constraint is memory and sustained power, and peak throughput matters less. Attack token count before step count.

A deeply compressing autoencoder plus a small step count. SANA's 32 times compression is the shape of the answer.

11Summary

  1. The bill is the number of forward passes. A text encoder and a decoder run once, and the denoiser runs once per step, doubled by guidance, so fifty guided steps cost a hundred passes per image.
  2. A step is one piece of a numerical integration. Fewer steps means a coarser approximation of one path, and a second-order solver needs about the square root of the steps a first-order one does, so DPM-Solver gets to 10 to 20 evaluations with no new weights.
  3. Determinism is what lets steps be skipped. DDIM removes the injected noise, so coarse integration approximates a fixed answer. Under-stepping drifts the composition without making the image look broken, and the floor for training-free samplers is around ten evaluations.
  4. Guidance silently doubles the count. Classifier-free guidance evaluates the model with and without the prompt, and a quoted step count for a guided model is half the real passes. Guidance distillation removes the factor of two, and costs you negative prompts and a free guidance scale.
  5. Limiting guidance to the middle of the chain is a free improvement. Steps outside the interval need one pass, and in one study FID on ImageNet-512 went from 1.81 to 1.40.
  6. Step distillation buys steps with a training run and pays in diversity. Few-step students match their teachers on FID while committing to a composition in the first evaluation, so every seed gives a similar picture.
  7. Rectified flow makes the path straight. A random pairing of noise and data gives crossing paths and a curved average field, while reflow re-pairs them so one Euler step is as accurate as sixteen.
  8. Caching has a ceiling of 1/r. With a cheap path costing a fraction of a full pass, the speedup is , and it drifts details instead of corrupting them. Caching and step distillation spend the same redundancy, so they don't stack.
  9. Joint video attention costs a factor of the latent frame count. Five seconds at 720p is 118,800 tokens, joint attention is 33 times the per-frame cost, and the autoencoder's 4 times temporal compression is worth about 15 times on attention.
  10. Diffusion serving is compute-bound. Intensity is TB, so a step is past the ridge point at batch 1. Batching adds latency, there's no KV cache, scaling out means splitting one sample, and quantisation only pays if the arithmetic is low precision too.
  11. Most failures are silent quality regressions. Check caching and distillation against an uncached or 50-step reference at a fixed seed, and measure diversity per prompt as well as FID.

12Build this

The claim you should least take on trust is that quality degrades gracefully with step count. Measure your own frontier, on your own checkpoint, in an afternoon.

Project Find the step floor and the cache ceiling, then measure what you lost ~4 hours · diffusers + one GPU

Take one checkpoint and one fixed set of 32 prompts. You are not looking for the best images. You are looking for the step count where the sampler stops reproducing its own 100-step answer, which is a different and much sharper question.

  1. Generate a reference set at 100 steps with a fixed seed per prompt. This is the ground truth for everything that follows, and everything is compared against it.
  2. Sweep step counts over 2, 4, 8, 16, 32 and 50 for DDIM and for a second-order solver, same seeds throughout. Record LPIPS against the reference and CLIP score against the prompt.
  3. Plot both. LPIPS will move long before CLIP does, so note the step count where each one starts to bend, since they differ.
  4. Enable feature caching at intervals 2, 3, 5 and 10 at your chosen step count. Fit to the measured speedups and read off .
  5. Now measure diversity in place of quality. Generate 32 samples of one prompt with 32 different seeds, from the base model and from a distilled few-step model. Embed all 64 and compare mean pairwise distance within each group.
You'll know it worked when your fitted predicts the speedup at an interval you did not fit, and when the extrapolated ceiling turns out to be a number you would not have guessed from the interval-2 measurement alone.
What step 5 teaches. The metrics in steps 2 and 3 will say the distilled model is fine. The pairwise distance in step 5 is where the loss shows, and the gap between those readings is section 04's whole argument. Look at the images too: the distilled group tends to share a composition and differ only in surface.

13Interview questions

BeginnerWhy is a diffusion model expensive to run compared with a GAN?

Because quality comes from an iterative loop rather than a single pass. A GAN generator produces its output in one forward evaluation. A diffusion sampler integrates a reverse process, and each increment of that integration is a full forward pass of a large network.

The other two components barely count. The text encoder runs once per request and the decoder runs once at the end, so a 50-step generation is essentially 50 network evaluations, doubled to 100 if classifier-free guidance is on.

That is the whole cost model, and it is why every acceleration technique for diffusion is ultimately about reducing the number of function evaluations or making each one cheaper.

BeginnerWhat does classifier-free guidance cost at inference, and how do people avoid it?

It doubles the forward passes. Each step evaluates the model once with the prompt and once without, then extrapolates away from the unconditional prediction, so a 50-step guided generation is 100 passes rather than 50.

The usual fix is guidance distillation: train a student that takes the guidance scale as an input and reproduces the combined output in a single pass. FLUX.1 [dev] ships this way, and HunyuanVideo reports about 1.9 times acceleration from it.

A cheaper partial fix is to apply guidance only over an interval of noise levels, which removes the second pass outside that interval and, in the paper that proposed it, also improved sample quality.

IntermediateYou need to get from 50 steps to 10. What do you try, and in what order?

Start with things that do not touch the weights. Swap the sampler for a higher-order ODE solver, since that changes the step floor by roughly a square root and costs nothing. Then check whether guidance can be limited to an interval, which removes a second pass from the steps outside it.

Next, feature caching. Measure the speedup at two intervals, fit the reuse model, and you get both the achievable range and the ceiling from the same two measurements.

Only then reach for distillation, because it costs a training run and changes the model's behaviour. Guidance distillation first, since it removes a factor of two with little quality argument. Step distillation last, because it is the one that costs diversity.

IntermediateWhat does a 4-step distilled model give up, and how would you measure it?

Mostly diversity, not fidelity. The DMD2 authors put their 4-step and 1-step students at FID 19.32 and 19.01 against an SDXL teacher at 19.36, so on a distribution metric the student is level, and they separately report a degradation in image diversity.

The mechanism is that distilled models fix their image structure in the first evaluation, where a base model spreads structural decisions over many steps. With one evaluation there is nowhere for the seed to change composition, so it changes only surface detail.

FID will not show this, because it compares distributions over thousands of samples. Measure it directly: generate many samples of a single prompt with different seeds, embed them, and compare mean pairwise distance against the base model on the same prompts.

IntermediateWhy do straighter probability paths need fewer sampling steps?

Because Euler integration of a straight line is exact at any step size. All the discretisation error comes from curvature, so a perfectly straight path can be traversed in one step and a curved one cannot.

The subtlety is that a linear interpolant does not by itself give a straight flow. The marginal velocity field averages over every data point a given noise sample might become, and that average bends. Straightness is a property of the coupling between noise and data, not of the schedule.

Reflow fixes this by running the learned ODE, recording where each noise sample lands, and retraining on those pairs. With one destination per starting point the paths stop crossing and the induced field is straight.

DeepDerive the speedup from feature caching and state its limit.

Let the full network cost 1 and the cached path cost a fraction r of it, and run the full network once every N steps. Average cost per step is (1 + (N-1)r)/N, so the speedup is N divided by that, which is N/(1 + (N-1)r).

Take N to infinity and the speedup tends to 1/r. The interval is a knob but the reuse fraction is a ceiling, so a scheme is characterised by how cheap its cheap path is rather than by how far apart the full evaluations are spaced.

This is usable in reverse. DeepCache report 2.30 times on Stable Diffusion v1.5 at interval 5; inverting gives r of about 0.293 and a ceiling near 3.4 times, which tells you not to spend a week tuning the interval. It also predicts that caching will not compose with a 4-step model, because the interval cannot exceed the step count.

DeepWhy is generating a five-second video not the same as generating 120 images?

Because the whole clip is one attention sequence. Split N tokens into k per-frame groups and attend within each and you pay k times (N/k) squared, which is N squared over k. Attend jointly and you pay N squared. The ratio is exactly k, the number of latent frames.

Concretely, HunyuanVideo compresses 129 frames of 1280 by 720 by 8 in space and 4 in time, patchifies by 2 spatially, and gets 33 by 45 by 80, which is 118,800 tokens. That is 33 times the tokens of one frame and 1,089 times the attention, so 33 times more attention work per frame of output.

Two consequences. Temporal compression in the autoencoder is worth more than any sampler change, since dropping it here would cost about 15 times on attention. And doubling the clip length roughly quadruples the dominant term, so duration budgets are not linear.

DeepHow does serving a diffusion model differ from serving an LLM?

The roofline position is opposite. One denoiser pass moves 2P bytes of weights and does roughly 2PTB operations over T tokens per sample and B samples, so arithmetic intensity is TB. For LLM decode T is 1 and intensity is the batch size; for a 1024 pixel image T is about 4,096 and for a five-second clip it is over 100,000.

Against an H100's ridge point near 295 operations per byte, a diffusion step is compute-bound at batch 1. Batching therefore buys much less than it does during decode, and raising it mostly adds latency.

The rest follows. There is no KV cache, so capacity is weights plus activations rather than context length. Scaling out means sequence parallelism over one sample rather than more concurrent requests. Weight-only quantisation gains little, because bytes moved was never the constraint. And hardware should be chosen on arithmetic throughput rather than on memory bandwidth.

14Go deeper

📄
Paper
Denoising Diffusion Implicit Models
Song, Meng & Ermon. The deterministic sampler behind section 02, reporting samples 10 to 50 times faster than DDPM. arXiv:2010.02502
📄
Paper
DPM-Solver: A Fast ODE Solver for Diffusion Probabilistic Model Sampling in Around 10 Steps
Lu et al. 10 to 20 evaluations and a 4 to 16 times speedup, with no change to the weights. arXiv:2206.00927
📄
Paper
Classifier-Free Diffusion Guidance
Ho & Salimans. Where the second forward pass per step comes from. arXiv:2207.12598
📄
Paper
On Distillation of Guided Diffusion Models
Meng et al. Guidance distillation: one student, conditioned on the scale, in place of two branches. arXiv:2210.03142
📄
Paper
Applying Guidance in a Limited Interval Improves Sample and Distribution Quality
Kynkäänniemi et al. Cheaper and better: guidance helps only in the middle of the schedule. arXiv:2404.07724
📄
Paper
Progressive Distillation for Fast Sampling of Diffusion Models
Salimans & Ho. Halve the step count, repeat. 8192 steps down to 4, FID 3.0 on CIFAR-10. arXiv:2202.00512
📄
Paper
Consistency Models
Song et al. Map every point on a trajectory to its endpoint, then jump. arXiv:2303.01469
📄
Paper
Latent Consistency Models
Luo et al. The same property distilled into a latent diffusion model. 2 to 4 steps at 768 px, about 32 A100 hours. arXiv:2310.04378
📄
Paper
Adversarial Diffusion Distillation
Sauer et al. Score distillation plus a discriminator, shipped as SDXL-Turbo. arXiv:2311.17042
📄
Paper
SDXL-Lightning: Progressive Adversarial Diffusion Distillation
Lin, Wang & Yang. Names the trade in its own abstract: quality against mode coverage. arXiv:2402.13929
📄
Paper
Improved Distribution Matching Distillation for Fast Image Synthesis
Yin et al. DMD2, and the FID table in section 04 showing what one-step does and does not cost. arXiv:2405.14867
📄
Paper
Distilling Diversity and Control in Diffusion Models
Gandikota & Bau. Why distilled models lose diversity: structure is fixed at the first timestep. arXiv:2503.10637
📄
Paper
Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow
Liu, Gong & Liu. Rectification, reflow, and one-step Euler. The source for section 05. arXiv:2209.03003
📄
Paper
Scaling Rectified Flow Transformers for High-Resolution Image Synthesis
Esser et al. The Stable Diffusion 3 paper, and what settled rectified flow as standard practice. arXiv:2403.03206
📄
Paper
DeepCache: Accelerating Diffusion Models for Free
Ma, Fang & Wang. 2.3 times on SD v1.5 for 0.05 CLIP, and the interval study section 06 inverts. arXiv:2312.00858
📄
Paper
Timestep Embedding Tells: It's Time to Cache for Video Diffusion Model
Liu et al. TeaCache. Adaptive rather than uniform reuse, up to 4.41 times on Open-Sora-Plan. arXiv:2411.19108
📄
Paper
HunyuanVideo: A Systematic Framework For Large Video Generative Models
Kong et al. Every constant used in section 07: the 4 by 8 by 8 autoencoder, the block counts, the guidance distillation. arXiv:2412.03603
📄
Paper
CogVideoX: Text-to-Video Diffusion Models with An Expert Transformer
Yang et al. The 3D causal autoencoder at 8 by 8 by 4, stated plainly. arXiv:2408.06072
📄
Paper
Fast Video Generation with Sliding Tile Attention
Zhang et al. Where the 800-of-945-seconds measurement comes from, and a kernel that attacks it. arXiv:2502.04507
📄
Paper
Radial Attention: O(n log n) Sparse Attention with Energy Decay for Long Video Generation
Li et al. Spatiotemporal energy decay turned into a sparsity pattern. arXiv:2506.19852
📄
Paper
Sparse VideoGen: Accelerating Video Diffusion Transformers with Spatial-Temporal Sparsity
Xi et al. Spatial heads and temporal heads, separated and sparsified at inference. arXiv:2502.01776
🔧
Model card
FLUX.1 [dev]
The source for the guidance-distillation line quoted in section 03, on a checkpoint you can download.
📄
Paper
SANA: Efficient High-Resolution Image Synthesis with Linear Diffusion Transformers
Xie et al. A 32 times autoencoder, which attacks token count rather than step count. arXiv:2410.10629
📄
Paper
Argus: Quality-Aware High-Throughput Text-to-Image Inference Serving System
Agarwal, Mitra & Iqbal. A serving system built around the fact that these models are compute-bound. arXiv:2511.06724
🔧
Tool
FastVideo
Distillation, sparse attention and distributed inference for video models, in one framework. The practical version of sections 04 and 07.
🔧
Tool
xDiT
Sequence and pipeline parallelism for diffusion transformers. What you reach for when one sample already fills the device.
🔧
Docs
Diffusers
Where the samplers, the distilled checkpoints and the caching hooks all live behind one interface. Start the project in section 12 here.
📝
Datasheet
NVIDIA H100 Tensor Core GPU
The two numbers section 08 divides to get a ridge point. Do the division for whatever card you have.

●Now write it yourself

Reading the derivation and being able to produce it are different skills. These are Deep-ML problems that exercise what this page covers — each one is checked against real test cases, not multiple choice.

Matched to this page from Deep-ML's catalogue of 1,380 problems. More at deep-ml.com, and Where to practise covers the other platforms and what each one trains.