Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Denoising step | One run of the network that predicts how to make the current noisy latent slightly cleaner. |
| Scheduler / sampler | The rule that decides the noise levels and how each step’s prediction updates the latent. |
| Flow matching | A training method (used by FLUX, SD3, Wan) where the model learns a straight-ish path from noise to image, so fewer steps are needed. |
| VAE | Variational autoencoder: compresses an image into a small latent and decodes the latent back to pixels at the end. |
| CFG | Classifier-free guidance: run the model with and without the prompt and push the result towards the prompt. Doubles the work per step. |
| Distillation | Training a student to match a teacher in fewer steps (step distillation) or without CFG (guidance distillation). |
| Step cache | Reusing a previous step’s outputs when the network’s activations barely change between steps. |
| Context parallelism | Splitting the token sequence of one image across GPUs (14.f). |
1. What is it?#
An image generator such as FLUX, Stable Diffusion 3 or Qwen-Image is a pipeline of three networks:
- Text encoder(s) turn the prompt into vectors, once.
- A denoiser, in 2026 almost always a diffusion transformer (DiT), runs N times. Each step it reads the whole latent image (thousands of tokens) and the text vectors, and predicts a correction.
- The VAE decoder turns the final latent into pixels, once.
Inference engineering for diffusion is about the middle part: the cost of one step, the number of steps, and how many images share the GPU. Facts checked on 13 November 2026 against diffusers v0.43.0 (12 November 2026), vLLM-Omni v0.32.0 and SGLang v0.5.23.
2. Why does it matter?#
- It is the most compute-hungry common workload. A 1024×1024 image from a 12B DiT is about 3,500 TFLOP at 28 steps, roughly a hundred chat requests’ worth (26.a).
- The levers are different from LLMs. No KV cache to page, no decode to batch. Speed comes from fewer steps, cheaper steps, and skipping steps.
- Quality is the constraint. Every big speed-up (distillation, caching, low precision) changes the image. You need a way to measure that, not just latency.
- Cost per image decides products. At $2.50 per GPU-hour, the difference between 25 seconds and under 1 second per image is the difference between a premium feature and a free one.
3. Simple analogy#
A sculptor working from a block of marble (noise). Each pass with the chisel (step) looks at the whole statue and removes a little. A master who has trained an apprentice to reach the same result in four passes (distillation) is faster than one who makes fifty careful passes. Some passes change almost nothing; a sculptor who notices that and skips them (step caching) saves time but risks missing a detail.
4. Tiny example: one FLUX-shaped image#
prompt "a red bicycle leaning on a blue wall", 1024 x 1024
text encoders T5 + CLIP -> 512 text tokens once, ~tens of ms
latent VAE latent 128 x 128 x 16 -> 2x2 patches -> 4,096 image tokens
denoiser 12B DiT, 57 blocks, 4,608 tokens per pass x 28 steps
VAE decode 128 x 128 latent -> 1024 x 1024 pixels once
user sees nothing until the very end (or optional low-res previews)FLUX.1-dev is guidance-distilled: it takes the guidance strength as an input and needs one pass per step instead of two. Many other models still run true CFG, two passes per step.
5. Technical explanation#
The cost of a step#
A step is one forward pass of the DiT over all latent tokens plus the text tokens. With thousands of tokens per pass, the matmuls are firmly compute-bound (26.a). Two terms:
- Linear layers: about 2 × parameters × tokens FLOPs.
- Attention: about 4 × blocks × width × tokens² FLOPs. It grows with the square of the token count: doubling both sides of the image quadruples the tokens and multiplies attention by 16.
At 1024×1024, linear layers dominate; at 2048×2048 (16,384 image tokens), attention catches up. That is why high-resolution and video models care so much about attention kernels (13.l) and sparse attention (26.d).
Lever 1: fewer steps#
| Technique | What changes | Typical steps | Cost |
|---|---|---|---|
| Better samplers (flow matching, DPM-Solver-style) | The update rule | 20–50 | Free, small quality changes |
| Guidance distillation | Removes the second CFG pass | Same steps, half the passes | A trained model (FLUX.1-dev) |
| Step distillation (consistency models, adversarial and distribution-matching distillation, rCM) | A student that jumps further per step | 1–8 | A trained model; diversity and prompt-following can drop |
Distilled “turbo”, “schnell” or “lightning” variants are a model choice, not a serving flag. In 2026 many new releases ship a few-step checkpoint next to the full one; for example, diffusers v0.43.0 added image models with fixed six- and eight-step distilled schedules.
Lever 2: cheaper steps#
- Attention kernels: FlashAttention-3/4 (13.l), and low-bit attention such as SageAttention
(INT8/FP8, and FP4 in SageAttention3 on Blackwell). Diffusers selects kernels with
set_attention_backend(...). - Low-precision matmuls: FP8 (13.e) works well on DiTs. 4-bit needs care: SVDQuant (Nunchaku) absorbs outliers into a small 16-bit low-rank branch and quantizes weights and activations to 4 bits; its authors report 3.5x less memory for 12B FLUX.1 and 3.0x speed-up over 4-bit weight-only quantization on a laptop RTX 4090.
- Compilation and graphs:
torch.compile(13.m) fuses the many small elementwise operations around attention (modulation, norms, gating); with fixed resolutions, CUDA graphs remove launch overhead.
Lever 3: skipping work inside steps (step caches)#
Adjacent steps often produce similar activations, especially in the middle of sampling. Step caches
exploit this. Diffusers v0.43.0 ships these through one API, pipe.transformer.enable_cache(config):
| Method | Idea |
|---|---|
FirstBlockCacheConfig(threshold=...) | Run the first block; if its output changed less than the threshold, reuse the rest of the network’s previous residual. Default threshold 0.05. |
TaylorSeerCacheConfig(...) | Predict later activations from earlier ones with a Taylor expansion; do a full pass every cache_interval steps. |
MagCacheConfig(mag_ratios=...) | Skip blocks based on measured residual magnitudes; needs a calibration run per checkpoint and scheduler. |
PyramidAttentionBroadcastConfig, FasterCacheConfig | Reuse attention outputs for some blocks and steps (mostly video); FasterCache can also skip the unconditional CFG branch. |
TextKVCacheConfig | Compute text key/value projections once instead of every step (only some models). |
The diffusers documentation is explicit: caches trade quality for speed, settings tuned for one model rarely transfer, and you should compare outputs with and without the cache on your own prompts. Third-party engines (cache-dit, TeaCache) offer more variants.
Lever 4: more GPUs per image#
For latency, not throughput:
- CFG parallelism: run the conditional and unconditional passes on two GPUs. A clean 2x when CFG is on.
- Context (sequence) parallelism: diffusers’
ContextParallelConfig(ulysses_degree=..., ring_degree=...)withtransformer.enable_parallelism(...). On 4 H100s, the diffusers benchmark for FLUX.1-dev measured Ulysses at 7.50 steps per second against 3.82 for Ring; Ulysses needs heads and sequence divisible by the degree, and “Ulysses Anything” removes that restriction. - Patch pipeline parallelism (PipeFusion, in xDiT) splits the image into patches and pipelines them through layers, reusing slightly stale activations from the previous step.
- Tensor parallelism for weights that do not fit; needs NVLink.
Serving engines#
- diffusers: the reference library. Fine for batch jobs; you add the server, queue and batching.
- SGLang Diffusion:
sglang generatefor one-off jobs,sglang servefor an OpenAI-compatible image and video API with LoRA management, caching (Cache-DiT, TeaCache) and quantization. - vLLM-Omni (v0.32.0, aligned with vLLM 0.32.0): DiT stages inside a stage graph, with request-level batching for diffusion, FP8 attention and an OpenAI-compatible server (26.h).
- xDiT: parallel inference (USP, PipeFusion, CFG parallel, parallel VAE) for many DiTs; 0.7.0 (September 2026) added FP8 Ulysses all-to-all communication.
6. Under the hood: what each lever is worth#
The program costs one FLUX-shaped image under five recipes. Estimates, not measurements: 50% of the H100’s BF16 peak, a fixed 150 ms for the text encoders and VAE, a 40% step-cache skip rate and a 1.6x FP8 speed-up are all assumptions.
package main
import "fmt"
// A FLUX.1-shaped image DiT: 12B parameters, 57 transformer blocks of width 3072.
// At 1024x1024 the VAE gives a 128x128 latent; 2x2 patches -> 4,096 image tokens, plus 512 text tokens.
const (
params = 12e9
blocks = 57
width = 3072.0
tokens = 4096 + 512
effTF = 0.5 * 989e12 // H100 BF16 dense at 50% of peak, FLOP/s
vaeMs = 150.0 // VAE decode + text encoders, assumed fixed
gpuHr = 2.5 // $ per H100-hour (Nov 2026 rental range $2-3)
)
func passMs(speedup float64) float64 {
linear := 2 * params * tokens
attn := 4 * blocks * width * tokens * tokens
return (linear + attn) / (effTF * speedup) * 1000
}
type recipe struct {
name string
steps float64
cfg float64 // passes per step: 2 with classifier-free guidance, 1 if guidance-distilled
skipped float64 // fraction of passes skipped by a step cache
speedup float64 // kernel/precision speed-up on each pass
}
func main() {
rs := []recipe{
{"50 steps, real CFG, BF16", 50, 2, 0, 1},
{"28 steps, guidance-distilled, BF16", 28, 1, 0, 1},
{" + step cache skips 40% of passes", 28, 1, 0.4, 1},
{" + FP8 matmul and attention (1.6x)", 28, 1, 0.4, 1.6},
{"4-step distilled, FP8", 4, 1, 0, 1.6},
}
fmt.Printf("one pass over %d tokens: %.0f ms\n\n", tokens, passMs(1))
fmt.Printf("%-38s %7s %9s %13s\n", "recipe", "passes", "latency", "$ per 1k img")
for _, r := range rs {
passes := r.steps * r.cfg * (1 - r.skipped)
ms := passes*passMs(r.speedup) + vaeMs
cost := ms / 1000 / 3600 * gpuHr * 1000
fmt.Printf("%-38s %7.0f %8.2fs %13.2f\n", r.name, passes, ms/1000, cost)
}
}Output:
one pass over 4608 tokens: 254 ms
recipe passes latency $ per 1k img
50 steps, real CFG, BF16 100 25.52s 17.72
28 steps, guidance-distilled, BF16 28 7.25s 5.04
+ step cache skips 40% of passes 17 4.41s 3.06
+ FP8 matmul and attention (1.6x) 17 2.81s 1.95
4-step distilled, FP8 4 0.78s 0.54(The cached rows run 16.8 passes on average; the program rounds.)
How to read it:
- Pass count dominates. Going from 100 passes to 4 is a 25x lever; precision and kernels give 1.5–2x each. Start with the model choice, then caching, then kernels.
- Cost per image assumes batch 1 fills the GPU. It nearly does: 4,608 tokens per pass is far above the ridge point, so batching four images gives little extra throughput. Unlike an LLM, a diffusion server does not get dramatically cheaper per output with batching. Batching still helps small or low-resolution models and smooths out the fixed per-request overheads.
- The fixed 150 ms matters at 4 steps. Once the DiT is fast, text encoders, VAE decode, PNG encoding and upload become a fifth of the latency or more.
7. Performance implications#
- Resolution is quadratic, then worse. Tokens grow with pixel count; attention with tokens squared. Price and rate-limit by resolution.
- Mixed resolutions do not batch cleanly. Requests of different sizes have different token counts. Bucket by resolution (and step count) or run them one at a time.
- VAE decode is a memory spike. Decoding a large latent can need more activation memory than the DiT step; tiled or sliced VAE decoding trades a little speed for a much lower peak.
- LoRA adapters are common in image products; loading and fusing them per request costs time. Keep popular adapters resident and route by adapter (as for LLM LoRA, 18.g).
- Offloading (
enable_model_cpu_offload, group offload) fits big pipelines on small GPUs at a large latency cost; never on a latency-sensitive server.
8. Production implications#
- Measure quality with every speed change. Keep a fixed prompt set and seeds; compare with image-similarity metrics and human review before shipping a new cache threshold, step count or quantization.
- Queue, do not stream. Users wait seconds; give them a job ID, progress events and, if useful, low-resolution previews from intermediate latents.
- Safety stages are part of the pipeline. Prompt filters before, image classifiers after; budget their latency and GPU memory.
- Seeds and determinism. Users expect “same seed, same image”. Batch composition, kernels and parallelism can change outputs; document what is guaranteed.
- Cost model per image. Use the latency of the recipe you ship, at the batch size you run, times the GPU-hour price, plus CPU and storage for encoding and delivering the image.
9. Common mistakes#
- Running 50 steps with CFG on a guidance-distilled model. Read the model card; the default step count and guidance mode differ per model.
- Copying cache thresholds between models. Diffusers warns that settings rarely transfer.
- Expecting LLM-style batching gains. A compute-bound pass is already full.
- Forgetting the VAE. OOMs at high resolution are often in decode, not in the DiT.
- Benchmarking without a quality check. A 4-step result that ignores half the prompt is not a 4x speed-up.
10. Hands-on exercise#
- Run the program. Change the resolution to 2048×2048 (16,384 image tokens). What fraction of a pass is now attention, and how does latency change?
- Add a recipe with CFG parallelism on two GPUs for the 50-step model. What happens to latency and to cost per image?
- With diffusers on a GPU, generate 20 images from fixed seeds with and without
FirstBlockCacheConfig(threshold=0.2). Measure time and compare the images side by side. - Estimate the GPUs needed to serve 50 images per second at the 2.81 s recipe with a p95 target of 4 seconds.
11. Interview questions#
- Why does batching help an LLM decode server far more than a diffusion server?
- Explain guidance distillation and step distillation. Which one halves the work and which one cuts it by 10x?
- What is a step cache, and how would you decide whether a threshold is safe to ship?
- When would you use CFG parallelism, context parallelism or tensor parallelism for one image?
- A 2048×2048 request OOMs but 1024×1024 is fine. Where do you look?
12. Further reading#
Checked on 13 November 2026.
- Diffusers: caching methods
- Diffusers: context parallelism
- Diffusers: attention backends
- Diffusers v0.43.0 release notes
- SGLang Diffusion documentation
- xDiT: parallel inference for diffusion transformers
- SVDQuant: 4-bit diffusion models (arXiv 2411.05007)
- SageAttention repository (SageAttention 1, 2, 2++ and 3)
- Scalable Diffusion Models with Transformers (DiT, arXiv 2212.09748)
- Flow Matching for Generative Modeling (arXiv 2210.02747)