17.9 Discrete Diffusion

Every model in the preceding sections relied on adding Gaussian noise to continuous vectors: points in R2\mathbb{R}^2, pixel intensities, or autoencoder latents. Discrete sequences such as text tokens, source code, or quantized image tokens cannot be perturbed by small additive real numbers. While autoregressive models (Section 11.2) generate LL tokens in LL sequential forward passes from left to right, discrete diffusion models generate multiple tokens in parallel per network evaluation with bidirectional context.

To define diffusion on a finite vocabulary, Hoogeboom et al. (2021) and Austin et al. (2021) replaced Gaussian perturbation with a discrete-state Markov chain governed by transition matrices Qt\mathbf{Q}_t. On text and discrete codes, the most effective corruption process is the absorbing (masking) kernel, which independently replaces tokens with a mask symbol [M][\textrm{M}] until the sequence is completely erased. Under this absorbing chain, the variational lower bound of Section 17.6 simplifies to a weighted masked cross-entropy objective (Sahoo et al., 2024; Shi et al., 2024). In this section we derive the absorbing Markov chain and its variational bound, analyze the independence error incurred when unmasking multiple tokens in parallel on a quantized two-token version of the three-mode mixture and on binary Fashion-MNIST images, and connect masked diffusion to autoregressive and masked language models (Section 11.4 and Section 11.2).

from scipy.special import ndtr, xlogy
torch.set_float32_matmul_precision('high')  # tf32 matmuls on tensor cores

17.9.1 Corrupting Tokens#

We ask of a forward process for tokens what the Gaussian chain of Section 17.2 provided: marginals and posteriors in closed form, and an end state that carries no information about the data.

17.9.1.1 Transition Matrices#

First a change of notation. To match the papers on discrete diffusion, t=1,…,Tt = 1, \ldots, T is now an integer that counts steps, the role kk played for the Gaussian chain. The network still receives t/Tt/T, the time on the chapter's clock.

Let a token take one of KK values, written as a one-hot row vector x∈{0,1}K\mathbf{x} \in \{0, 1\}^K. Noise for a token is a random change of its value, given by transition matrices Qt∈[0,1]K×K\mathbf{Q}_t \in [0, 1]^{K \times K} whose rows sum to one: [Qt]ij[\mathbf{Q}_t]_{ij} is the probability of moving from value ii to value jj at step tt. These are the row-stochastic matrices of Markov chain Monte Carlo (Section 24.8.3): a distribution is a row vector, multiplied by Qt\mathbf{Q}_t from the right. Hence

q(xt∣xt−1)=Cat(xt; xt−1Qt),(17.9.1)q(\mathbf{x}_t \mid \mathbf{x}_{t-1}) = \mathrm{Cat}(\mathbf{x}_t;\ \mathbf{x}_{t-1} \mathbf{Q}_t), \tag{17.9.1}

where Cat(x;p)\mathrm{Cat}(\mathbf{x}; \mathbf{p}) is the categorical distribution with probability vector p\mathbf{p}, here the row of Qt\mathbf{Q}_t selected by the current value. A sequence of LL tokens is corrupted by running the chain at every position independently. Composing two transitions multiplies their matrices, so by induction on tt the marginal after tt steps is

q(xt∣x0)=Cat(xt; x0Qˉt),Qˉt=Q1Q2⋯Qt.(17.9.2)q(\mathbf{x}_t \mid \mathbf{x}_0) = \mathrm{Cat}(\mathbf{x}_t;\ \mathbf{x}_0 \bar{\mathbf{Q}}_t), \qquad \bar{\mathbf{Q}}_t = \mathbf{Q}_1 \mathbf{Q}_2 \cdots \mathbf{Q}_t. \tag{17.9.2}

The posterior of one step given both of its ends follows from Bayes' rule and the Markov property,

q(xt−1∣xt,x0)=q(xt∣xt−1) q(xt−1∣x0)q(xt∣x0)=Cat ⁣(xt−1; xtQt⊤⊙x0Qˉt−1x0Qˉtxt⊤),(17.9.3)\begin{aligned} q(\mathbf{x}_{t-1} \mid \mathbf{x}_t, \mathbf{x}_0) &= \frac{q(\mathbf{x}_t \mid \mathbf{x}_{t-1})\, q(\mathbf{x}_{t-1} \mid \mathbf{x}_0)}{q(\mathbf{x}_t \mid \mathbf{x}_0)} \\ &= \mathrm{Cat}\!\left(\mathbf{x}_{t-1};\ \frac{\mathbf{x}_t \mathbf{Q}_t^\top \odot \mathbf{x}_0 \bar{\mathbf{Q}}_{t-1}}{\mathbf{x}_0 \bar{\mathbf{Q}}_t \mathbf{x}_t^\top}\right), \end{aligned} \tag{17.9.3}

where ⊙\odot is the elementwise product: each possible predecessor is weighted by its probability given the start and by its probability of leading to the observed xt\mathbf{x}_t.

A binary token that flips with probability 0.10.1 at every step shows the posterior at work. Here Q1=Q2=(0.90.10.10.9)\mathbf{Q}_1 = \mathbf{Q}_2 = \left(\begin{smallmatrix} 0.9 & 0.1 \\ 0.1 & 0.9 \end{smallmatrix}\right). Start from the first value, x0=(1,0)\mathbf{x}_0 = (1, 0), and suppose that after two steps the token shows the second value, x2=(0,1)\mathbf{x}_2 = (0, 1). This happens with probability 0.9⋅0.1+0.1⋅0.9=0.180.9 \cdot 0.1 + 0.1 \cdot 0.9 = 0.18, the denominator. For the middle state, x2Q2⊤=(0.1,0.9)\mathbf{x}_2 \mathbf{Q}_2^\top = (0.1, 0.9) and x0Qˉ1=(0.9,0.1)\mathbf{x}_0 \bar{\mathbf{Q}}_1 = (0.9, 0.1). Their elementwise product is (0.09,0.09)(0.09, 0.09), and dividing by 0.180.18 gives (1/2,1/2)(1/2, 1/2). The token flipped once, and given both ends the flip is equally likely to have happened at the first step or at the second.

17.9.1.2 The Absorbing Kernel#

The bound needs a closed form for Qˉt\bar{\mathbf{Q}}_t, and the sampler a known starting state. The absorbing kernel of Austin et al. (2021) provides both. It enlarges the vocabulary by one value, the mask [M][\textrm{M}], and moves each token there with probability βt\beta_t at step tt; a masked token stays masked:

Qt=(1−βt) I+βt 1eM⊤,(17.9.4)\mathbf{Q}_t = (1 - \beta_t)\, \mathbf{I} + \beta_t\, \mathbf{1} \mathbf{e}_{\textrm{M}}^\top, \tag{17.9.4}

with 1\mathbf{1} the all-ones column vector and eM\mathbf{e}_{\textrm{M}} the one-hot column vector of the mask, so that every row of 1eM⊤\mathbf{1} \mathbf{e}_{\textrm{M}}^\top puts all its mass on the mask.

Products of such matrices collapse. Write P=1eM⊤\mathbf{P} = \mathbf{1} \mathbf{e}_{\textrm{M}}^\top. Since eM⊤1=1\mathbf{e}_{\textrm{M}}^\top \mathbf{1} = 1, we have P2=P\mathbf{P}^2 = \mathbf{P}, and therefore (aI+bP)(cI+dP)=ac I+(ad+bc+bd) P(a\mathbf{I} + b\mathbf{P})(c\mathbf{I} + d\mathbf{P}) = ac\, \mathbf{I} + (ad + bc + bd)\, \mathbf{P}. When a+b=c+d=1a + b = c + d = 1 the second coefficient equals 1−ac1 - ac, so the coefficient of I\mathbf{I} multiplies along the chain. Let αˉt=∏s≤t(1−βs)\bar{\alpha}_t = \prod_{s \leq t} (1 - \beta_s), the same product as for the Gaussian chain of Section 17.2. There it was the squared weight of the clean point; here it has a more direct meaning, the probability that a token survives tt steps without being masked. Then

Qˉt=αˉt I+(1−αˉt) 1eM⊤.(17.9.5)\bar{\mathbf{Q}}_t = \bar{\alpha}_t\, \mathbf{I} + (1 - \bar{\alpha}_t)\, \mathbf{1}\mathbf{e}_{\textrm{M}}^\top. \tag{17.9.5}

The chain never confuses one token with another; it only erases. A schedule with αˉT=0\bar{\alpha}_T = 0 ends at the fully masked sequence (Figure 17.9.1), which carries no information about the data, as the Gaussian chain ends at pure noise. The other common choice, the uniform kernel, resamples a token uniformly from the vocabulary (Hoogeboom et al., 2021) (Exercise 1).

Figure 17.9.1:

The absorbing chain on nine tokens. Forward, each token is independently replaced by the mask (drawn as ?) with probability βt\beta_t per step and stays masked; after TT steps every token is masked. Reverse, the model predicts masked tokens from the partially masked sequence, and a revealed token is never changed.

