ELLMEngineering Large
Language Models
Download PDF

Chapter 57

Diffusion Transformers, Flow Matching, and Parallel Generation

On this page

A transformer can predict the next text token, denoise image patches, or estimate a velocity field that transports noise into data. This chapter separates architecture, training target, and sampler, then derives the state and compute costs of continuous and discrete refinement.

Diffusion transformers operate on noisy latent patches

The original Diffusion Transformer (DiT) replaces a diffusion U-Net with a transformer over image-latent patches. A latent [B,C,H,W] split into square patches of side p gives N=(H/p)*(W/p) tokens, each projected from C*p*p values to hidden width D. Transformer outputs are projected back to patch values and unpatchified. Time and class conditioning enter the network; DiT's adaptive layer normalization modulates blocks with that conditioning. The transformer backbone and the diffusion objective are separate choices.

For a teaching configuration [B,4,32,32] with p=2, N=256. Changing to p=1 yields 1024 tokens: four times as many tokenwise activations and sixteen times as many dense attention score entries. Memory-efficient attention can avoid materializing that score matrix, but does not eliminate its quadratic arithmetic. These numbers describe the chosen latent shape, not a universal image encoder.

A common noise-prediction setup constructs x_t=alpha_t*x_clean+sigma_t*epsilon and regresses a network output toward Gaussian noise epsilon. The schedule and reverse update rule must agree with that output parameterization. A denoising pass updates the whole latent; generation repeats passes rather than appending one vocabulary token at a time. Original DiT also predicts variance, so its complete output head contains more than the teaching noise target alone.

A 4-channel, 32-by-32 latent becomes 256 tokens with 2-by-2 patches. Each 16-value patch projects to width D; the transformer predicts continuous patch outputs under time and optional class/text conditioning. The output head depends on whether the target is noise, velocity, or another parameterization.
Open full diagram ↗

A 4-channel, 32-by-32 latent becomes 256 tokens with 2-by-2 patches. Each 16-value patch projects to width D; the transformer predicts continuous patch outputs under time and optional class/text conditioning. The output head depends on whether the target is noise, velocity, or another parameterization.

Trace the conditioning inside a DiT block

For patch activations 2026-10-12T12:02:56.435038 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ {stroke-linejoin: round; stroke-linecap: butt} , the original class-conditioned DiT adds a timestep embedding to a class embedding to obtain 2026-10-12T12:02:56.439530 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ {stroke-linejoin: round; stroke-linecap: butt} . A SiLU/linear projection produces six vectors: shifts, scales, and residual gates for the attention and MLP branches. Each vector broadcasts along the patch axis. The paper's adaLN-Zero design separates normalization from this conditioning:

2026-10-12T12:02:56.446992 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

LayerNorm normalizes each patch over its D channels; the conditioning supplies scale and shift.

2026-10-12T12:02:56.469892 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

The first branch mixes patch positions and gates its result before the residual addition.

2026-10-12T12:02:56.482957 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

The second branch transforms channels independently at each patch position.

Gold paths carry conditioning; teal paths carry patch activations; coral paths show residual additions and gates. The MLP consumes the attention branch's updated residual stream. The final patch-output projection sits after the stack and is not part of this block.
Open full diagram ↗

Gold paths carry conditioning; teal paths carry patch activations; coral paths show residual additions and gates. The MLP consumes the attention branch's updated residual stream. The final patch-output projection sits after the stack and is not part of this block.

The reference implementation disables LayerNorm's learned affine parameters and zero-initializes the modulation projection. Both gates therefore begin at zero, making each block an identity map at initialization. The separate final projection is also zero-initialized. Attention spans the latent patches rather than using the causal text mask. Replacing a noise target with a velocity target changes the loss/output interpretation; it does not remove these shape and conditioning contracts.

Flow matching predicts motion along a probability path

Flow Matching trains a vector field by regression along chosen probability paths. One simple conditional construction samples noise x_0, data x_1, and time t, then uses a straight interpolation:

2026-10-12T12:02:56.493532 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

This convention runs from noise at t=0 to data at t=1.

With optional conditioning 2026-10-12T12:02:56.498331 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ , the training loss is:

2026-10-12T12:02:56.506877 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

d counts the predicted scalar coordinates; time is sampled directly during training.

At inference, initialize from noise and integrate 2026-10-12T12:02:56.516595 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ {stroke-linejoin: round; stroke-linecap: butt} toward 2026-10-12T12:02:56.520667 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ {stroke-linejoin: round; stroke-linecap: butt} . The target is an instantaneous velocity. Training need not integrate an ODE for every example.

At a given 2026-10-12T12:02:56.523685 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ , many noise/data pairs can be compatible with the observed point. Squared-error regression learns their conditional mean velocity:

2026-10-12T12:02:56.528417 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

The network averages compatible conditional targets; it does not receive the clean endpoint at inference.

Expand expected squared error around that conditional mean. The cross term vanishes, leaving a constant conditional variance plus the squared distance from the predicted mean. Straight training interpolations therefore need not produce straight trajectories of the learned field.

An analytically specified one-dimensional flow from a standard normal to a normal with mean 2 and variance 1. Curves show exact trajectories under the conditional-mean velocity field; circles are Euler steps for one initial point. Training pairs and inference trajectories are different objects.
Open full diagram ↗

An analytically specified one-dimensional flow from a standard normal to a normal with mean 2 and variance 1. Curves show exact trajectories under the conditional-mean velocity field; circles are Euler steps for one initial point. Training pairs and inference trajectories are different objects.

A transformer can parameterize this vector field, just as it can parameterize a noise predictor. DiT names an architecture family; flow matching names a training construction. Neither term implies left-to-right token sampling. Continuous latent interpolation also does not apply directly to integer vocabulary IDs; discrete generation requires a formulation over discrete states.

Compute a training loss and inspect one sampler

Example status: Illustrative PyTorch excerpt; requires a shape-preserving velocity network, data latents, conditioning, and a positive integer steps value. The first section computes the training loss; backpropagation and the optimizer update are omitted. The sampling section assumes training has completed.

import torch

# x1: [B,C,H,W] clean data latents; c: model-specific conditioning
x0 = torch.randn_like(x1)
t = torch.rand(x1.shape[0], device=x1.device)
t_broadcast = t[:, None, None, None]
xt = (1 - t_broadcast) * x0 + t_broadcast * x1
velocity_target = x1 - x0
loss = (model(xt, t, c) - velocity_target).square().mean()

# Euler sampling after training, with dropout disabled.
model.eval()
with torch.no_grad():
    x = torch.randn_like(x1)
    dt = 1.0 / steps
    for k in range(steps):
        time = torch.full_like(t, k * dt)
        x = x + dt * model(x, time, c)

The snippet fixes an independent noise/data pairing and uniform time sampling. Other paths, couplings, time distributions, and loss weightings change training. Straight conditional paths do not guarantee that trajectories of the learned marginal field are straight. Euler is a first-order approximation; increasing steps can reduce integration error, but a learned field can still be inaccurate. Decode final latents through the matching image decoder before evaluating generated images.

Work a continuous example with a known answer

Let independent endpoints be 2026-10-12T12:02:56.543976 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ {stroke-linejoin: round; stroke-linecap: butt} and 2026-10-12T12:02:56.552499 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ {stroke-linejoin: round; stroke-linecap: butt} . The linear training path has mean 2026-10-12T12:02:56.555515 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ {stroke-linejoin: round; stroke-linecap: butt} , variance 2026-10-12T12:02:56.558670 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ {stroke-linejoin: round; stroke-linecap: butt} , and covariance 2026-10-12T12:02:56.562145 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ with the target velocity. Gaussian conditioning gives:

2026-10-12T12:02:56.567081 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

The field expands or contracts deviations from the time-dependent mean.

2026-10-12T12:02:56.575812 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Differentiate this trajectory to recover the velocity field and verify the target distribution.

python -m examples.flow_matching compares Euler integration with this closed-form trajectory. Increasing the step count tests numerical integration against a known field; it does not test whether a neural network learned that field or whether generated images are good. A useful debugging order is path endpoints, target sign, broadcast axes, network output shape, then solver error.

Train a field and inspect the generated distribution

The executable examples/learned_flow.py learns an eight-component mixture in two dimensions. The centers lie on a radius-two circle, each component has standard deviation 0.12, and component probabilities are uniform. Training pairs independent standard-normal noise with a fresh target draw. A three-hidden-layer SiLU MLP, with width 64 and 8,706 parameters, receives two coordinates and time and returns two velocity coordinates. It is a small flow model, not a DiT or an image-quality experiment.