We use the absorbing kernel from now on. It gave the best likelihoods on text in the comparisons of Austin et al., and its posterior is as simple as a posterior can be. It also gives something up. In reverse the chain only reveals, so the sampler commits to every token it writes, just as a left-to-right model does. Chains that resample tokens, such as the uniform kernel, and samplers that mask revealed tokens again, such as ReMDM (Wang et al., 2025), can revise an early mistake (Section 17.10).

17.9.2 The Masked Bound#

To train a reverse chain we need a loss, and the variational bound of Section 17.6 offers one.

17.9.2.1 The Same Bound, a Different Target#

The reverse model is a Markov chain pθ(xt−1∣xt)p_{\boldsymbol{\theta}}(\mathbf{x}_{t-1} \mid \mathbf{x}_t), started from the all-mask sequence. Section 17.6 bounded the negative log-likelihood of such a chain by

−log⁡pθ(x0)≤LVLB=DKL(q(xT∣x0) ∥ p(xT))+∑t=2TEq[DKL(q(xt−1∣xt,x0) ∥ pθ(xt−1∣xt))]+Eq[−log⁡pθ(x0∣x1)].\begin{aligned} -\log p_{\boldsymbol{\theta}}(\mathbf{x}_0) \leq L_{\textrm{VLB}} &= D_{\textrm{KL}}\big(q(\mathbf{x}_T \mid \mathbf{x}_0)\, \|\, p(\mathbf{x}_T)\big) \\ &\quad + \sum_{t=2}^{T} \mathbb{E}_q\Big[D_{\textrm{KL}}\big(q(\mathbf{x}_{t-1} \mid \mathbf{x}_t, \mathbf{x}_0)\, \|\, p_{\boldsymbol{\theta}}(\mathbf{x}_{t-1} \mid \mathbf{x}_t)\big)\Big] \\ &\quad + \mathbb{E}_q\big[-\log p_{\boldsymbol{\theta}}(\mathbf{x}_0 \mid \mathbf{x}_1)\big]. \end{aligned}

This is the negative of the evidence lower bound of Section 24.7, with the forward chain as the variational distribution. Its derivation used only the Markov property and Bayes' rule, so it holds for tokens as it stands.

What changes is the target. For Gaussian noise the network predicted the noise, the velocity or the clean point, each an affine function of one posterior mean E[x0∣xt]\mathbb{E}[\mathbf{x}_0 \mid \mathbf{x}_t] (Section 17.1). For a one-hot token that posterior mean is the vector of probabilities of the values the clean token might have, so predicting that distribution is the discrete form of the denoiser the chapter started from. Following Austin et al. (2021), the network outputs, for each position ii, a distribution pθ(x0i∣xt)p_{\boldsymbol{\theta}}(\mathbf{x}_0^i \mid \mathbf{x}_t) over the clean values given the whole corrupted sequence, and the reverse transition averages the true posterior over this prediction,

pθ(xt−1∣xt)=∑x^0q(xt−1∣xt,x^0) pθ(x^0∣xt),(17.9.6)p_{\boldsymbol{\theta}}(\mathbf{x}_{t-1} \mid \mathbf{x}_t) = \sum_{\hat{\mathbf{x}}_0} q(\mathbf{x}_{t-1} \mid \mathbf{x}_t, \hat{\mathbf{x}}_0)\, p_{\boldsymbol{\theta}}(\hat{\mathbf{x}}_0 \mid \mathbf{x}_t), \tag{17.9.6}

position by position, with the prediction at an unmasked position taken to be the observed token. For a single token, a perfect prediction makes this the true reverse transition (Exercise 3a). For a sequence it falls short in one respect: positions that revert in the same step are drawn independently of one another, whereas the true reverse transition draws them jointly. Much of this section is about what that shortfall costs.

17.9.2.2 The Posterior of the Absorbing Chain#

Proposition (posterior of the absorbing chain). Under the absorbing kernel with β1>0\beta_1 > 0, so that αˉt<1\bar{\alpha}_t \lt 1 for every t≥1t \geq 1, consider one position with clean value x0≠[M]\mathbf{x}_0 \neq [\textrm{M}]. If xt=x0\mathbf{x}_t = \mathbf{x}_0, then xt−1=x0\mathbf{x}_{t-1} = \mathbf{x}_0 with probability one. If xt=[M]\mathbf{x}_t = [\textrm{M}], then

q(xt−1=x0∣xt=[M],x0)=αˉt−1−αˉt1−αˉt,q(xt−1=[M]∣xt=[M],x0)=1−αˉt−11−αˉt,(17.9.7)\begin{aligned} q(\mathbf{x}_{t-1} = \mathbf{x}_0 \mid \mathbf{x}_t = [\textrm{M}], \mathbf{x}_0) &= \frac{\bar{\alpha}_{t-1} - \bar{\alpha}_t}{1 - \bar{\alpha}_t}, \\ q(\mathbf{x}_{t-1} = [\textrm{M}] \mid \mathbf{x}_t = [\textrm{M}], \mathbf{x}_0) &= \frac{1 - \bar{\alpha}_{t-1}}{1 - \bar{\alpha}_t}, \end{aligned} \tag{17.9.7}

and no other value has positive probability.

Proof. Evaluate (17.9.3) with (17.9.4) and (17.9.5). The vector x0Qˉt−1\mathbf{x}_0 \bar{\mathbf{Q}}_{t-1} puts mass αˉt−1\bar{\alpha}_{t-1} on x0\mathbf{x}_0 and 1−αˉt−11 - \bar{\alpha}_{t-1} on the mask, so only these two predecessors are possible. If xt=x0\mathbf{x}_t = \mathbf{x}_0, the vector xtQt⊤\mathbf{x}_t \mathbf{Q}_t^\top has the entry 1−βt1 - \beta_t at x0\mathbf{x}_0 and the entry 00 at the mask, because a mask never returns to a token, and the posterior is a point mass. If xt=[M]\mathbf{x}_t = [\textrm{M}], the entries are βt\beta_t at x0\mathbf{x}_0 and 11 at the mask, so the unnormalized posterior is αˉt−1βt\bar{\alpha}_{t-1}\beta_t on x0\mathbf{x}_0 and 1−αˉt−11 - \bar{\alpha}_{t-1} on the mask. Their sum, 1−αˉt−1(1−βt)=1−αˉt1 - \bar{\alpha}_{t-1}(1 - \beta_t) = 1 - \bar{\alpha}_t, is the denominator q(xt=[M]∣x0)q(\mathbf{x}_t = [\textrm{M}] \mid \mathbf{x}_0), and αˉt−1βt=αˉt−1−αˉt\bar{\alpha}_{t-1}\beta_t = \bar{\alpha}_{t-1} - \bar{\alpha}_t. ■\blacksquare

One step back, a masked token either stays masked or reverts to its clean value. The reverse model (17.9.6) therefore copies the unmasked positions of xt\mathbf{x}_t and replaces each masked one, independently, by a draw from pθ(x0i∣xt)p_{\boldsymbol{\theta}}(\mathbf{x}_0^i \mid \mathbf{x}_t) with the probability of reverting.

17.9.2.3 A Weighted Cross-Entropy#

The reverse model copies what is visible and fills only masks, so only the masked positions can cost anything in the bound. The next result, found in this form by Sahoo et al. (2024) and Shi et al. (2024), is the central one of the section: what they cost is a cross-entropy.

Proposition (masked diffusion bound). For the absorbing kernel with αˉ0=1\bar{\alpha}_0 = 1, αˉt<1\bar{\alpha}_t \lt 1 for t≥1t \geq 1, and αˉT=0\bar{\alpha}_T = 0, and the reverse model just described,

LVLB=∑t=1Tαˉt−1−αˉt1−αˉt  Eq(xt∣x0)[∑i : xti=[M]−log⁡pθ(x0i∣xt)].(17.9.8)\begin{aligned} L_{\textrm{VLB}} &= \sum_{t=1}^{T} \frac{\bar{\alpha}_{t-1} - \bar{\alpha}_t}{1 - \bar{\alpha}_t}\; \mathbb{E}_{q(\mathbf{x}_t \mid \mathbf{x}_0)}\Big[ \sum_{i \,:\, \mathbf{x}_t^i = [\textrm{M}]} -\log p_{\boldsymbol{\theta}}(\mathbf{x}_0^i \mid \mathbf{x}_t) \Big]. \end{aligned} \tag{17.9.8}