Run python -m examples.learned_flow --output output/experiments/my-flow-run in the optional PyTorch environment. The command refuses an existing output directory and saves every configured seed, evaluation curve, sample set, and checkpoint. The recorded CPU/FP32 run uses seeds 7, 17, and 29; Adam at 0.001; 3,000 updates per seed; batch size 256; and one CPU thread. It evaluates 4,096 held-out interpolation pairs without using them for training or selecting a checkpoint.

Seed Initial / final held-out target MSE Final field RMSE against oracle Sample distance, 8 / 32 / 128 Euler steps Within 0.4 of a target center, 128 steps
7 3.026 / 1.919 0.340 0.117 / 0.107 / 0.106 57.5%
17 3.030 / 1.926 0.352 0.126 / 0.122 / 0.123 55.3%
29 3.037 / 1.889 0.289 0.165 / 0.145 / 0.142 82.1%
Measured samples and held-out losses from the recorded CPU experiment. The scatter uses the first prespecified seed, 7, with 128 Euler evaluations; the three curves show seeds 7, 17, and 29. Axes are shared between target and generated samples. The visible spread between modes is a remaining modeling error.
Open full diagram ↗

Measured samples and held-out losses from the recorded CPU experiment. The scatter uses the first prespecified seed, 7, with 128 Euler evaluations; the three curves show seeds 7, 17, and 29. Axes are shared between target and generated samples. The visible spread between modes is a remaining modeling error.

Sample distance is empirical sliced Wasserstein-1: project both 2,048-point samples onto 64 fixed directions, sort each projection, and average absolute paired differences. The untransported-noise distance is 0.504; distances for the three untrained networks are 0.504–0.512. Two independent target draws score 0.108 on this one fixture, so differences near that scale should not be read as an exact population ranking. All seeds share the held-out samples and directions. These three runs do not provide confidence intervals or establish performance on other distributions.

Target regression MSE need not approach zero because compatible endpoint pairs have different velocities. This example permits a separate analytic field check. For component center 2026-10-12T12:02:56.612135 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ {stroke-linejoin: round; stroke-linecap: butt} and component standard deviation 2026-10-12T12:02:56.616027 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ {stroke-linejoin: round; stroke-linecap: butt} , define:

2026-10-12T12:02:56.624677 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Uniform component weights and a common variance yield these posterior responsibilities.

2026-10-12T12:02:56.637361 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Condition within each Gaussian component, then average using its posterior responsibility.

The final field RMSE remains 0.289–0.352, although it began around 1.105. More Euler steps do not repair this learned-field error: seed 17's sample distance slightly worsens from 32 to 128 steps. Inspect sample coverage and field error alongside the training loss. The environment, source hash, all three results, and plotted coordinates are retained in docs/experiments/learned-flow-2026-10-12.json; examples/plot_learned_flow.py reproduces the standalone charts.

Count refinement work and cache validity

For Euler with K steps, generation uses K network evaluations over the entire latent. A multi-stage solver can use several evaluations per step. Report network evaluations, latent shape, guidance calls, and total latency alongside quality. Fewer steps alone do not establish a faster or better sampler. As latent tokens change, bidirectional attention changes their hidden states, so the autoregressive append-only KV cache is generally invalid for the mutable latent. Reusing fixed conditioning projections is a separate optimization.

The following sections switch to discrete language generation: corruption is masking vocabulary tokens, and the prediction head returns token distributions rather than continuous velocities.

Train a masked denoiser

Take a clean sequence and randomly replace some tokens with a mask symbol. The network sees the corrupted sequence and predicts original tokens at masked positions. Vary the corruption level during training so it learns both nearly complete and heavily masked contexts. Unlike a causal decoder, a denoiser can use visible context on both sides of a missing position.

For an illustrative objective with independent mask probability t sampled uniformly in (0,1], weight the summed masked-token cross-entropy by 1/t. The weighting compensates for how often positions are masked; implementations need their precise noise schedule, conditioning, and loss normalization. This is not obtained by adding a mask token to a pretrained causal model and changing its decoder. LLaDA studies large language models trained through a masked-diffusion formulation.

Generate through a schedule of commitments