Proof. The prior term vanishes: αˉT=0\bar{\alpha}_T = 0 makes q(xT∣x0)q(\mathbf{x}_T \mid \mathbf{x}_0) the point mass on the all-mask sequence, which is also p(xT)p(\mathbf{x}_T). Both q(xt−1∣xt,x0)q(\mathbf{x}_{t-1} \mid \mathbf{x}_t, \mathbf{x}_0) and pθ(xt−1∣xt)p_{\boldsymbol{\theta}}(\mathbf{x}_{t-1} \mid \mathbf{x}_t) factorize over positions, so each divergence is a sum of per-position divergences. At an unmasked position both distributions are the same point mass and the divergence is zero. At a masked position write wt=(αˉt−1−αˉt)/(1−αˉt)w_t = (\bar{\alpha}_{t-1} - \bar{\alpha}_t) / (1 - \bar{\alpha}_t). The true posterior puts 1−wt1 - w_t on the mask and wtw_t on x0i\mathbf{x}_0^i; the model puts 1−wt1 - w_t on the mask and wt pθ(⋅∣xt)w_t\, p_{\boldsymbol{\theta}}(\cdot \mid \mathbf{x}_t) on the tokens; hence

DKL=(1−wt)log⁡1−wt1−wt+wtlog⁡wtwt pθ(x0i∣xt)=−wtlog⁡pθ(x0i∣xt).\begin{aligned} D_{\textrm{KL}} &= (1 - w_t) \log \frac{1 - w_t}{1 - w_t} + w_t \log \frac{w_t}{w_t\, p_{\boldsymbol{\theta}}(\mathbf{x}_0^i \mid \mathbf{x}_t)} \\ &= -w_t \log p_{\boldsymbol{\theta}}(\mathbf{x}_0^i \mid \mathbf{x}_t). \end{aligned}

This accounts for t=2,…,Tt = 2, \ldots, T. The reconstruction term is E[−log⁡pθ(x0∣x1)]\mathbb{E}[-\log p_{\boldsymbol{\theta}}(\mathbf{x}_0 \mid \mathbf{x}_1)]. Since w1=(1−αˉ1)/(1−αˉ1)=1w_1 = (1 - \bar{\alpha}_1)/(1 - \bar{\alpha}_1) = 1, the model replaces every position masked at step 11 by a draw from pθ(⋅∣x1)p_{\boldsymbol{\theta}}(\cdot \mid \mathbf{x}_1) and copies the rest, so this term equals the sum of −log⁡pθ(x0i∣x1)-\log p_{\boldsymbol{\theta}}(\mathbf{x}_0^i \mid \mathbf{x}_1) over the masked positions, which is the t=1t = 1 term of the sum. ■\blacksquare

This is the loss of a masked language model with two changes: the masking rate ranges over all levels from nothing to everything instead of staying at one value, and each level carries its own weight. Divided by log⁡2\log 2 and the number of tokens, the bound is a code length in bits per token (Section 25.2), the unit in which we will read it on images.

Under the linear schedule αˉt=1−t/T\bar{\alpha}_t = 1 - t/T, a fraction t/Tt/T of the tokens is masked at step tt, and wt=(1/T)/(t/T)=1/tw_t = (1/T)/(t/T) = 1/t. An error on a heavily masked sequence counts less than the same error on a lightly masked one. Since the number of masked positions grows in proportion to tt, every step carries the same expected weighted count of masked positions, L/TL/T for LL tokens; the steps differ only in how hard their masked tokens are to predict.

The sum is also a Riemann sum. Write ℓ(x0,x)\ell(\mathbf{x}_0, \mathbf{x}) for the cross-entropy on the masked positions of x\mathbf{x}, the inner sum of (17.9.8), and let T→∞T \to \infty with αˉt=αˉ(t/T)\bar{\alpha}_t = \bar{\alpha}(t/T) for a decreasing function on the chapter's clock, data at time 00 and the all-mask sequence at time 11. Since tt now counts steps, we write τ=t/T\tau = t/T for the time. Then wt≈−αˉ′(τ)/(T(1−αˉ(τ)))w_t \approx -\bar{\alpha}'(\tau)/(T(1 - \bar{\alpha}(\tau))). Its factor 1/T1/T is the width dτd\tau of one step, so the bound tends to