Start with a requested output length of masks. Predict distributions for currently masked positions, sample or choose candidate tokens, and reveal a subset according to a schedule—possibly using confidence. Repeat until complete. Some methods remask or revise positions. Output length and end-of-sequence handling are part of the method, not details that left-to-right decoding supplies automatically.

Example status: Explanatory pseudocode; model training, sampling policy, and length selection are intentionally abstract.

tokens = MASK repeated output_length times
for step in denoising_schedule:
    predictions = model(prompt, tokens, noise_level=step.level)
    positions = choose_positions_to_commit(predictions, step)
    tokens[positions] = sample(predictions[positions])
assert no_required_position_is_masked(tokens)

An eight-position sequence revealed two positions per round requires four denoiser calls. Under the causal-generation convention in Part I, eight autoregressive output tokens require one prompt prefill and seven single-token decode forwards: prefill supplies the first output distribution. Each denoiser call can process all eight output positions, while each cached decode forward processes one new position against prior state. Include prompt processing and any separate cache-population passes for both methods. Comparing call counts without FLOPs, memory traffic, batch size, and quality is misleading. Independent guesses can also disagree: choosing a subject and verb simultaneously may commit an incompatible pair.

Block diffusion and cache validity

Three snapshots show an initially masked block and two reveal steps. The causal prefix stays fixed while the current block changes. Question marks denote masked positions. Cache validity depends on which representations can change under the method's attention mask.
Open full diagram ↗

Three snapshots show an initially masked block and two reveal steps. The causal prefix stays fixed while the current block changes. Question marks denote masked positions. Cache validity depends on which representations can change under the method's attention mask.

Block Diffusion interpolates between autoregressive blocks and within-block diffusion. Earlier blocks can become fixed context while positions in the current block are refined together. This introduces a tunable tradeoff among block size, denoising steps, parallelism, and quality.

A causal prefix cache is valid because later output cannot alter its representations. A bidirectional mutable block lacks that property: changing one token can change the other positions' hidden states. Do not reuse its KV as if it were an unchanged autoregressive prefix. Cache reuse must follow the method's attention mask and update dependencies; an approximation needs an accuracy test of its own.

A diffusion draft inside speculative decoding is a different system from a diffusion target model. In the former, an autoregressive target can still define the output distribution if the proposal and verification procedure is valid; Part III discusses DFlash in that role. In the latter, the denoising model and generation schedule define the output behavior. There is no general promise of equality to an unrelated autoregressive model.

From a denoising idea to a serving implementation

DiffusionGemma's July 31 technical report describes an experimental Gemma 4 adaptation with 256-token blocks, supervised denoising, reinforcement learning, and sampler distillation. It reports roughly twenty tokens per forward pass and about 1,500 output tokens per second on one H100 across its evaluation suite. These are source-reported results, not measurements reproduced for this book.

Unlike the masked example above, DiffusionGemma starts with random tokens, re-noises uncertain positions, and uses previous predicted distributions as self-conditioning. Entropy helps control refinement. Its method and limitations also report lower absolute capability than the autoregressive initialization, occasional repetition, and a throughput crossover favoring autoregressive execution at higher concurrency. A crossover measured in that setup is not a universal user-count threshold.

The vLLM implementation account, June 10, exposes an important serving detail. Requests can occupy different denoising stages within one batch. A mutable canvas uses bidirectional attention, while accepting a completed canvas requires a causal pass to populate the reusable prefix cache. The implementation therefore uses per-request attention causality rather than one global causal flag for the entire batch. The model's architecture and scheduler must agree about which state is final.

This changes the benchmark contract. Record time to the first committed readable block, total completion time, useful output tokens, denoiser passes, acceptance passes, and memory at the actual concurrent load. Count canceled or revised work. A low-latency single request and a high-throughput batch can prefer different block sizes or even different model families. Include an autoregressive baseline with a tuned speculative path, not only naive token-by-token execution.

A useful toy calculation is a 32-token block refined in four 10-millisecond passes followed by a 4-millisecond acceptance pass. Its model-side rate is about 727 tokens per second, but the first committed block arrives no earlier than 44 milliseconds after the required prefix is ready. Reporting only 800 tokens per second from the four refinement passes omits necessary work. These numbers are illustrative, not measurements of DiffusionGemma.

Compare generation methods by their commit boundary

Method Mutable unit and commitment Reusable state and comparison boundary
Autoregressive target One next token becomes final under the decoding policy Causal prefix KV; measure useful committed tokens and full serving latency
Exact speculative autoregression Draft block or tree, then target verification and correction Discard rejected branch state; target-distribution equivalence requires the correct sampling algorithm
Full-sequence masked diffusion Multiple masked positions refined under a schedule Mutable bidirectional state; no general promise of an early stable readable prefix
Block diffusion Refine one block against fixed earlier blocks Prefix reuse follows the actual attention mask; mutable-block KV is not automatically reusable
DiffusionGemma Random-token canvas with self-conditioning, then acceptance Separate causal encode-and-append pass populates prefix cache; count it alongside denoising
Sequence editing Insertions and deletions change token positions and length Revalidate positional/cache dependencies and termination; support depends on the actual engine

The rows summarize the cited mechanisms in this chapter, not a speed ranking. In particular, diffusion used only as a speculative draft belongs under the autoregressive target's verification contract. A native diffusion target defines its own output behavior. Benchmark the same workload, quality floor, concurrency and output policy, and include canceled, revised and rejected work. A smaller number of model calls can still mean more arithmetic, memory traffic or time before the first useful commitment.

Sequence editing and commercial diffusion

The LLaDA2.2-flash card, inspected September 23, introduces DELETE and INSERT controls, block-level MoE routing, and agentic reinforcement learning. This extends refinement beyond replacing tokens at fixed positions: deletion and insertion change sequence structure. Position indices, termination, visible streaming, and cache invalidation must follow the editing method. The card provides a Transformers example but says SGLang deployment support is coming soon; model availability does not establish readiness of every suggested engine.

Mercury 2.5, announced September 8, supplies a commercial contrast: Inception documents an available diffusion service with configurable reasoning, parallel tool calls, and schema-aligned JSON. Its production and performance claims are vendor evidence, not a matched benchmark against the open implementations above. Test structured-output validity, correct tool arguments, committed-output latency, and concurrent throughput under the same application contract before selecting a generation family.

Exercises and worked answers

  1. Does half as many model calls mean twice the speed? No. Each call may process more positions and move more state; measure end-to-end time at matched quality and batch size.
  2. Why train across corruption levels? Inference encounters different amounts of known context as generation proceeds; training only at one mask rate can mismatch that sequence.
  3. When may an earlier block be cached? When its representations cannot depend on mutable later positions under the actual attention mask and model computation.
  4. Is masked denoising exact speculative sampling? No. It can supply proposals, but a target-preserving verifier needs the correct proposal semantics and acceptance/correction logic.
  5. Why does an accepted diffusion block need a separate cache decision? Mutable bidirectional representations are not automatically valid as causal prefix KV. Follow the method's acceptance/cache-population pass and include its work in latency.
  6. What could reject a fast single-request diffusion deployment? Worse task quality, slow first committed output, poor batching under mixed refinement stages, excessive workspace, or expensive cancellation can all violate the service contract.
  7. Do all discrete diffusion models repeatedly reveal masked tokens? No. Masked denoising, random-token corruption with self-conditioning, and length-changing sequence editing have different transition rules. Use the target method's sampler, termination, and cache dependencies.
  8. Does a straight interpolation target imply straight generated trajectories? No. The network estimates a conditional mean over compatible pairs. The analytic Gaussian example has changing variance and generally curved trajectories.
  9. What changes when patch side falls from two to one? For the same latent, token count grows fourfold and dense attention score entries grow sixteenfold. Projection, MLP, and actual runtime have different scaling.
  10. What does a convergent Euler test establish? Integration correctness for the supplied field and step convention; it does not establish training success or image quality.

Mutable-canvas state reference

examples/cross_layer.py includes a deliberately limited canvas simulation. Starting from [MASK,MASK,4,MASK], one pass writes position 1, and a later pass fills positions 0 and 3. Each real mutation advances the canvas revision. Cached bidirectional block state belongs to a revision; after any relevant token changes, earlier representations in that block can be stale because they could attend to the changed position.

This is a dependency test, not a learned denoising sampler or evidence of generation quality. A committed causal prefix may remain reusable if the architecture isolates it from the mutable block. A conventional append-only KV cache cannot establish that property on its own. The simulator makes the invalidation obligation inspectable without pretending that a list update implements a diffusion model.