∫01−αˉ′(τ)1−αˉ(τ) E[ℓ(x0,xτ)] dτ.\int_0^1 \frac{-\bar{\alpha}'(\tau)}{1 - \bar{\alpha}(\tau)}\, \mathbb{E}\big[\ell(\mathbf{x}_0, \mathbf{x}_\tau)\big]\, d\tau .

Now substitute the masking probability u=1−αˉ(τ)u = 1 - \bar{\alpha}(\tau) (in this section uu is a probability, not a velocity). Since du=−αˉ′(τ) dτdu = -\bar{\alpha}'(\tau)\, d\tau, the integral becomes

∫011u Eu[ℓ(x0,x)] du,\int_0^1 \frac{1}{u}\, \mathbb{E}_u\big[\ell(\mathbf{x}_0, \mathbf{x})\big]\, du,

where Eu\mathbb{E}_u masks each token independently with probability uu. For a network told the masking probability rather than the time, the limit does not depend on the schedule, the discrete counterpart of the schedule invariance of the Gaussian bound (Section 17.6) (Kingma et al., 2021).

In fact the best network needs neither. Which positions are masked is decided by coin flips that never look at the tokens. Once the input shows which positions are masked and what the others hold, the time adds nothing about the hidden tokens. The best prediction at a masked position, the conditional of its token given the visible ones, therefore does not depend on the time at all (Ou et al., 2025) (Exercise 4).

Readers of recent papers will meet this limit in another form: a continuous-time Markov chain that masks each surviving token at the rate −αˉ′(τ)/αˉ(τ)-\bar{\alpha}'(\tau)/\bar{\alpha}(\tau) (Campbell et al., 2022), reversed with the help of ratios of probabilities between sequences that differ in one token (Lou et al., 2024). For the absorbing kernel such a ratio is a known function of time times the clean conditional our network predicts (Ou et al., 2025), so both views train the same object.

The function masked_loss estimates the bound with one step tt per sequence, given the schedule alpha_bar (the values αˉ0,…,αˉT\bar{\alpha}_0, \ldots, \bar{\alpha}_T) and the index mask_id of the mask; the factor TT makes a uniformly drawn step unbiased for the sum over steps. The sum runs over every axis after the first, so pairs of tokens and images share the function. Our networks still receive t/Tt/T, to keep the chapter's interfaces; Exercise 4 measures how little the trained pair model uses it.

def masked_loss(model, x0, t, alpha_bar, mask_id):
    """One-draw estimate of the masked bound per sequence, in nats."""
    T = len(alpha_bar) - 1
    shape = (-1,) + (1,) * (x0.dim() - 1)      # broadcast over positions
    masked = (torch.rand(x0.shape, device=x0.device)
              < (1 - alpha_bar[t]).view(shape))  # with prob. 1 - abar_t
    logits = model(torch.where(masked, mask_id, x0), t / T)
    nll = -torch.log_softmax(logits, -1).gather(-1, x0[..., None])[..., 0]
    w = (alpha_bar[t - 1] - alpha_bar[t]) / (1 - alpha_bar[t])  # 1/t if linear
    return (T * w.view(shape) * nll * masked).flatten(1).sum(1)

17.9.3 Sampling by Unmasking#

A trained network gives a distribution at every masked position. Generation must decide which positions to fill, and when.

17.9.3.1 Parallel Reveals and the Independence Error#

Generation starts from the all-mask sequence. At step tt, one forward pass yields pθ(⋅∣xt)p_{\boldsymbol{\theta}}(\cdot \mid \mathbf{x}_t) at every masked position; each masked position draws a candidate token and accepts it with probability wtw_t. As with the Gaussian samplers of Section 17.5, we would rather not spend TT network evaluations, so we choose levels T=t0>t1>⋯>tS=0T = t_0 > t_1 > \cdots > t_S = 0 and jump between them. Skipping levels composes kernels, and by the collapse shown above a product of absorbing kernels is again absorbing. The coarser chain therefore has the marginals (17.9.5) at its levels, and the proposition applies to it unchanged: the function unmask jumps from tkt_k to tk+1t_{k+1} by revealing each masked token with probability (αˉtk+1−αˉtk)/(1−αˉtk)(\bar{\alpha}_{t_{k+1}} - \bar{\alpha}_{t_k}) / (1 - \bar{\alpha}_{t_k}).

The reveal decisions never look at the network, so we can say in advance when each token appears. The probabilities of staying masked, (1−αˉtk+1)/(1−αˉtk)(1 - \bar{\alpha}_{t_{k+1}})/(1 - \bar{\alpha}_{t_k}), multiply along the jumps and telescope: a token is still masked at level tkt_k with probability 1−αˉtk1 - \bar{\alpha}_{t_k}, as under the forward chain. It is therefore revealed in jump kk, for k=0,…,S−1k = 0, \ldots, S - 1, with probability Δk=αˉtk+1−αˉtk\Delta_k = \bar{\alpha}_{t_{k+1}} - \bar{\alpha}_{t_k}, independently of the other positions.

@torch.inference_mode()
def unmask(model, shape, steps, alpha_bar, mask_id):
    """Reveal tokens from the all-mask state in `steps` jumps."""
    T = len(alpha_bar) - 1
    levels = torch.linspace(T, 0, steps + 1).round().long().tolist()
    z = torch.full(shape, mask_id, device=alpha_bar.device)
    for t, s in zip(levels[:-1], levels[1:]):
        logits = model(z, torch.full(shape[:1], t / T, device=z.device))
        draw = torch.distributions.Categorical(logits=logits).sample()
        p = (alpha_bar[s] - alpha_bar[t]) / (1 - alpha_bar[t])  # reveal prob.
        reveal = (z == mask_id) & (torch.rand(shape, device=z.device) < p)
        z = torch.where(reveal, draw, z)
    return z

The network's prediction is a product over positions. Tokens revealed in the same jump are therefore drawn independently of one another, each from its own predicted distribution, while tokens revealed in different jumps are drawn one after another, each conditioned on those already revealed. What does this independence cost? Let us start with the smallest case in which it can cost anything: two tokens.

The chapter's running example supplies them. It is the mixture of three Gaussians in the plane with means (−2.5,−1.5)(-2.5, -1.5), (2.5,−1.5)(2.5, -1.5) and (0,2.5)(0, 2.5), weights 0.50.5, 0.30.3 and 0.20.2, and standard deviation 0.50.5 (Section 17.1). Quantizing the plane onto a 32×3232 \times 32 grid over [−5,5]2[-5, 5]^2 turns each sample into a pair of tokens, the indices of its cell along the two axes. The table pp of the pairs has three blobs, one per mode. Its marginals p1p^1 and p2p^2 have three bumps along the first axis but only two along the second, since two modes share a height. The product of the marginals, p1⊗p2p^1 \otimes p^2, draws the two tokens independently and puts a blob at every crossing of a bump of one with a bump of the other: six blobs, three of them where no data lie.

Now take an exact network, whose prediction at each masked position is the true conditional of that token given the unmasked ones. With SS equal jumps under the linear schedule, Δk=1/S\Delta_k = 1/S for every jump, so both tokens are revealed in the same jump with probability S⋅(1/S)2=1/SS \cdot (1/S)^2 = 1/S, and in that event the pair comes from p1⊗p2p^1 \otimes p^2. Otherwise one token is drawn from its marginal and the other later from its conditional, and the pair comes from pp. The sampler draws from the mixture

(1−1S)p+1S p1⊗p2.\left(1 - \tfrac{1}{S}\right) p + \tfrac{1}{S}\, p^1 \otimes p^2 .

In total variation, half the summed absolute difference of two probability tables, this mixture lies TV(p1⊗p2,p)/S\mathrm{TV}(p^1 \otimes p^2, p)/S from pp. The error falls as one over the number of steps and grows with the dependence between the tokens.

We can predict the one-step error before computing anything. The three phantom blobs of the product receive 0.5⋅0.2+0.3⋅0.2+0.2⋅0.8=0.320.5 \cdot 0.2 + 0.3 \cdot 0.2 + 0.2 \cdot 0.8 = 0.32 of the mass, and if no blobs overlapped this would be the total variation. Cell probabilities factorize into one-dimensional Gaussian integrals, so the cell below computes pp exactly, with its entropy, the mutual information of the two tokens, and the error of an exact network's sampler for four step counts.

mix = d2l.GaussianMixture.three_modes()
means, weights = np.float64(mix.means), np.float64(mix.weights)
K, T = 32, 32                 # vocabulary of each token; number of steps
edges = np.linspace(-5, 5, K + 1)
cdf = ndtr((edges - means[:, :, None]) / mix.std)  # (modes, axes, K + 1)
cdf[:, :, 0], cdf[:, :, -1] = 0, 1      # edge cells extend to infinity
cell = np.diff(cdf, axis=2)             # mass of each cell, per mode, axis
table = np.einsum('m,mi,mj->ij', weights, cell[:, 0], cell[:, 1])
p1, p2 = table.sum(1), table.sum(0)     # marginals of the two tokens
product = np.outer(p1, p2)
H = lambda p: -xlogy(p, p).sum()        # entropy in nats
tv = lambda p, q: np.abs(p - q).sum() / 2
mutual = H(p1) + H(p2) - H(table)
print(f'entropy {H(table):.3f} nats, mutual information {mutual:.3f} nats')
for S in (1, 2, 8, 32):
    print(f'{S:>2} steps, exact network: TV {tv(product, table) / S:.3f}')
entropy 4.840 nats, mutual information 0.479 nats
 1 steps, exact network: TV 0.314
 2 steps, exact network: TV 0.157
 8 steps, exact network: TV 0.039
32 steps, exact network: TV 0.010

The one-step sampler misplaces 0.3140.314 of the mass, a little less than the predicted 0.320.32 because neighboring blobs overlap slightly, and thirty-two steps bring the error down to 0.0100.010.

17.9.3.2 Confidence-Ordered Reveals#

Many practical samplers do not reveal at random. MaskGIT (Chang et al., 2022) and the diffusion language model LLaDA (Nie et al., 2025) draw a candidate at every masked position, keep the candidates that are most probable under their own predicted distributions, and mask the others again. This confidence remasking chooses which tokens to reveal from the values it has drawn. Is that better than a random order? The two-token table answers without any training. For two tokens, confidence remasking draws both from their marginals, A∼p1A \sim p^1 and B∼p2B \sim p^2, keeps the draw that is more probable under its own marginal, and redraws the other from its conditional given the kept one. Its output table is

q(a,b)=p1(a) P(p2(B)≤p1(a)) p(b∣a)+p2(b) P(p1(A)<p2(b)) p(a∣b),\begin{aligned} q(a, b) &= p^1(a)\, P\big(p^2(B) \leq p^1(a)\big)\, p(b \mid a) \\ &\quad + p^2(b)\, P\big(p^1(A) \lt p^2(b)\big)\, p(a \mid b), \end{aligned}

where the first term keeps the draw aa of the first token and the second keeps the draw bb of the second. The cell compares this table with those of one step, two random jumps, and a fixed order (first token from its marginal, second from its conditional).

c2 = table / p1[:, None]                # p(x2 | x1); each row sums to one
c1 = table / p2[None, :]                # p(x1 | x2); each column sums to one
keep1 = p1[:, None] >= p2[None, :]      # the draw of x1 is the likelier one
confidence = ((product * keep1).sum(1)[:, None] * c2
              + (product * ~keep1).sum(0)[None, :] * c1)
centers = (edges[:-1] + edges[1:]) / 2
grid = np.stack(np.meshgrid(centers, centers, indexing='ij'), -1)
mode = ((grid[:, :, None] - means) ** 2).sum(-1).argmin(-1)  # nearest mode
orders = {'one step': product, 'two random jumps': (product + table) / 2,
          'fixed order': p1[:, None] * c2, 'confidence': confidence}
print(f'{"order":>16} {"TV":>6} {"entropy":>8}  mass near the modes')
for name, q in orders.items():
    masses = ' '.join(f'{q[mode == k].sum():.3f}' for k in range(3))
    print(f'{name:>16} {tv(q, table):6.3f} {H(q):8.3f}  {masses}')
           order     TV  entropy  mass near the modes
        one step  0.314    5.319  0.482 0.321 0.197
two random jumps  0.157    5.216  0.491 0.310 0.199
     fixed order  0.000    4.840  0.500 0.300 0.200
      confidence  0.179    4.406  0.606 0.322 0.072

With exact conditionals, an order fixed before the tokens are drawn, left to right or random, is exact when it reveals one token per step, as the fixed order shows. Two random jumps reveal both tokens together half of the time and halve the one-step error. Surprisingly, confidence remasking, which also reveals one token per step but chooses its order from the values it draws, lands farther from pp than two random jumps, at 0.1790.179 against 0.1570.157. The formula shows why. A draw from a small mode has a small marginal probability, so it tends to lose the comparison and is the one redrawn, from a conditional given the winner that rarely leads back to the small mode. The sampler seeks modes: the smallest mode falls from 0.20.2 to about 0.070.07, and the entropy drops from 4.844.84 to 4.414.41 nats. On text, lower entropy often reads as fluency, and with an imperfect network it can help to reveal the easy positions first. But the bound does not describe this sampler and cannot detect its bias. It scores predictions under random masks, which is to say it describes the random-order sampler.

17.9.4 Trained Denoisers#

So far every number came from an exact table. We now train networks, first on the pair, where every error can be attributed, then on images.

17.9.4.1 The Quantized Mixture#

The network for the pair takes the one-hot encoding of both tokens, with the mask as a thirty-third value at index KK, together with the time t/Tt/T, and outputs logits over the 3232 clean values at each position. The schedule is linear with T=32T = 32 steps.

class MaskedMLP(nn.Module):
    """Logits of both clean tokens of a pair, given the masked pair and t."""
    def __init__(self, K, hidden=256):
        super().__init__()
        self.K = K
        self.net = d2l.make_mlp([2 * (K + 1) + 1, hidden, hidden, 2 * K],
                                nn.SiLU())

    def forward(self, z, t):  # z: (n, 2) in {0, ..., K}, where K is the mask
        h = F.one_hot(z, self.K + 1).float().flatten(1)
        return self.net(torch.cat([h, t[:, None]], 1)).view(-1, 2, self.K)

def quantize(x):  # points in the plane to pairs of tokens in {0, ..., K - 1}
    return ((x + 5) / 10 * K).floor().long().clamp(0, K - 1)

alpha_bar = 1 - torch.arange(T + 1) / T     # the linear schedule

We train it with d2l.train_regression (Section 17.1) on fresh draws from the mixture, 512 pairs per batch, each with a uniformly drawn step, with a learning rate that decays along a cosine over 6,000 updates.

torch.manual_seed(0)
batch_fn = lambda: (quantize(mix.sample(512)), torch.randint(1, T + 1, (512,)))
loss_fn = lambda model, batch: masked_loss(model, *batch, alpha_bar,
                                           mask_id=K).mean()
_, pair_model, _ = d2l.train_regression(MaskedMLP(K), loss_fn, batch_fn,
                                        6000, cosine=True)

With two positions, the expectation in the bound can be computed exactly. At each step there are three mask patterns with at least one mask. A pattern with mm masks has probability um(1−u)2−mu^m (1 - u)^{2 - m}, where u=1−αˉtu = 1 - \bar{\alpha}_t, and the 1,024 pairs are weighted by the table. This average cannot fall below the entropy of the table, the smallest average negative log-likelihood any model attains (Section 25.1). How close can a network come?

Let us work it out for an exact network, writing X1X^1 and X2X^2 for the two tokens of a pair drawn from the table. The bound scores each token at the step in which the reverse chain reveals it: the weight wtw_t times the probability 1−αˉt1 - \bar{\alpha}_t that the token is masked at step tt is αˉt−1−αˉt\bar{\alpha}_{t-1} - \bar{\alpha}_t, the probability that the reverse chain reveals it at step tt. When the tokens are revealed in different steps, the first is predicted from its marginal and the second from its conditional given the first; together they cost H(X1)+H(X2∣X1)=H(X1,X2)H(X^1) + H(X^2 \mid X^1) = H(X^1, X^2), nothing more. Two tokens revealed in the same step are predicted independently from their marginals and cost H(X1)+H(X2)H(X^1) + H(X^2) instead of H(X1,X2)H(X^1, X^2), an excess of the mutual information I(X1;X2)I(X^1; X^2) (Section 25.6). Under the linear schedule each token is revealed at a given step with probability 1/T1/T, so both are revealed in the same step with probability T⋅(1/T)2=1/TT \cdot (1/T)^2 = 1/T, and an exact network attains

H(X1,X2)+I(X1;X2)TH(X^1, X^2) + \frac{I(X^1; X^2)}{T}

(Exercise 5 turns this argument into a proof for every schedule). No network that predicts the positions independently can go below this floor, 4.840+0.479/32≈4.8554.840 + 0.479/32 \approx 4.855 nats. As T→∞T \to \infty no two tokens are revealed in the same step, and the floor falls to the entropy.

@torch.inference_mode()
def exact_bound(model, table, alpha_bar, mask_id):
    """The bound averaged over the table, summed exactly over t and masks."""
    T, K = len(alpha_bar) - 1, len(table)
    pairs = torch.cartesian_prod(torch.arange(K), torch.arange(K))
    p, total = torch.tensor(table.flatten(), dtype=torch.float32), 0.0
    for t in range(1, T + 1):
        u = 1 - alpha_bar[t]
        w = (alpha_bar[t - 1] - alpha_bar[t]) / u
        for masked in torch.tensor([[1, 0], [0, 1], [1, 1]], dtype=torch.bool):
            z, m = torch.where(masked, mask_id, pairs), masked.sum()
            logp = torch.log_softmax(model(z, torch.full((K * K,), t / T)), -1)
            nll = -(logp.gather(-1, pairs[..., None])[..., 0] * masked).sum(1)
            total += u ** m * (1 - u) ** (2 - m) * w * (p @ nll)
    return float(total)

bound = exact_bound(pair_model, table, alpha_bar, mask_id=K)
print(f'exact bound {bound:.3f} nats; '
      f'entropy {H(table):.3f}, floor {H(table) + mutual / T:.3f}')
exact bound 4.856 nats; entropy 4.840, floor 4.855

The bound lies less than two hundredths of a nat above the entropy: the model has learned the marginal of each token and its conditional given the other. Almost all of the gap is the floor; the network's own excess over the floor is of the order of a thousandth of a nat. The floor is not just looseness of the bound: the thirty-two-step sampler of an exact network models (1−1/32) p+(1/32) p1⊗p2(1 - 1/32)\, p + (1/32)\, p^1 \otimes p^2 rather than pp. The bound and the sampler agree about what is lost.

Does the trained sampler lose the same? With two tokens its output table can be summed instead of sampled. Each token is revealed in jump kk with probability Δk\Delta_k (pi in the code), independently of the other. Tokens revealed together are drawn from the network's two marginals at that level, and a token revealed later from its conditional given the first. conditionals reads these predictions from a pair model, and sampler_table sums over the jumps; fed the true marginals and conditionals, it must reproduce the exact network's errors printed earlier.

@torch.inference_mode()
def conditionals(model, tau):
    """A pair model's predictions at time tau: both marginals with both
    tokens masked, then c2[a, b] = q(x2 = b | x1 = a), c1[a, b] = q(x1 = a |
    x2 = b)."""
    K = model.K                                   # also the mask index
    a, m = torch.arange(K), torch.full((K,), K)
    z = torch.cat([torch.tensor([[K, K]]),        # both masked
                   torch.stack([a, m], 1),        # x1 = a revealed
                   torch.stack([m, a], 1)])       # x2 = a revealed
    q = torch.softmax(model(z, torch.full((2 * K + 1,), tau)), -1)
    q = q.double().numpy()                        # (2K + 1, 2, K)
    return q[0, 0], q[0, 1], q[1:K + 1, 1], q[K + 1:, 0].T

Given a function cond with the signature of conditionals, sampler_table sums over all jump combinations to form the exact output distribution of the SS-step unmasking sampler, which we compare against the true joint table for both pair_model and exact across S∈{32,8,2,1}S \in \{32, 8, 2, 1\}:

def sampler_table(cond, steps, alpha_bar):
    """Exact output table of `unmask` on a pair; cond(t / T) returns the
    predictions at level t in the order of `conditionals`."""
    T = len(alpha_bar) - 1
    levels = [round(l) for l in np.linspace(T, 0, steps + 1)]
    pi = np.float64([float(alpha_bar[s] - alpha_bar[t])  # P(revealed in jump)
                     for t, s in zip(levels[:-1], levels[1:])])[:, None]
    q1, q2, c2, c1 = map(np.stack, zip(*[cond(t / T) for t in levels[:-1]]))
    before1 = np.cumsum(pi * q1, 0) - pi * q1     # revealed in earlier jumps
    before2 = np.cumsum(pi * q2, 0) - pi * q2
    return (np.einsum('j,ja,jb->ab', pi[:, 0] ** 2, q1, q2)   # same jump
            + np.einsum('ja,jab->ab', pi * before1, c2)       # x1 first
            + np.einsum('jb,jab->ab', pi * before2, c1))      # x2 first

exact = lambda tau: (p1, p2, c2, c1)  # the true marginals and conditionals
print('TV to the table: trained and exact network; TV between the two')
for S in (32, 8, 2, 1):
    q = sampler_table(lambda tau: conditionals(pair_model, tau), S, alpha_bar)
    q_exact = sampler_table(exact, S, alpha_bar)
    print(f'{S:>2} steps: trained {tv(q, table):.3f}, exact '
          f'{tv(q_exact, table):.3f}, between {tv(q, q_exact):.3f}')
TV to the table: trained and exact network; TV between the two
32 steps: trained 0.020, exact 0.010, between 0.013
 8 steps: trained 0.045, exact 0.039, between 0.013
 2 steps: trained 0.159, exact 0.157, between 0.012
 1 steps: trained 0.316, exact 0.314, between 0.012

The exact column reproduces 0.314/S0.314/S, and the trained sampler follows it at every step count. The network's own error, the distance between the trained and the exact table, is about 0.010.01 for every SS. This error doubles the distance at thirty-two steps, 0.0200.020 against 0.0100.010, and hardly matters at one or two. More steps cannot remove it; only a better network can.

The panels below show 2,000 data pairs and 2,000 pairs from each sampler, drawn with unmask, each placed at random inside its cell. The one-step sampler fills the three phantom blobs, where the column of one mode crosses the row of another.

torch.manual_seed(1)
pairs = [quantize(mix.sample(2000))] + [
    unmask(pair_model, (2000, 2), S, alpha_bar, mask_id=K) for S in (32, 1)]
decode = lambda z: (z + torch.rand(len(z), 2)) / K * 10 - 5  # inside cell
d2l.scatter_panels([decode(z) for z in pairs], ['data', '32 steps', '1 step']);

17.9.4.2 Images as Binary Tokens#

Two tokens show the mechanism; an image shows it at scale. Masked diffusion for images works on the discrete codes of a learned tokenizer (Chang et al., 2022). Binary pixels stand in for such codes here because they need no tokenizer. Thresholding Fashion-MNIST at half intensity makes every pixel a token with two values, and a masked pixel has a third. An image is then a sequence of 784 tokens on a grid, so the network can be the chapter's U-Net (Section 17.4); it takes the one-hot encoding as three input channels and returns the logits of the clean pixel as two output channels. The loss and the sampler are those of the pair, with a linear schedule of T=100T = 100 steps and the mask at index 2.

X, _, X_test, _ = d2l.load_fashion_mnist_pm1(binary=True)  # (n, 28, 28)
T_img = 100                                   # steps of the image chain
alpha_bar_img = 1 - torch.arange(T_img + 1, device=X.device) / T_img

class MaskedUNet(nn.Module):
    """d2l.UNet on one-hot pixels (black, white, mask); clean-pixel logits."""
    def __init__(self):
        super().__init__()
        self.unet = d2l.UNet(in_channels=3, out_channels=2)

    def forward(self, z, t):  # z: (n, 28, 28) in {0, 1, 2}
        x = F.one_hot(z, 3).float().permute(0, 3, 1, 2)
        return self.unet(x, t).permute(0, 2, 3, 1)  # (n, 28, 28, 2)

Training takes 6,000 updates on batches of 128 images, with a constant learning rate and a moving average of the weights with a half-life of 1,000 updates.

torch.manual_seed(2)
def batch_fn():
    i = torch.randint(0, len(X), (128,), device=X.device)
    return X[i], torch.randint(1, T_img + 1, (128,), device=X.device)

loss_fn = lambda model, batch: masked_loss(  # per pixel
    model, *batch, alpha_bar_img, mask_id=2).mean() / (28 * 28)
_, unet, _ = d2l.train_regression(MaskedUNet().to(X.device), loss_fn,
                                  batch_fn, 6000)

We estimate the bound on 1,000 held-out images, with one random mask per image and level, and compare it with the cross-entropy of a model that treats pixels as independent, using the frequency of white at each position in the training set.

X_eval = X_test[:1000]
with torch.inference_mode():
    bound = sum(masked_loss(unet, X_eval, torch.full_like(X_eval[:, 0, 0], t),
                            alpha_bar_img, mask_id=2).mean()
                for t in range(1, T_img + 1)) / T_img
white = X.float().mean(0).clamp(1e-6, 1 - 1e-6)  # frequency of white
indep = -torch.where(X_eval == 1, white.log(), (1 - white).log()).sum((1, 2))
bits = lambda nats: f'{nats / math.log(2) / (28 * 28):.3f} bits per pixel'
print(f'bound {bits(bound)}, independent pixels {bits(indep.mean())}')
bound 0.170 bits per pixel, independent pixels 0.702 bits per pixel

The bound is about 0.17 bits per pixel, against about 0.70 for independent pixels: read as code lengths, about 135 bits for a held-out garment instead of about 550. Independent pixels are a weak yardstick, admittedly, since almost any model that looks at a pixel's neighbors beats them by a wide margin. What the run does establish is the size of the gap: a model of the dependence between pixels saves at least three quarters of the code length of independent pixels, and the network has learned enough of that dependence to do so. The fair rival would be a model of the same size that reveals the pixels one at a time in raster order. We do not train one here; Section 17.9.5.1 reports how masked diffusion and left-to-right models compare on text.

The sampler draws 1,000 images in a hundred steps; the grid shows the first 48.

torch.manual_seed(3)
z100 = unmask(unet, (1000, 28, 28), T_img, alpha_bar_img, mask_id=2)
d2l.show_gray(z100[:48], 6, 8, scale=0.8);

Most samples are recognizable binary garments, rougher than the gray-level samples of the earlier sections; about one in five is a fragment or nearly empty. Six thousand updates leave the U-Net undertrained, which is acceptable here: the experiment is about the bound and the number of steps, not about the best garment. Each of the hundred jumps reveals about eight pixels, drawn from predictions that see every pixel revealed in earlier jumps. The next grid uses four jumps of about 200 pixels each.

z4 = unmask(unet, (1000, 28, 28), 4, alpha_bar_img, mask_id=2)
d2l.show_gray(z4[:48], 6, 8, scale=0.8);

No garment survives. The first jump draws its pixels independently from predictions for an all-mask image, which know only where garments tend to be, and every later jump conditions on this noise. What remains is a garment's outline, more often an average garment's than any particular one's, filled with texture.

To measure what four steps lose, we count speckles, pixels that differ from all four of their neighbors, in 1,000 images of each kind, and print each fraction with its standard error over the 1,000 images. A third batch takes 784 jumps, one pixel per jump on average, to show what a hundred steps still lose. The chain's hundred levels cannot carry that many jumps: unmask rounds its levels to the chain's, and a jump between two equal levels reveals nothing. These jumps therefore run on a linear schedule of 784 levels of their own. Most of their times k/784k/784 fall between the hundred times the network was trained at (the last seven lie below the smallest), and the number of masked pixels tells it the time in any case.

def speckles(z):
    """Per image, the fraction of interior pixels unlike all four neighbors."""
    c = z[:, 1:-1, 1:-1]
    unlike = ((c != z[:, :-2, 1:-1]) & (c != z[:, 2:, 1:-1])
              & (c != z[:, 1:-1, :-2]) & (c != z[:, 1:-1, 2:]))
    return unlike.float().mean((1, 2))

alpha_bar_784 = 1 - torch.arange(785, device=X.device) / 784  # 784 levels
z784 = unmask(unet, (1000, 28, 28), 784, alpha_bar_784, mask_id=2)
for name, z in (('data', X[:1000]), ('784 steps', z784), ('100 steps', z100),
                ('4 steps', z4)):
    per_image = speckles(z)
    print(f'{name:>9}: speckles {per_image.mean():.4f}, standard error over '
          f'the 1,000 images {per_image.std() / len(z) ** 0.5:.5f}')
     data: speckles 0.0037, standard error over the 1,000 images 0.00016
784 steps: speckles 0.0047, standard error over the 1,000 images 0.00016
100 steps: speckles 0.0075, standard error over the 1,000 images 0.00021
  4 steps: speckles 0.0330, standard error over the 1,000 images 0.00027

The data have about four speckles per thousand interior pixels, and the four-step samples about nine times as many: the image counterpart of the phantom blobs of the one-step pair. The hundred-step samples have about twice the data's count, and there two causes mix: about eight pixels still appear per jump, and the network is imperfect after 6,000 updates. The 784-step row pulls them apart. More jumps shrink the independence error and leave the network's own error where it was, as on the pair, and one pixel per jump removes two thirds to three quarters of the hundred-step excess. Could the draw of the images alone produce that drop? Both rows come from the same network, so the 1,000 images of each are the only chance in the comparison. Each count is a mean over independent images, with a standard error of 0.00016 to 0.0002, and the difference of two such means has one of about 0.00026; the drop is about ten times that. Most of what a hundred steps lose is therefore the independence error, not the network. The rest, which leaves the 784-step samples with about 1.3 times the data's speckles, still about four standard errors of a difference above the data, is the network's own error plus what little independence remains when a pixel seldom shares its jump with a neighbor; Exercise 2e separates the two.

17.9.5 Neighbors and Retrospect#

This section has treated masked diffusion on its own terms. Its neighbors in the book are the language models of Section 11.2 and Section 11.4, and its ancestors are the earlier sections of this chapter.

17.9.5.1 Diffusion and Autoregression#

A reader who has trained the language model of Section 11.2 will want to know how it relates to this one. The two-token tables answer, once we sort samplers by the number of tokens they reveal per step.

Reveal one token per step in a fixed order, left to right, and the sampler has the form of the language model of Section 11.2. Its conditionals are the network's predictions at inputs with an unmasked prefix and a masked rest. On the pair this is the fixed-order row of the table of four orders, at distance 0.0000.000 from pp: with exact conditionals, a chain of one-token reveals is exact, and its loss is the entropy.

Reveal one token per step in a uniformly random order, and the sampler is an order-agnostic autoregressive model (Uria et al., 2014), whose loss averages the negative log-likelihoods of all orders. Hoogeboom et al. (2022) showed that this loss is the continuous-time bound of Section 17.9.2.3 for a network that ignores the time (Exercise 6 derives it with a Beta integral), and Ou et al. (2025) that ignoring the time loses nothing, since the best prediction for a masked token depends only on the tokens already revealed. A masked diffusion model is thus trained as a language model over all orders at once. For an exact network every order gives the same joint likelihood, the entropy of the data, so its continuous-time bound is tight. This is the floor of the pair seen from the orders: as T→∞T \to \infty no two tokens are revealed together, and the excess I/TI/T vanishes.

Reveal several tokens per step, and the sampler incurs the independence error: on the pair, SS jumps draw 1/S1/S of the mass from the product of the marginals, and a TT-step bound rises by I/TI/T. In exchange, SS network evaluations generate LL tokens, where a left-to-right model needs LL.

The two kinds of evaluation are not the same size, though. A left-to-right model that caches its keys and values (Section 11.3) processes one new token per step. The denoiser has no causal mask, so a revealed token changes the activations at every position, nothing can be cached, and each evaluation is a full pass over all LL positions. Counted in token passes the costs are about LL against SLS L. Parallel decoding therefore saves sequential steps, and with them latency, while its total arithmetic is typically higher. Fast-dLLM (Wu et al., 2026) recovers part of it by reusing approximate caches across steps, and block diffusion (Arriola et al., 2025) by decoding block after block with an exact cache over the finished blocks.

At the far end stands BERT (Devlin et al., 2018), which hides 15% of the tokens of a text and predicts them from both sides; the masked language model of Section 11.4 does the same, masking each byte with probability 15%. Restricted to this single masking level, the loss (17.9.8) becomes their masked-token objective, the summed negative log-likelihood of the hidden tokens, up to BERT's replacement of some masks by random or unchanged tokens. A masked language model is thus a discrete diffusion model with one step (Austin et al., 2021), though one that has seen a single masking level; a sampler starting from the all-mask sequence would show it inputs far from anything it was trained on.

Between these extremes sit today's diffusion language models, whose denoiser is a transformer without the causal mask, with an extra vocabulary entry for [M][\textrm{M}] and no time input (Nie et al., 2025). What do they gain? Not likelihood where data are plentiful: with fresh data throughout, masked diffusion needs a constant factor more compute than an autoregressive model to reach the same loss (Nie et al., 2025). When data are scarce and repeated many times, it can come out ahead (Prabhudesai et al., 2025), which the authors attribute to the random masks acting as data augmentation. The case for these models rests on parallel decoding, which writes many tokens per network evaluation and so needs fewer sequential steps, and on infilling, which conditions on text on both sides of a gap.

17.9.5.2 Diffusion Models in Retrospect#

Apart from its further reading, the chapter ends here, and with it the Advanced part, so let us look back once. One idea carried every section: a network that predicts the clean point from a noisy one, at every noise level, is a generator, and a sampler turns its predictions into data by integrating them. For tokens the noisy point became a partly erased sequence, the prediction a distribution over the erased values and the integration a sequence of reveals; the bound carried over unchanged.

Each part of that answer has a drawback, and a practitioner meets all of them. The density arrives as a bound, and the weighting that gives the best bound is not the one that gives the best samples (Section 17.6). A regression replaces the adversarial game of Chapter 16, but sampling calls the network many times: a thousand for the original DDPM chain, a few tens with a good solver (Section 17.5), and a handful only after a second training run that distills a student (Section 17.8). A latent space makes large images affordable but adds a second model, the autoencoder, trained first and then frozen (Section 17.7). And for text, many tokens per evaluation bring the independence error, and the sampler cannot take back what it wrote.

Several questions remain open. Few-step students trained along their teacher's trajectories still trail it. The students that match or pass their teachers add a critic to distribution matching, and give up the map from noise to sample (Section 17.8). No single weighting is known to give both the best likelihood and the best samples. Whether the compute gap between masked diffusion and autoregression on text persists at the largest scales is being decided by experiments far larger than any in this book.

17.9.6 Summary#

Discrete diffusion corrupts categorical tokens via row-stochastic transition matrices Qt\mathbf{Q}_t; under the absorbing kernel, each token survives tt steps with probability αˉt=∏s≤t(1−βs)\bar\alpha_t = \prod_{s \le t}(1 - \beta_s) and is otherwise replaced by [M][\textrm{M}]. Its variational bound on the negative log-likelihood simplifies to a weighted sum of masked-token cross-entropies with weight wt=(αˉt−1−αˉt)/(1−αˉt)w_t = (\bar\alpha_{t-1} - \bar\alpha_t)/(1 - \bar\alpha_t) (1/t1/t under a linear schedule) and continuous-time limit ∫011u Eu[ℓ] du\int_0^1 \frac{1}{u}\, \mathbb{E}_u[\ell]\, du, where independent masking renders the optimal clean-token distribution at a masked position time-agnostic. Because the reverse model factorizes across positions within each step, unmasking multiple tokens simultaneously incurs an independence error: on a two-token distribution pp, SS equal linear jumps sample from (1−1/S)p+(1/S)p1⊗p2(1 - 1/S)p + (1/S)p^1 \otimes p^2 with total variation error proportional to 1/S1/S, and the TT-step bound floor exceeds the entropy H(X1,X2)H(X^1, X^2) by I(X1;X2)/TI(X^1; X^2)/T. Viewed across unmasking schedules, masked diffusion connects classical sequence models: revealing one token per step left to right recovers autoregressive modeling (Section 11.2), revealing one token per step in a random order recovers order-agnostic autoregression, and training at a single masking rate u=0.15u = 0.15 recovers BERT (Section 11.4).

17.9.7 Exercises#

  1. The uniform kernel. Let the forward chain use the uniform kernel Qt=(1−βt) I+βt 1K11⊤\mathbf{Q}_t = (1 - \beta_t)\, \mathbf{I} + \beta_t\, \tfrac{1}{K}\mathbf{1}\mathbf{1}^\top with βt>0\beta_t > 0 at every step.

    1. Show that Qˉt=αˉt I+(1−αˉt) 1K11⊤\bar{\mathbf{Q}}_t = \bar{\alpha}_t\, \mathbf{I} + (1 - \bar{\alpha}_t)\, \tfrac{1}{K}\mathbf{1}\mathbf{1}^\top and that xt=x0\mathbf{x}_t = \mathbf{x}_0 with probability αˉt+(1−αˉt)/K\bar{\alpha}_t + (1 - \bar{\alpha}_t)/K. A token that shows a value at step tt may therefore have been resampled. Which question about every position does a network have to answer under this kernel but not under the absorbing kernel?
    2. Derive the posterior q(xt−1∣xt,x0)q(\mathbf{x}_{t-1} \mid \mathbf{x}_t, \mathbf{x}_0) from (17.9.3), treating the cases xt=x0\mathbf{x}_t = \mathbf{x}_0 and xt≠x0\mathbf{x}_t \neq \mathbf{x}_0 separately. Show that for t≥2t \geq 2 every one of the KK values has positive probability, unlike under the two-point posterior (17.9.7).
    3. The divergence terms of the bound compare this posterior with the reverse model at every position. Why are they more expensive to evaluate than the summand of (17.9.8)?
  2. [code] Pairs revealed together. Let the sampler use the levels T=t0>t1>⋯>tS=0T = t_0 > t_1 > \cdots > t_S = 0 under a schedule with αˉ0=1\bar{\alpha}_0 = 1 and αˉT=0\bar{\alpha}_T = 0, and write Δk=αˉtk+1−αˉtk\Delta_k = \bar{\alpha}_{t_{k+1}} - \bar{\alpha}_{t_k} for the increase of αˉ\bar{\alpha} in jump kk, where k=0,…,S−1k = 0, \ldots, S - 1.

    1. In the coarser chain on the levels tkt_k, a token is revealed in jump kk with probability Δk\Delta_k, independently of the other positions. Show that two tokens are revealed in the same jump with probability ρ=∑kΔk2\rho = \sum_k \Delta_k^2, and that, among all SS increments that sum to one, equal increments Δk=1/S\Delta_k = 1/S minimize ρ\rho.
    2. Show that with an exact network the sampler draws the two tokens of the quantized mixture from (1−ρ) p+ρ p1⊗p2(1 - \rho)\, p + \rho\, p^1 \otimes p^2.
    3. For a sequence of LL tokens and equal increments, compute the expected number of pairs of tokens revealed in the same jump. How many steps keep it below one for L=1024L = 1024? Why does this count overstate the error of the sampler on text?
    4. A jump that reveals no token leaves the input of the next jump unchanged. A sampler whose network ignores the time, as the exact network does by Exercise 4a, can therefore draw the reveal decisions first and evaluate the network only in the jumps that reveal at least one token. Show that with SS equal jumps under the linear schedule the expected number of evaluations is S (1−(1−1/S)L)S\, (1 - (1 - 1/S)^L) for LL tokens. Evaluate it for the pair with S=32S = 32, for the binary images with S=100S = 100 and S=784S = 784, and for L=S=1024L = S = 1024.
    5. The 784-step samples of Section 17.9.4.2 keep a quarter to a third of the hundred-step excess of speckles. Show that with SS equal jumps an interior pixel shares its jump with at least one of its four neighbors with probability 1−(1−1/S)41 - (1 - 1/S)^4, and evaluate it for S=4S = 4, 100100 and 784784. Then train unet for twice as many updates and count the speckles at 100 and at 784 jumps again. Which count falls, and what does that say about the share of the remaining excess that is the network's?
  3. Two reverse parameterizations. ● The reverse model (17.9.6) averages the posterior over the network's prediction. Austin et al. (2021) instead set

pθ(xt−1∣xt)∝∑x^0q(xt−1,xt∣x^0) p~θ(x^0∣xt)(17.9.9)p_{\boldsymbol{\theta}}(\mathbf{x}_{t-1} \mid \mathbf{x}_t) \propto \sum_{\hat{\mathbf{x}}_0} q(\mathbf{x}_{t-1}, \mathbf{x}_t \mid \hat{\mathbf{x}}_0)\, \tilde{p}_{\boldsymbol{\theta}}(\hat{\mathbf{x}}_0 \mid \mathbf{x}_t) \tag{17.9.9}

for a network output p~θ\tilde{p}_{\boldsymbol{\theta}}, which reweights each candidate by q(xt∣x^0)q(\mathbf{x}_t \mid \hat{\mathbf{x}}_0). For most kernels the two forms differ. Let q(x0∣xt)q(\mathbf{x}_0 \mid \mathbf{x}_t) and q(xt−1∣xt)q(\mathbf{x}_{t-1} \mid \mathbf{x}_t) denote the conditionals of the forward process started from the data.

  1. Take a single token. Show that if the prediction in (17.9.6) equals q(x0∣xt)q(\mathbf{x}_0 \mid \mathbf{x}_t), the reverse model is the true reverse transition q(xt−1∣xt)q(\mathbf{x}_{t-1} \mid \mathbf{x}_t), for every kernel.
  2. Show that under the absorbing kernel the weight q(xt∣x^0)q(\mathbf{x}_t \mid \hat{\mathbf{x}}_0) is the same for every candidate at a masked position, so that the two forms agree.
  1. [code] Time-agnostic predictions. ● This section argued that under the absorbing kernel the best prediction at a masked position does not depend on tt (Ou et al., 2025).

    1. Write the argument as a short proof. Which property of the absorbing forward process does it use? Does the same hold for the uniform kernel?
    2. The masked language model of Section 11.4 masks each token independently with probability 15%. By (a), its exact predictions are those that the sampler needs at mask patterns of that density. For sequences of L=512L = 512 tokens, find the range of masked fractions that such a model sees in training, say within three standard deviations of 15%. What fraction of the steps of a run from the all-mask sequence, with S=512S = 512 equally spaced levels under the linear schedule, shows the network a masked fraction in this range?
    3. MaskedMLP receives the time as an input. Fix the pattern in which the first token is masked and the second is observed, and compute the predictions of pair_model for all 32 values of the second token at t∈{1,16,31}t \in \{1, 16, 31\}, that is, at time inputs t/32t/32. Then compute two kinds of Kullback–Leibler divergence, each averaged over the marginal of the second token: that of the predictions at t=16t = 16 and at t=31t = 31 from those at t=1t = 1, and that of the predictions at each tt from the exact conditionals of table (clamp probabilities at 10−1210^{-12}). What do the sizes of the two kinds say about the use that the trained network makes of its time input?
  2. [code] Floor of an exact network. ● Let a schedule with αˉ0=1\bar{\alpha}_0 = 1 and αˉT=0\bar{\alpha}_T = 0 have the increments Δt=αˉt−1−αˉt\Delta_t = \bar{\alpha}_{t-1} - \bar{\alpha}_t, and consider the two tokens of the quantized mixture.

    1. Show that the bound (17.9.8) of an exact network, averaged over the true table, is
H(X1,X2)+I(X1;X2)∑t=1TΔt2.(17.9.10)H(X^1, X^2) + I(X^1; X^2) \sum_{t=1}^{T} \Delta_t^2. \tag{17.9.10}

Write the term of step tt with the three mask patterns and their probabilities; a telescoping sum of (1−αˉt)2(1 - \bar{\alpha}_t)^2 evaluates the sum over tt. Check that the linear schedule gives H(X1,X2)+I(X1;X2)/TH(X^1, X^2) + I(X^1; X^2)/T.

  1. Evaluate the sum for the schedule αˉt=1−(t/T)2\bar{\alpha}_t = 1 - (t/T)^2 in closed form and at T=32T = 32, and compare the floor with that of the linear schedule. Why does the choice of schedule cease to matter as T→∞T \to \infty?
  2. Write a function with the call signature of MaskedMLP that returns the logarithms of the exact conditionals computed from table, and of the marginals where both tokens are masked (clamp probabilities at 10−1210^{-12}). Pass it to exact_bound with each of the two schedules as alpha_bar.
  3. Train MaskedMLP with masked_loss under the schedule of (b), with the settings used for pair_model, and compare its exact bound with its floor and with the exact bound of pair_model.
  1. The order-agnostic bound. ● Let a network ignore the time, as the exact network does by Exercise 4a, and write ℓ(i,U)=−log⁡pθ(x0i∣x0U)\ell(i, U) = -\log p_{\boldsymbol{\theta}}(\mathbf{x}_0^i \mid \mathbf{x}_0^U) for its loss at position ii when exactly the positions in the set UU are unmasked. The continuous-time limit of the bound in Section 17.9.2.3, written as an integral over the masking probability uu, is then a weighted sum of the losses ℓ(i,U)\ell(i, U) over i∉Ui \notin U. Hoogeboom et al. (2022) and Ou et al. (2025) show that it equals the expected negative log-likelihood of an order-agnostic autoregressive model (Uria et al., 2014),
Eσ[∑k=1L−log⁡pθ(x0σ(k)∣x0σ(1),…,x0σ(k−1))],(17.9.11)\mathbb{E}_{\sigma} \Big[ \sum_{k=1}^{L} -\log p_{\boldsymbol{\theta}}\big(\mathbf{x}_0^{\sigma(k)} \mid \mathbf{x}_0^{\sigma(1)}, \ldots, \mathbf{x}_0^{\sigma(k-1)}\big) \Big], \tag{17.9.11}

where σ\sigma is a uniformly random permutation of the LL positions.

  1. Find the weight of ℓ(i,U)\ell(i, U) in the integral when ∣U∣=L−m|U| = L - m. The Beta integral ∫01um−1(1−u)L−m du=(m−1)! (L−m)!/L!\int_0^1 u^{m-1} (1 - u)^{L-m}\, du = (m-1)!\, (L-m)! / L! evaluates it.
  2. Find the probability that a random order reveals the positions of UU first and position ii next, and conclude that the two expressions agree.
  3. Every order gives the same value for an exact network. Which value is it? Compare with Exercise 5a as T→∞T \to \infty.
  4. Use Jensen's inequality to show that the expression also bounds the negative log-likelihood of the model that draws an order uniformly at random and then samples the tokens in that order.
  1. [extended] A masked diffusion language model. ●● Prabhudesai et al. (2025) report that masked diffusion models make better use of repeated data than autoregressive models. This problem repeats the data on purpose. Use the character-level windows d2l.TimeMachine(batch_size=64, num_steps=128, tokenization='char', num_train=100000, num_val=3000) of Section 8.2, whose 100,000 training windows start at the first 100,000 positions of The Time Machine; 2,000 updates on minibatches of 64 windows of 128 characters then pass over these positions about 160 times.
    1. Train the GPT of Section 11.2 on these windows for 2,000 updates with its recipe, LMOptimizer, and record its training and validation losses every 200 updates. At which update does the validation loss reach its minimum, and what do the two losses do after it?
    2. Build the denoiser as a subclass of d2l.GPT with vocab_size + 1 tokens, the last one the mask, and a forward pass that accepts the time and ignores it, as this section's argument allows. (Hint: to drop the causal mask, override the nested class CausalAttention and call the framework's fused attention without the mask.) Train it with masked_loss and the linear alpha_bar of T=128T = 128 steps for 2,000 updates.
    3. Every 200 updates, estimate its bound in bits per character on the validation windows, with several masks per window. Plot it next to the validation loss of GPT in bits per character. Compare the best value of each curve and the update at which it is reached. Expect the denoiser's bound to stay well above the loss of GPT at every update before GPT begins to overfit: the gap is the cost that the scaling studies measure, not a bug.
    4. Continue training the denoiser to 8,000 updates if its bound still falls at update 2,000. Which model begins to overfit later? How does training on randomly masked windows change what the denoiser can memorize from a window it has seen many times?
    5. Sample windows with S∈{128,32,8}S \in \{128, 32, 8\} steps and compare them with samples of GPT. Where do the few-step samples fail? Relate the failures to Exercise 2c.

Discussions