Diffusion Language Models

Michael BrenndoerferNovember 17, 202645 min read

Learn how masked diffusion language models corrupt text with absorbing masks, bound likelihood, sample in parallel, and evaluate quality and compute.

Language AI HandbookAll chapters
Part 19 of 67Alternative Sequence and Generative Architectures
Chapter 136Diffusion Language Models
Reading the full chapter · 13 sections · 45 min13 sections · 45 min

All 13 sections · 45 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Diffusion Language Models

In a basic left-to-right sampler, each next-token probability is conditioned on the committed prefix. Speculative verification can check several candidates in one target model pass while preserving that factorization. Masked diffusion uses a different conditional. It can infer several missing positions from visible tokens on either side.

The chain rule writes a string’s joint probability as a product of next-token probabilities conditioned on its prefixes. For a string of length LL over a vocabulary of KK tokens, a parameter-shared causal model computes LL categorical factors, one per position. Teacher forcing supplies the observed prefixes, and a causal mask lets one forward pass score all positions during training. Unrestricted conditional tables still have KL−1K^L-1 independent parameters, just like the full joint distribution. Left-to-right sampling commits to the position order chosen by the model.

In the absorbing-mask formulation used here, generation begins with a sequence of [MASK] tokens. At each step the model sees the partial sequence and predicts a distribution over the original token at each masked position. The sampler can reveal several positions together and choose their order. Samplers that allow remasking can also reconsider an earlier reveal.

Several positions can be proposed in a single model call. A TT-round sampler uses fewer sequential calls than a basic LL-call autoregressive sampler when T<LT<L, though each full-sequence call evaluates every position. Visible text on either side of a gap can guide an infill. A sampler that explicitly remasks previous predictions can also revise them. The application and implementation determine how these choices affect quality and elapsed time.

Discrete diffusion has been used for text at character and token resolution. D3PM includes character-level experiments. In LLaDA’s same-data scaling study, the smaller models match in architecture dimensions, while the larger diffusion and autoregressive models have 8.02B and 6.83B total parameters, respectively. The published comparison against an external Llama 3 8B uses different training data. D3PM. LLaDA, §3.1 and Appendix B.2

The trade-offs are real, and you should understand them before proceeding:

  • Likelihood evaluation. The reverse chain defines a normalized distribution. Evaluating its exact likelihood can require summing many latent paths. Training commonly optimizes a variational bound, and benchmark reports should label an exact value, a bound, or an estimate of that bound.
  • Sampling work. This full-sequence implementation evaluates all LL positions in each of TT denoising rounds. Bidirectional computation over changing tokens lacks the unchanged-prefix cache used by ordinary causal decoding.
  • Sampling policy. The schedule and order determine which intermediate inputs the denoiser sees. Confidence ordering or token revision may implement a different sampler from the fixed reverse transitions used to derive the objective.

A likelihood bound and a measured runtime answer different questions. Report the estimator and normalization for likelihood. For speed, measure the complete request under a fixed hardware, precision, sequence-length, and batch protocol. The number of serialized model calls and the positions evaluated per call help explain those measurements.

The worked example distinguishes three quantities: the per-position predictions, the joint posterior they approximate, and the likelihood bounded by the objective. We define the corruption process and training objective, verify the calculation by enumerating a two-token example, then train and sample from a small model.

From Continuous Diffusion to Discrete Tokens

The diffusion recipe in continuous space has three parts. A forward process gradually adds Gaussian noise to a data point x0∈Rdx_0 \in \mathbb{R}^d: q(xt∣xt−1)=N(1−βt xt−1,βtI)q(x_t \mid x_{t-1}) = \mathcal{N}(\sqrt{1-\beta_t}\,x_{t-1}, \beta_t I), where βt∈(0,1)\beta_t \in (0,1) is the per-step noise variance and II is the identity matrix. A network is trained to reverse it, usually by predicting the noise or, equivalently, the clean signal x^0\hat x_0. Sampling starts from pure noise and iteratively denoises.

A finite Gaussian chain with 0<βt<10<\beta_t<1 reduces the signal coefficient at each step. While that coefficient stays positive, q(xt∣x0)q(x_t\mid x_0) still depends on x0x_0. A sufficiently small terminal coefficient motivates using a noise prior. The forward posterior q(xt−1∣xt,x0)q(x_{t-1}\mid x_t,x_0) is Gaussian at intermediate noise steps when conditioned on the clean input. Integrating over the unknown clean input generally gives a mixture. A learned Gaussian reverse transition, as in DDPM, approximates the reverse process using only xtx_t and the step. Ho et al. (2020), §2

Diffusion-LM applies Gaussian diffusion to continuous word-vector representations. The paper demonstrated gradient-based control for selected syntactic and semantic attributes using trained attribute classifiers with a fixed base language model. The gradient steers the denoising trajectory. The results measure the tested controls and models. Li et al. (2022)

The continuous model still needs a map back to discrete words. Diffusion-LM includes a learned word distribution and examines clamping predicted clean representations to word embeddings during sampling. A decoding rule can affect the discrete output even when the continuous denoising trajectory is unchanged.

Discrete diffusion

Replace the Gaussian corruption with a corruption defined directly on the token alphabet. The state is always a well-formed sequence of tokens (possibly including a mask symbol), rounding is unnecessary, and the likelihood is a genuine categorical likelihood over sequences. The forward process becomes a Markov chain over a finite state space, and the model in this chapter uses a product of categorical distributions across positions for each reverse step.

This reframing is the central move. Once the state space is the set of token sequences rather than the set of embedding vectors, every operation is well defined on the object we actually care about. There is no nearest-neighbor projection, no rounding loss, no gap between what the model generates and what it can represent. The price is that the clean Gaussian algebra of the continuous case is replaced by finite-state combinatorics, but, as we will see, the absorbing variant makes that combinatorics almost trivially simple.

Two examples of discrete corruption are uniform replacement and absorbing masking.

Uniform corruption is one option in D3PM (Austin et al., 2021). Its doubly stochastic transition is Qt=(1−βt)I+βt1K11⊤Q_t = (1-\beta_t)I + \beta_t \frac{1}{K}\mathbf{1}\mathbf{1}^\top. With enough noise, visible tokens may be wrong. The reverse transitions must allow a visible token to change into another token.

Absorbing corruption maps a token to a dedicated [MASK] symbol that is outside the clean vocabulary. A masked position stays masked through the remaining forward steps. LLaDA is one example that uses absorbing masks. The reverse process reveals tokens, and the absorbing formulation is the one developed below.

Absorbing noise keeps visible tokens unchanged. This simplifies what each denoising step must predict.

  1. Visible tokens are preserved in forward corruption. Uniform noise can replace a lexical token with another one. Absorbing noise removes the token and records that its value is hidden.
  2. Masked states provide a focused prediction task. D3PM Table 2 reports lower LM1B perplexity with its absorbing kernel than with its uniform kernel at the tested 1,000 steps. That comparison measures the systems and training settings used there. D3PM
  3. The clean-conditioned reverse posterior has small support. If a position is masked and its clean token vv is given, the posterior at the preceding step has support in {m,v}\{m,v\}. The first reverse update back to the clean time must recover vv. A learned reveal distribution spreads mass across the model's candidate lexical tokens when the clean answer is unknown. Uniform corruption can involve a vocabulary-wide KL sum, but its identity-plus-rank-one kernel can be applied without materializing a dense transition matrix. D3PM

BERT selects 15 percent of input positions for prediction and replaces 80 percent of those selected positions with its mask symbol. A masked prediction objective alone does not specify a reverse chain or a sequence likelihood. Here the corruption and reverse transitions define both. BERT, §3.1

The Absorbing-Mask Forward Process

Set up notation. A sequence is x0=(x01,…,x0L)x_0 = (x_0^1, \dots, x_0^L) with x0i∈Vx_0^i \in V for a vocabulary of size KK. The diffusion state space adds one symbol: Vˉ=V∪{m}\bar V = V \cup \{m\}, where mm denotes [MASK]. The model's output distribution will always be over the KK real tokens; it never predicts mm.

Fix a schedule 0=αˉT<⋯<αˉ1<αˉ0=10 = \bar\alpha_T < \dots < \bar\alpha_1 < \bar\alpha_0 = 1. The forward process masks each position independently conditional on the clean sequence:

q(xti=x0i∣x0)=αˉt,q(xti=m∣x0)=1−αˉt.q(x_t^i = x_0^i \mid x_0) = \bar\alpha_t, \qquad q(x_t^i = m \mid x_0) = 1 - \bar\alpha_t.

The quantity αˉt\bar\alpha_t has a direct reading: it is the probability that a given position has survived unmasked after tt steps, which is why it decreases from one to zero as tt grows. The mask rate, the fraction of positions expected to be masked, is 1−αˉt1-\bar\alpha_t. At t=0t=0 nothing is masked; at the terminal step t=Tt=T with αˉT=0\bar\alpha_T = 0 everything is masked.

Write βt\beta_t for the per-step masking probability, so αˉt=∏s=1t(1−βs)\bar\alpha_t = \prod_{s=1}^{t}(1-\beta_s). The terminal step uses βT=1\beta_T=1 to mask every remaining token. The single-position transition matrix is

Qt=(1−βt)I+βt1em⊤,Q_t = (1-\beta_t)I + \beta_t \mathbf{1}e_m^\top,

where:

  • QtQ_t: the single-position transition matrix over Vˉ=V∪{m}\bar V = V \cup \{m\}
  • βt\beta_t: the probability of masking a visible token at step tt
  • II: the identity matrix over Vˉ\bar V
  • 1\mathbf{1}: the all-ones column vector
  • eme_m: the one-hot column vector for the mask symbol mm

From any visible token the chain stays put with probability 1−βt1-\beta_t and jumps to mm with probability βt\beta_t. The mask is absorbing, so the chain stays at mm with probability one. By the chain rule, surviving tt steps means multiplying the per-step survival probabilities conditional on being visible at the start of each step.

Because positions are corrupted independently, the joint conditional factorizes:

q(xt∣x0)=∏i=1Lq(xti∣x0i).q(x_t \mid x_0) = \prod_{i=1}^{L} q(x_t^i \mid x_0^i).

Let S⊆{1,…,L}S\subseteq\{1,\dots,L\} be the set of masked positions in xtx_t. Independent masking gives the probability of that mask set. To give the probability of the entire corrupted state, also require that its visible values match the clean sequence:

q(xt∣x0)=(1−αˉt)∣S∣ αˉtL−∣S∣⋅1 ⁣[xtSˉ=x0Sˉ],q(x_t \mid x_0) = (1-\bar\alpha_t)^{|S|}\,\bar\alpha_t^{L-|S|}\cdot\mathbb{1}\!\left[x_t^{\bar S} = x_0^{\bar S}\right],

where:

  • SS: the set of masked positions at time tt
  • ∣S∣|S|: the number of masked positions
  • Sˉ\bar S: the complement of SS (the visible positions)
  • xtSˉx_t^{\bar S}: the sub-vector of state xtx_t at the visible positions
  • 1[⋅]\mathbb{1}[\cdot]: the indicator function, one when the argument holds and zero otherwise

Only patterns consistent with the visible positions get probability mass, and among those, the probability depends only on the count of masks, not on which positions they are or what values they hold. The indicator enforces consistency: if the state claims a visible position holds a particular token, the clean sequence had better agree, or the pattern is impossible. The factor (1−αˉt)∣S∣αˉtL−∣S∣(1-\bar\alpha_t)^{|S|}\bar\alpha_t^{L-|S|} is the probability of that particular mask pattern under independent masking, and it depends on the pattern only through its size. That symmetry is what makes the exact computations below come out in closed form.

The schedule chooses how quickly survival drops between its endpoints. Let u=k/Tu=k/T be the normalized forward step.

  • Linear mask rate. αˉk=1−u\bar\alpha_k=1-u, so the mask rate is uu. The worked examples use this choice.
  • Cosine-squared survival. Set g(u)=cos⁡2 ⁣(π2u+s1+s)g(u)=\cos^2\!\left(\frac{\pi}{2}\frac{u+s}{1+s}\right) with s≥0s\ge 0, and use αˉk=g(u)/g(0)\bar\alpha_k=g(u)/g(0). This adapts the normalized image-diffusion schedule with an exact all-mask endpoint for this discrete process. Nichol and Dhariwal (2021), §3.2
  • Exponential survival with terminal masking. For k<Tk<T, use αˉk=exp⁡[−σ(u)]\bar\alpha_k=\exp[-\sigma(u)], where σ(0)=0\sigma(0)=0 and σ\sigma increases. If σ\sigma remains finite at the endpoint, set αˉT=0\bar\alpha_T=0 with a final full-mask step.

Changing the schedule changes the weights and the intermediate states in a finite-step loss. In continuous time, a differentiable, strictly increasing mask rate from zero to one can replace time as the integration coordinate. The expected objective is invariant under this change when predictions depend only on the partial string, or when any time-dependent predictor is reparameterized to give the same predictions at matching mask rates. Finite grids, sampling variance, and decoding can still depend on the schedule.

What the Network Must Predict

The derivation uses three distinct distributions. The first is the per-position conditional given only that a position is masked. The second is the joint posterior given the entire masked state. The third consists of the per-position marginals predicted by the network.

The token conditional is uninformative

Suppose you observe only that position ii is masked at a step with positive mask probability. Bayes’ rule gives the original token distribution at that position:

q(x0i=v∣xti=m)=q(xti=m∣x0i=v) q(x0i=v)∑v′q(xti=m∣x0i=v′) q(x0i=v′).q(x_0^i = v \mid x_t^i = m) = \frac{q(x_t^i = m \mid x_0^i = v)\,q(x_0^i = v)}{\sum_{v'} q(x_t^i = m\mid x_0^i = v')\,q(x_0^i = v')}.

where:

  • vv, v′v': candidate real tokens in the vocabulary VV
  • q(x0i=v)q(x_0^i = v): the prior probability (unigram marginal) of token vv at position ii
  • q(xti=m∣x0i=v)q(x_t^i = m \mid x_0^i = v): the probability position ii is masked at time tt given the true token vv

The likelihood term q(xti=m∣x0i=v)q(x_t^i = m \mid x_0^i = v) equals 1−αˉt1-\bar\alpha_t for every vv, because masking is independent of content. It cancels:

q(x0i=v∣xti=m)=q(x0i=v).q(x_0^i = v \mid x_t^i = m) = q(x_0^i = v).

The mask at one position alone gives the position’s marginal token distribution. In the full corrupted sequence, the visible tokens provide information about the missing values. The set of masks tells the model which information is missing.

The joint posterior carries the information

The useful object is the joint posterior over the entire clean sequence given the whole masked state xtx_t, including which positions are visible and what they contain:

q(x0∣xt)=q(xt∣x0) pdata(x0)∑x0′q(xt∣x0′) pdata(x0′).q(x_0 \mid x_t) = \frac{q(x_t \mid x_0)\,p_{\text{data}}(x_0)}{\sum_{x_0'} q(x_t \mid x_0')\,p_{\text{data}}(x_0')}.

The forward likelihood is zero for a clean candidate inconsistent with any visible position. For every consistent x0x_0, the factor q(xt∣x0)=(1−αˉt)∣S∣αˉtL−∣S∣q(x_t\mid x_0)=(1-\bar\alpha_t)^{|S|}\bar\alpha_t^{L-|S|} is common and cancels whenever the observed partial state has positive mass. Each surviving candidate still contributes its own prior probability:

q(x0∣xt)∝pdata(x0)⋅1 ⁣[x0Sˉ=xtSˉ].q(x_0 \mid x_t) \propto p_{\text{data}}(x_0)\cdot\mathbb{1}\!\left[x_0^{\bar S} = x_t^{\bar S}\right].

The joint posterior is just the data distribution restricted to the strings consistent with the visible positions, renormalized. In the worked example below, this is an explicit finite table we can compute exactly. The formula is worth examining, because it says that the masked state acts as a hard constraint: it rules out every string that disagrees with what is visible, and reweights the survivors by their prior probability. All the context in the visible positions enters through that indicator, and none of it enters through the mask rate.

The posterior has at most K∣S∣K^{|S|} nonzero entries. With 50,000 lexical tokens and ten masked positions, an exhaustive table over the candidates has 500001050000^{10} rows. The model below represents one categorical distribution per masked position.

The model is a mean-field approximation to the joint

A network outputs one categorical distribution per position. On a possible partial state, use the product of its masked-position predictions as an approximation to the clean joint posterior:

q(x0∣xt)≈1 ⁣[x0Sˉ=xtSˉ]∏i∈Sfθi(x0i∣xt).q(x_0 \mid x_t) \approx \mathbb{1}\!\left[x_0^{\bar S}=x_t^{\bar S}\right]\prod_{i\in S} f_\theta^i(x_0^i\mid x_t).

The product on the right defines a normalized distribution over clean completions. The visible tokens are fixed. With the population masked-token loss and a model that can represent the true marginals, each predicted factor can match its context-conditioned marginal. The product still represents missing positions independently within that update.

Mean-field gap

Positions revealed in the same step are sampled independently under this reverse transition. Even exact marginals can produce a jointly inconsistent combination, such as a singular subject with a plural verb. At fixed length under a finer linear schedule, simultaneous reveals become less likely.

Revealing one position per step removes the need to approximate dependencies within a reveal group. If the decoder uses exact data conditionals and a fixed or independently sampled reveal order, the chain rule recovers the data distribution. Learned prediction errors and a reveal policy that selects among sampled token values can still change the output law.

The reverse step

Now we can write the reverse transition. Consider a position masked at time tt. Given the true token x0i=vx_0^i = v, what is the distribution of the previous state? Two cases, both computed by Bayes:

q(xt−1i=v∣xti=m,x0i=v)=βtαˉt−11−αˉt,q(xt−1i=m∣xti=m,x0i=v)=1−αˉt−11−αˉt.q(x_{t-1}^i = v \mid x_t^i = m, x_0^i = v) = \frac{\beta_t \bar\alpha_{t-1}}{1-\bar\alpha_t}, \qquad q(x_{t-1}^i = m \mid x_t^i = m, x_0^i = v) = \frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}.

The two sum to one, as they must: βtαˉt−1+1−αˉt−1=1−αˉt−1(1−βt)=1−αˉt\beta_t\bar\alpha_{t-1} + 1 - \bar\alpha_{t-1} = 1 - \bar\alpha_{t-1}(1-\beta_t) = 1-\bar\alpha_t. The first expression is the probability that the position was visible at t−1t-1 and got masked at step tt, divided by the probability it is masked at tt; the second is the probability it was already masked at t−1t-1, again normalized. The first numerator uses the masking probability conditional on survival to the previous step. Define

ρt=1−αˉt−11−αˉt,rt=1−ρt=αˉt−1−αˉt1−αˉt.\rho_t = \frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}, \qquad r_t = 1 - \rho_t = \frac{\bar\alpha_{t-1}-\bar\alpha_t}{1-\bar\alpha_t}.

Here ρt\rho_t is the probability of staying masked, and rtr_t is the probability of being revealed at this step. Replacing the unknown x0ix_0^i with the model's prediction gives the generative reverse step for masked positions:

pθ(xt−1i=v∣xt)=rt fθi(v∣xt)+ρt 1[v=m].p_\theta(x_{t-1}^i = v \mid x_t) = r_t\, f_\theta^i(v\mid x_t) + \rho_t\,\mathbb{1}[v = m].

Positions that are already visible are copied unchanged with probability one. This is a proper distribution over Vˉ\bar V: the mask mass plus the token mass sums to 11. The model predicts fθi(v∣xt)f_\theta^i(v\mid x_t) on the KK lexical tokens. Extend it by setting fθi(m∣xt)=0f_\theta^i(m\mid x_t)=0 in the displayed equation. The term with ρt\rho_t supplies the remaining mass on mm. Notice the structure: with probability rtr_t the position is revealed and its value is drawn from the model's prediction, and with probability ρt\rho_t it stays masked. The unknown clean token has been integrated out and replaced by the model's belief about it, which is the only place the network enters the reverse chain.

Two structural observations follow immediately, and both matter in practice.

At step tt, each of the nmaskedn_{\text{masked}} masked positions independently reveals with probability rtr_t. The number revealed is therefore Binomial(nmasked,rt)\mathrm{Binomial}(n_{\text{masked}},r_t). In the exact reverse data process, the reveal times are independent of the final lexical sequence because the forward masks were drawn independently of that sequence. The learned product sampler still draws reveal decisions without consulting lexical predictions. Which positions reveal together can affect its final lexical distribution, as the two-token example shows.

The binomial spread is worth examining directly, because it makes the mean-field risk concrete: a step can reveal several positions at once, and those positions are then sampled independently.

PythonIn [2]
CollapseExpand
import math

import numpy as np

reveal_n = 6
reveal_r = 1 / 3
reveal_counts = np.arange(reveal_n + 1)
reveal_pmf = np.array(
    [
        math.comb(reveal_n, int(x))
        * reveal_r ** int(x)
        * (1 - reveal_r) ** (reveal_n - int(x))
        for x in reveal_counts
    ]
)
VisualizationOut [4]
CollapseExpand
Bar chart shows binomial probabilities for the number of positions revealed in one step.
Binomial distribution of the number of masked positions revealed at one reverse step, with six masked positions and a reveal probability of one third. The distribution assigns positive probability to two or more reveals.

Every position is revealed exactly once. Summing the unconditional reveal probability over all steps gives ∑t(αˉt−1−αˉt)=αˉ0−αˉT=1\sum_t (\bar\alpha_{t-1}-\bar\alpha_t) = \bar\alpha_0 - \bar\alpha_T = 1. Nothing is revealed twice, and nothing is left over. The telescoping sum is a direct consequence of the schedule running from αˉ0=1\bar\alpha_0 = 1 to αˉT=0\bar\alpha_T = 0, and it is what makes the reverse chain a valid generative process rather than merely a sequence of partial repairs.

With the linear schedule αˉk=1−k/T\bar\alpha_k = 1 - k/T and TT steps, these quantities collapse to something you can compute in your head: at step kk (counting k=T,T−1,…,1k = T, T-1, \dots, 1 in the reverse direction) the reveal probability is exactly 1/k1/k. At the last step everything remaining is revealed at once. To see the 1/k1/k, substitute αˉk−1=1−(k−1)/T\bar\alpha_{k-1} = 1-(k-1)/T and αˉk=1−k/T\bar\alpha_k = 1-k/T into the definition of rtr_t: the numerator is 1/T1/T and the denominator is k/Tk/T, so the ratio is 1/k1/k. This is the schedule used throughout the worked example and the implementation, and it is why the loss weight in those sections takes the simple form it does.

The Training Objective

The reveal probability also determines the weight on the denoising loss. To connect the two, start from the model’s likelihood over reverse paths.

The bound

A clean sequence x0x_0 can be reached by many reverse paths. The model probability pθ(x0)p_\theta(x_0) sums their probabilities. We can bound that probability by using the forward corruption chain as the distribution over latent paths. Write q(x1:T∣x0)q(x_{1:T}\mid x_0) for its path probability and pθ(x0:T)p_\theta(x_{0:T}) for the joint probability defined by the terminal prior and learned reverse transitions. Jensen's inequality gives

log⁡pθ(x0)≥Eq(x1:T∣x0)[log⁡pθ(x0:T)q(x1:T∣x0)]=ELBO⁡(x0).\log p_\theta(x_0) \ge \mathbb E_{q(x_{1:T}\mid x_0)} \left[\log\frac{p_\theta(x_{0:T})}{q(x_{1:T}\mid x_0)}\right] =\operatorname{ELBO}(x_0).

The likelihood can also include paths outside the forward chain's support. The inequality still holds because the ratio expectation sums only over paths in the forward support. Factorizing those paths in reverse order separates the negative bound into reconstruction, intermediate transitions and terminal prior mismatch:

−ELBO⁡(x0)=−Eqlog⁡pθ(x0∣x1)+∑k=2TEqKL⁡ ⁣(q(xk−1∣xk,x0) ∥ pθ(xk−1∣xk))+KL⁡ ⁣(q(xT∣x0) ∥ p(xT)).-\operatorname{ELBO}(x_0) = -\mathbb E_q\log p_\theta(x_0\mid x_1) +\sum_{k=2}^T \mathbb E_q\operatorname{KL}\!\left( q(x_{k-1}\mid x_k,x_0)\,\|\,p_\theta(x_{k-1}\mid x_k) \right) +\operatorname{KL}\!\left(q(x_T\mid x_0)\,\|\,p(x_T)\right).

Both distributions in the last term are point masses on the all-mask state when αˉT=0\bar\alpha_T=0 and we start the reverse model there. The term vanishes. If some visible tokens can survive forward corruption at TT, an all-mask prior gives those states zero probability and makes the terminal KL infinite. A different terminal prior requires carrying its KL term through the derivation.

A visible position contributes zero to the intermediate KL because both transitions copy it. For a masked position each distribution assigns the same mass 1−rk1-r_k to the mask. The true transition assigns the remaining mass rkr_k to the original token x0ix_0^i. The model assigns mass rkfθi(x0i∣xk)r_k f_\theta^i(x_0^i\mid x_k) to that token. The matching mask terms cancel, leaving

KL⁡i=rklog⁡rkrkfθi(x0i∣xk)=−rklog⁡fθi(x0i∣xk).\operatorname{KL}_i =r_k\log\frac{r_k}{r_k f_\theta^i(x_0^i\mid x_k)} =-r_k\log f_\theta^i(x_0^i\mid x_k).

At k=1k=1 the model reveals every remaining mask. The reconstruction term is the same sum of negative log probabilities with r1=1r_1=1. With independent corruption conditioned on x0x_0 and product reverse transitions, the result is the masked reconstruction loss

LNELBO(x0)=∑k=1Trk Eq(xk∣x0)[∑i: xki=m−log⁡fθi(x0i∣xk)].\mathcal L_{\mathrm{NELBO}}(x_0) = \sum_{k=1}^T r_k\, \mathbb E_{q(x_k\mid x_0)} \left[\sum_{i:\,x_k^i=m} -\log f_\theta^i(x_0^i\mid x_k)\right].

With the linear schedule, rk=1/kr_k=1/k. Training averages this bound over sequences drawn from the training distribution. Sahoo et al. (2024) use the carry-over and zero-mask-probability properties to simplify this objective for masked diffusion.

The continuous-time limit

Taking T→∞T \to \infty turns the sum into an integral with a 1/t1/t weight. Use Δ=1/T\Delta = 1/T, tk=k/Tt_k = k/T, and 1/tk=T/k1/t_k = T/k:

∑k=1T1kE[∑i∈Mkℓi]=∑k=1TΔ⋅1tkE[∑i∈Mkℓi]  ⟶  ∫011t E[∑i∈Mtℓi]dt,\sum_{k=1}^{T}\frac{1}{k}\mathbb{E}\left[\sum_{i\in M_k}\ell_i\right] = \sum_{k=1}^{T}\Delta\cdot\frac{1}{t_k}\mathbb{E}\left[\sum_{i\in M_k}\ell_i\right] \;\longrightarrow\; \int_0^1 \frac{1}{t}\,\mathbb{E}\left[\sum_{i\in M_t}\ell_i\right]dt,

where ℓi=−log⁡fθi(x0i∣xt)\ell_i = -\log f_\theta^i(x_0^i\mid x_t). In expectation form, with tt drawn uniformly:

  L∞=Et∼U[0,1]  Eq(xt∣x0)[1t∑i: xti=m(−log⁡fθi(x0i∣xt))]  \boxed{\;\mathcal{L}_\infty = \mathbb{E}_{t\sim U[0,1]}\;\mathbb{E}_{q(x_t\mid x_0)}\left[\frac{1}{t}\sum_{i:\,x_t^i = m}\left(-\log f_\theta^i(x_0^i\mid x_t)\right)\right]\;}

The evaluation points tk=k/Tt_k=k/T are right endpoints, and Δ/tk=1/k\Delta/t_k=1/k. A sufficient condition for convergence is that the mean loss given a position is masked extends continuously to the endpoints for every position. Drawing tt uniformly in (0,1)(0,1) and then sampling the mask gives an unbiased estimate of the integral when the expected weighted loss is integrable.

For t>0t>0, the expected sum of masked losses divided by tt equals ∑iE[ℓi∣xti=m]\sum_i\mathbb E[\ell_i\mid x_t^i=m]. Each mask indicator contributes a factor of tt in its expectation, which the denominator cancels. The conditional losses still depend on the visible context.

BERT selects prediction positions at random and applies its own corruption mixture to them. A masked-token training loss by itself gives no reverse transition rule or normalized sequence likelihood. Here the forward chain and the model's normalized reverse transitions supply both. In the population model, a content-independent mask schedule makes time redundant once a possible partially visible state is given. An implementation can still supply a time embedding as a modeling choice.

Estimating the bound

To estimate the continuous-time objective, sample tt uniformly from (0,1)(0,1) and draw the mask at that rate. Average the weighted masked loss over draws. At small tt, most samples have few masks, while a rare mask can receive a large weight. The estimator can have a finite mean and infinite variance. For one position whose masked loss is a constant c>0c>0, the contribution is c/tc/t with probability tt and zero otherwise. Its conditional mean is cc, while its conditional second moment is c2/tc^2/t. Integrating that second moment over uniform tt diverges. A stratum that includes the zero endpoint can still have this problem. Clipping tt to a positive threshold changes the sampling law and generally changes the estimand unless the procedure corrects for it.

For a finite TT, a direct Monte Carlo estimate samples kk uniformly from {1,…,T}\{1,\ldots,T\} and weights the masked cross-entropy by TrkT r_k. On short sequences one can instead enumerate all 2L2^L masks at each step. The code later in this chapter compares these two estimates at the same TT.

Worked Example: An Exact Bound on a Two-Token Language

The gap between data surprisal, model likelihood, and the model's bound is visible with just two positions. Take V={a,b}V=\{a,b\} and the following data distribution.

Data distribution over the four two-token strings.
StringData mass
aaaa0.50.5
abab0.30.3
baba0.20.2
bbbb00

Use the exact data conditional as each position prediction, then draw positions independently whenever they are revealed in the same step. This specifies the reverse model. For T=2T=2 the reveal probability is 1/21/2 at the first reverse step and 11 at the last. Each position independently has a 1/21/2 chance to reveal at each of these two steps. Thus the probability of a simultaneous reveal is 1/21/2.

  • If the two positions reveal together, the prediction at each is its unconditional marginal. The first position is aa with probability 0.80.8 and the second is aa with probability 0.70.7. The model assigns 0.560.56 to aaaa on these paths.
  • If they reveal separately, the second prediction sees the first token. In either order the chain rule gives the data probability 0.50.5 for aaaa.

The model's probability of aaaa is the average of these two numbers, 0.530.53. Its NLL is −log⁡0.53≈0.63488-\log 0.53 \approx 0.63488. The bound averages negative logs along the paths, yielding [−log⁡0.56−log⁡0.5]/2≈0.63648[-\log 0.56-\log 0.5]/2\approx 0.63648. Data surprisal is −log⁡0.5≈0.69315-\log 0.5\approx 0.69315. For this particular sequence the model has assigned more probability than the data distribution.

Under a linear TT-step schedule each position has a uniform reveal step from 11 through TT, so the probability of collision is 1/T1/T. The calculation extends directly. For bbbb, the model assigns mass (0.2)(0.3)/T=0.06/T(0.2)(0.3)/T=0.06/T. This string has zero data probability.

Let's compute the model NLL and the bound from these paths, then cross-check the bound against the masked loss formula. With aaaa as target, the negative log likelihood for simultaneous paths and both one-at-a-time orders remains finite.

PythonIn [5]
CollapseExpand
import itertools
import math

import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F

torch.set_num_threads(1)
torch.manual_seed(0)
np.random.seed(0)

# The toy language: four possible two-token strings, one of them impossible.
STRINGS = [("a", "a"), ("a", "b"), ("b", "a"), ("b", "b")]
PRIOR = np.array([0.5, 0.3, 0.2, 0.0])
L_TOY = 2
X0 = ("a", "a")  # the sequence whose likelihood we will bound

The example evaluates one position-factorized reverse model. It predicts each missing token from the exact data marginal conditional on the visible tokens. With both positions masked, those predictions reduce to the prior marginals. When both positions reveal together, independent draws from those marginals can miss their dependence.

PythonIn [6]
CollapseExpand
def population_marginal(mask, position, token, visible=X0):
    compatible = np.array(
        [
            all(mask[j] or state[j] == visible[j] for j in range(L_TOY))
            for state in STRINGS
        ]
    )
    chosen = np.array([state[position] == token for state in STRINGS])
    support = PRIOR[compatible].sum()
    if support == 0:
        raise ValueError("Visible values have zero probability in the toy data")
    return PRIOR[compatible & chosen].sum() / support


def exact_nelbo(T):
    total = 0.0
    for k in range(1, T + 1):
        t = k / T
        for mask in itertools.product([False, True], repeat=L_TOY):
            count = sum(mask)
            pattern_mass = t**count * (1 - t) ** (L_TOY - count)
            if pattern_mass == 0 or count == 0:
                continue
            loss = sum(
                -math.log(population_marginal(mask, i, X0[i]))
                for i in range(L_TOY)
                if mask[i]
            )
            total += pattern_mass * loss / k
    return total

We can compute the model likelihood without sampling. Enumerate both reveal steps for each position, multiply the assigned token probabilities along each path and average the products. The corresponding path bound averages their negative logs.

PythonIn [7]
CollapseExpand
def path_scores(T):
    joint_prob = PRIOR[STRINGS.index(X0)]
    independent_prob = math.prod(
        population_marginal((True, True), i, token)
        for i, token in enumerate(X0)
    )
    path_probabilities = np.array(
        [
            independent_prob if first == second else joint_prob
            for first, second in itertools.product(range(T), repeat=2)
        ]
    )
    return -math.log(path_probabilities.mean()), -np.log(
        path_probabilities
    ).mean()


toy_steps = [1, 2, 4, 8, 16, 32, 64]
sweep = pd.DataFrame(
    [
        {"steps": T, "NLL": path_scores(T)[0], "NELBO": exact_nelbo(T)}
        for T in toy_steps
    ]
)
for row in sweep.itertuples():
    assert math.isclose(row.NELBO, path_scores(row.steps)[1], abs_tol=1e-10)
    assert row.NLL <= row.NELBO + 1e-12
data_surprisal = -math.log(PRIOR[STRINGS.index(X0)])
ConsoleOut [8]
CollapseExpand
Data surprisal of ('a', 'a'): 0.69315 nats
 steps     NLL   NELBO
     1 0.57982 0.57982
     2 0.63488 0.63648
     4 0.66359 0.66482
     8 0.67826 0.67898
    16 0.68568 0.68606
    32 0.68940 0.68961
    64 0.69127 0.69138
VisualizationOut [9]
CollapseExpand
The exact model NLL and dashed negative ELBO curves approach the dotted data surprisal reference from below.
For the string aa, exact model NLL and its negative ELBO approach the data surprisal as simultaneous reveals become less frequent.

At a single step there is only one reveal grouping and the two numbers for the model coincide. At intermediate step counts, paths can assign different probabilities to the same string. The negative ELBO is then above its exact model NLL. Both approach the data surprisal for this string as the chance of a collision goes to zero. The bound gap compares two quantities for the same model. The distance from the data surprisal is a separate comparison.

Sampling

Start each position at mm. At step kk, evaluate the denoiser on the current state, then draw each reveal decision with probability 1/k1/k for the linear schedule. For each selected position draw a clean token from its predicted categorical distribution. Copy the other positions through unchanged.

Schedules and the quality/latency dial

Changing TT changes both the number of model calls and the distribution of reveal groups. At T=LT=L, independent reveal decisions still allow some steps to reveal several tokens and others to reveal none. Alternatively, a decoder can explicitly reveal one position per call and require exactly LL calls. In that case every next draw conditions on the previously revealed tokens.

Heuristic sampling: where theory stops

Some decoders replace random Bernoulli selection with a fixed count such as ⌈n/k⌉\lceil n/k\rceil, where nn is the number of remaining masks. They can choose those positions at random or rank candidate tokens by the denoiser's confidence. LLaDA describes a confidence heuristic in which the lowest-confidence predictions at still-masked positions are kept masked. Tokens committed at earlier steps stay visible. A different revision algorithm may explicitly mask previous commitments again. Both selecting by confidence and revising positions change the sampler, so the likelihood bound from the derived random-reveal model does not automatically describe their output distributions.

Self-conditioning

A denoiser may also receive its own earlier clean estimate as input. This is called self-conditioning. It changes what the prediction depends on, beyond the current partial string and the time. To implement it, provide the same kind of signal during training that later steps will have at generation time. Training and inference implementations can have different costs if inference reuses an estimate that it has already computed.

Compute, latency, and the missing cache

Count only generated positions and hold the model width and prompt length fixed. Cached autoregressive decoding adds one new position per generation step. Naive full-sequence denoising recomputes all LL positions at each of its TT steps. The total counts are O(L)O(L) and O(TL)O(TL) respectively, before accounting for attention. With dense attention over LL positions, total attention work across the TT denoising rounds scales as O(TL2)O(TL^2) for fixed width.

The ratio below counts evaluated positions relative to the cached autoregressive baseline. Attention operations and elapsed time require separate accounting.

PythonIn [10]
CollapseExpand
import numpy as np

step_budgets = np.array([4, 8, 16, 32, 64])
relative_work = step_budgets.astype(float)
budget_labels = [str(int(t)) for t in step_budgets]
budget_xpos = np.arange(len(step_budgets))
VisualizationOut [11]
CollapseExpand
Bars show the ratio of generated-position evaluations for full-sequence denoising relative to cached autoregressive decoding.
At the same generated length, T full-sequence denoising rounds evaluate T times as many generated positions as the one-visit-per-position cached autoregressive baseline. The ratio counts position evaluations.

The naive denoiser may need fewer sequential network calls when T<LT<L. Timing depends on the cost of each call, memory movement, batch size, precision, hardware and implementation. Position counts alone give no wall-clock prediction. In a fully bidirectional transformer, even a visibly unchanged position can have a new hidden representation after a mask elsewhere is filled, which prevents ordinary causal KV caching across rounds. Block diffusion defines a different attention structure, allowing completed blocks to be cached while denoising the next block.

Controllability

This is where diffusion language models differ rather than merely compete.

Keep known tokens visible and mask the positions to fill. The copy-through rule preserves those fixed tokens. An arbitrary visible assignment can have zero support under the data distribution. The clamped procedure induces its own completion distribution, which can differ from conditioning the original generative joint.

In the two-token model with T=2T=2, the two positions reveal together half the time. The unconditional sampler assigns bbbb mass 12(0.2)(0.3)=0.03\frac12(0.2)(0.3)=0.03 and assigns first-token bb mass 0.20.2. Conditioning that model on first-token bb gives second-token bb probability 0.03/0.2=0.150.03/0.2=0.15. If the first bb is fixed before denoising, every prediction for the remaining position instead uses the data conditional given that visible bb. The toy data put all that conditional mass on baba, so the clamped sampler assigns the second bb probability zero.

Left-to-right sequence models also define conditional distributions given a suffix when the conditioning event has positive probability. Evaluating or sampling that conditional efficiently can require search, rearranged training examples, or another generation procedure. A fill-in-the-middle training setup provides one such interface.

Soft constraints via guidance. To steer toward a control variable cc, train predictions with and without the control input and combine their logits. This applies the classifier-free guidance idea to categorical predictions. Ho and Salimans (2022)

ℓγ(xt,c)=(1+γ) ℓθ(xt,c)−γ ℓθ(xt,∅),\ell_\gamma(x_t, c) = (1+\gamma)\,\ell_\theta(x_t, c) - \gamma\,\ell_\theta(x_t, \varnothing),

Here ∅\varnothing denotes the unconditional case and γ\gamma sets the strength of the extrapolation. A softmax over the adjusted logits supplies the next lexical distribution. The relative conditional and unconditional scores determine which tokens gain probability. Increasing γ\gamma does not guarantee higher adherence or lower entropy. Diffusion-LM used a different guidance method, applying gradients from an external attribute classifier to the continuous latent state.

Hard constraints need an enforcement rule. Return only completions that pass the test. Rejection sampling can produce an accepted completion when valid outputs have positive mass. Repair can propose edits for another check. A left-to-right decoder can also enforce constraints that admit a suitable next-token test, such as a prefix restriction derived from a JSON grammar.

Likelihood Evaluation

The posterior over model paths given a completed sequence is pθ(x1:T∣x0)p_\theta(x_{1:T}\mid x_0). When the sequence log likelihood and the ELBO are both finite, subtracting the log-ratio expression for the ELBO from the log likelihood yields

log⁡pθ(x0)−ELBO⁡(x0)=KL⁡ ⁣(q(x1:T∣x0) ∥ pθ(x1:T∣x0)).\log p_\theta(x_0)-\operatorname{ELBO}(x_0) = \operatorname{KL}\!\left(q(x_{1:T}\mid x_0) \,\|\,p_\theta(x_{1:T}\mid x_0)\right).

Since KL divergence is nonnegative, −log⁡pθ(x0)≤LNELBO(x0)-\log p_\theta(x_0)\leq\mathcal L_{\mathrm{NELBO}}(x_0). For a fixed dataset, divide the sum of either quantity by its total number of scored tokens and exponentiate to obtain exact perplexity or an upper bound, respectively. A Monte Carlo estimate of the bound can fall below its true value due to sampling error. Quote the score form, mask schedule, time sampling method and uncertainty when reporting it.

Per-token scores need common tokenization, preprocessing, document boundaries and scored positions. A common byte denominator can help compare scores across tokenizers if the models assign probability to the same underlying text under compatible sequence and boundary conventions. In every case report whether the value is an exact NLL or a bound. An upper bound above a comparison model's exact NLL leaves their ordering unresolved. An established upper bound below a comparison model's larger exact NLL establishes which has the smaller NLL for that evaluation.

The any-order equivalence

For continuous absorbing-mask diffusion with full terminal masking and a time-independent prediction rule, the training objective equals the average negative log likelihood across uniform one-position-at-a-time reveal orders. Ou et al. give this equivalence in their analysis of reparameterized absorbing diffusion.

We can check it by fixing a visible set CC, with c=∣C∣c=|C|, and specifying the next position j∉Cj\notin C. Under independent mask probability tt, the mask pattern has probability (1−t)ctL−c(1-t)^c t^{L-c}. Multiplying by the loss weight 1/t1/t and integrating over tt gives c!(L−c−1)!/L!c!(L-c-1)!/L!. Among the L!L! possible reveal permutations, this is the fraction with exactly the positions in CC first and jj next. Because the prediction for fixed CC and its visible tokens has no explicit time dependence, it can be taken outside that integral.

For each fixed order, multiplying the conditional token probabilities gives a normalized sequence model. Averaging a log loss over orderings and taking the log of the probability under their mixture are different operations. Jensen's inequality places the mixture's NLL below or at the average per-order NLL. The finite-step sampler earlier also permits simultaneous reveals, so this single-position derivation does not describe its likelihood.

Implementation: A Small Masked Diffusion Language Model

We now build a complete, if tiny, masked diffusion language model. The corpus is a synthetic grammar with a constraint in it, so that sample quality is measurable rather than a matter of taste.

Sentences have the form DET NOUN VERB DET NOUN ., with six tokens. Determiners come from {the, a} and nouns from {cat, cats, dog, dogs}. The verb agrees in number with the first noun. There are 2×4×1×2×4=642 \times 4 \times 1 \times 2 \times 4 = 64 valid strings among the 128 strings in the positional template. Uniformly choosing the verb within the valid template gives a 50 percent reference rate. The reported validity checks both the template and agreement. A sampler that repeats one valid sentence could score 100 percent, so use separate tests to measure whether it learned a dependency that generalizes.

PythonIn [13]
CollapseExpand
DETS = ["the", "a"]
NOUNS = ["cat", "cats", "dog", "dogs"]
VERB_OF = {"cat": "chases", "dog": "chases", "cats": "chase", "dogs": "chase"}

VOCAB = DETS + NOUNS + ["chases", "chase", "."] + ["[MASK]"]
K = len(VOCAB) - 1  # number of real tokens; the model never predicts [MASK]
MASK_ID = K
SEQ_LEN = 6
stoi = {w: i for i, w in enumerate(VOCAB)}


def make_corpus():
    rows = []
    for d1 in DETS:
        for n1 in NOUNS:
            for d2 in DETS:
                for n2 in NOUNS:
                    rows.append([d1, n1, VERB_OF[n1], d2, n2, "."])
    return torch.tensor([[stoi[w] for w in r] for r in rows])


corpus = make_corpus()
ConsoleOut [14]
CollapseExpand
vocabulary size (real tokens): 9
mask symbol index: 9
corpus size: 64 sentences of length 6
example: the cat chases the cat .

The denoiser is a bidirectional Transformer encoder with a time embedding broadcast to all positions. Its output head has one logit per lexical token. The product structure of the forward and model reverse transitions yields the sum over positions in the KL. Supplying the mask mass from the schedule leaves the revealed lexical distribution as the network's prediction.

PythonIn [15]
CollapseExpand
class Denoiser(nn.Module):
    def __init__(self, n_tokens, seq_len, d=64, heads=4, layers=2, ff=128):
        super().__init__()
        self.tok = nn.Embedding(n_tokens + 1, d)  # +1 for [MASK]
        self.pos = nn.Embedding(seq_len, d)
        self.time = nn.Sequential(nn.Linear(1, d), nn.SiLU(), nn.Linear(d, d))
        self.blocks = nn.TransformerEncoder(
            nn.TransformerEncoderLayer(
                d, heads, ff, dropout=0.0, batch_first=True, norm_first=True
            ),
            layers,
        )
        self.norm = nn.LayerNorm(d)
        self.head = nn.Linear(d, n_tokens)

    def forward(self, x, t):
        h = (
            self.tok(x)
            + self.pos(torch.arange(x.shape[1]))
            + self.time(t[:, None])[:, None, :]
        )
        return self.head(self.norm(self.blocks(h)))

Train on the uniform six-position grammar with T=6T=6. Draw kk uniformly from the six steps per sequence and mask each position with probability k/Tk/T. Multiplying the masked cross-entropy by T/kT/k makes the stochastic loss unbiased for the sum over steps. The demonstration trains and evaluates on the same finite support to test the model mechanics.

PythonIn [16]
CollapseExpand
TRAIN_STEPS = 6


def diffusion_loss(model, x0):
    k = torch.randint(1, TRAIN_STEPS + 1, (x0.shape[0],))
    t = k / TRAIN_STEPS
    mask = torch.rand(x0.shape) < t[:, None]
    xt = torch.where(mask, torch.full_like(x0, MASK_ID), x0)
    logp = F.log_softmax(model(xt, t), dim=-1)
    true_logp = logp.gather(-1, x0[..., None]).squeeze(-1)
    return (-(true_logp * mask).sum(-1) / t).mean()

Both training runs use 801 optimizer updates and sample 128 corpus rows per update with replacement. The optimizer-update count is separate from the six denoising steps.

PythonIn [17]
CollapseExpand
model = Denoiser(K, SEQ_LEN)
opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.01)
running = []

for step in range(801):
    batch = corpus[torch.randint(0, len(corpus), (128,))]
    loss = diffusion_loss(model, batch)
    opt.zero_grad()
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    opt.step()
    running.append(loss.item())

model.eval()
ConsoleOut [18]
CollapseExpand
training NELBO, first 100 steps: 4.876 nats/sequence
training NELBO, last 100 steps:  4.324 nats/sequence
per token (dividing by L=6): 0.721 nats/token

The displayed loss means describe noisy training batches at two points during optimization. Now inspect the conditional probabilities at individual masked positions.

PythonIn [19]
CollapseExpand
@torch.no_grad()
def inspect(tokens, mask_rate):
    ids = torch.tensor([[stoi[w] for w in tokens]])
    probs = F.softmax(model(ids, torch.tensor([mask_rate])), dim=-1)[0]
    out = []
    for i, w in enumerate(tokens):
        if w == "[MASK]":
            top = probs[i].topk(3)
            picks = ", ".join(
                f"{VOCAB[j]} {p:.2f}" for p, j in zip(top.values, top.indices)
            )
            out.append((i, picks))
    return out


prompt = ["the", "[MASK]", "[MASK]", "a", "[MASK]", "."]
for pos, picks in inspect(prompt, mask_rate=0.34):
    print(f"position {pos}: {picks}")
ConsoleOut [20]
CollapseExpand
prompt: [MASK] cats [MASK] [MASK] [MASK] .
position 0: a 0.56, the 0.44, chases 0.00
position 2: chase 1.00, chases 0.00, cat 0.00
position 3: a 0.55, the 0.45, dogs 0.00
position 4: dog 0.31, cat 0.30, cats 0.23

In the second input, the known subject at zero-based position 1 gives evidence for the plural verb at position 2. The determiner at position 0 is a separate prediction. In this grammar the data sampler picks the determiner independently of the noun.

Compare three ways to choose positions. The Bernoulli rule samples the modeled transition. Fixed-count random and confidence selection choose exactly ⌈n/k⌉\lceil n/k\rceil positions. Confidence here means the probability of the sampled token. The categorical sampler flattens the batch and sequence axes to give one row of probabilities per position.

PythonIn [21]
CollapseExpand
def reveal_positions(masked, confidence, k, order, generator):
    noise = torch.rand(masked.shape, generator=generator)
    if order == "bernoulli":
        return masked & (noise < 1 / k)
    count = torch.ceil(masked.sum(-1) / k).long()
    score = confidence if order == "confidence" else noise
    score = score.masked_fill(~masked, -torch.inf)
    rank = score.argsort(dim=-1, descending=True).argsort(dim=-1)
    return masked & (rank < count[:, None])


@torch.no_grad()
def sample(model, initial, steps, order, seed):
    generator = torch.Generator().manual_seed(seed)
    x = initial.clone()
    for k in range(steps, 0, -1):
        t = torch.full((len(x),), k / steps)
        probs = F.softmax(model(x, t), dim=-1)
        candidates = torch.multinomial(
            probs.reshape(-1, K), 1, generator=generator
        ).reshape_as(x)
        confidence = probs.gather(-1, candidates[..., None]).squeeze(-1)
        reveal = reveal_positions(x == MASK_ID, confidence, k, order, generator)
        x = torch.where(reveal, candidates, x)
    return x

For infilling, keep the subject and punctuation visible. Check that the sampler preserves both tokens and never returns a mask.

PythonIn [22]
CollapseExpand
known = torch.tensor([[stoi[w] for w in prompt2]]).repeat(8, 1)
infilled = sample(model, known, steps=6, order="bernoulli", seed=18)
assert torch.equal(infilled[known != MASK_ID], known[known != MASK_ID])
assert torch.all(infilled != MASK_ID)
ConsoleOut [23]
CollapseExpand
the cats chase the dogs .
a cats chase the cats .
the cats chase a cat .

For unconditional generation start with all masks. Score the positional pattern and subject–verb agreement for every sample.

PythonIn [24]
CollapseExpand
NOUN_IDS = {stoi[w] for w in NOUNS}
DET_IDS = {stoi[w] for w in DETS}
SG_IDS = {stoi["cat"], stoi["dog"]}


def validity_rate(ids):
    """Fraction of samples matching the grammar, including subject-verb agreement."""
    a = ids.numpy()
    pattern = (
        np.isin(a[:, 0], list(DET_IDS))
        & np.isin(a[:, 1], list(NOUN_IDS))
        & np.isin(a[:, 3], list(DET_IDS))
        & np.isin(a[:, 4], list(NOUN_IDS))
        & (a[:, 5] == stoi["."])
    )
    want = np.where(
        np.isin(a[:, 1], list(SG_IDS)), stoi["chases"], stoi["chase"]
    )
    return float((pattern & (a[:, 2] == want)).mean())


configs = [
    ("Bernoulli", "bernoulli"),
    ("Fixed count, random", "random"),
    ("Fixed count, confidence", "confidence"),
]
step_grid = [2, 3, 6, 12]
initial = torch.full((512, SEQ_LEN), MASK_ID, dtype=torch.long)

rows = []
for steps in step_grid:
    for label, order in configs:
        sampled = sample(model, initial, steps=steps, order=order, seed=steps)
        assert torch.all(sampled != MASK_ID)
        rows.append(
            {
                "steps": steps,
                "sampler": label,
                "valid%": 100 * validity_rate(sampled),
            }
        )
results = pd.DataFrame(rows)
ConsoleOut [25]
CollapseExpand
sampler  Bernoulli  Fixed count, confidence  Fixed count, random
steps                                                           
2             75.8                     84.4                 81.4
3             80.7                     98.6                 88.7
6             91.2                    100.0                 98.6
12            96.1                     99.8                 99.4
VisualizationOut [26]
CollapseExpand
Grouped bars show the percentage satisfying the template and agreement by step count and reveal policy.
Percentage of 512 unconditional samples per configuration that match both the synthetic template and subject–verb agreement. Bars compare three reveal policies at four denoising step budgets.

Rows with the same step count use the same denoiser and number of network evaluations. Differences across those rows reflect both the reveal policy and sampling variation. The 12-step run changes the set of times encountered at generation. The figure describes this grammar without measuring wall-clock time.

Likelihood: exact enumeration versus Monte Carlo

Check the bound on the same synthetic distribution in two ways. The exhaustive evaluation sums the expected discrete loss across every mask pattern at each step. The stochastic evaluation samples from that same sum. Both use T=6T=6 for the primary comparison. A causal model trained on the same corpus provides an exact NLL through its left-to-right factorization.

PythonIn [27]
CollapseExpand
SUBSETS = torch.tensor(
    list(itertools.product([False, True], repeat=SEQ_LEN))
)  # (S, L)
N_SUBSETS = SUBSETS.shape[0]


@torch.no_grad()
def nelbo_exact_model(model, x0, steps):
    """Exact discrete-time NELBO with a linear schedule, by enumerating mask patterns."""
    b, L = x0.shape
    total = torch.zeros(b)
    for k in range(1, steps + 1):
        t = k / steps
        q_pattern = torch.tensor(
            [t ** int(s.sum()) * (1 - t) ** (L - int(s.sum())) for s in SUBSETS]
        )
        xt = torch.where(
            SUBSETS.unsqueeze(1),
            torch.full((N_SUBSETS, b, L), MASK_ID),
            x0.unsqueeze(0),
        )
        tt = torch.full((N_SUBSETS * b,), t)
        logp = F.log_softmax(model(xt.reshape(N_SUBSETS * b, L), tt), dim=-1)
        target = (
            x0.unsqueeze(0).expand(N_SUBSETS, b, L).reshape(N_SUBSETS * b, L)
        )
        lp = (
            logp.gather(-1, target.unsqueeze(-1))
            .squeeze(-1)
            .reshape(N_SUBSETS, b, L)
        )
        masked_lp = (lp * SUBSETS.unsqueeze(1).float()).sum(-1)  # (S, B)
        total += (q_pattern.unsqueeze(1) * (-masked_lp)).sum(0) / k
    return total


@torch.no_grad()
def mc_estimates(model, x0, steps, draws=400, seed=0):
    generator = torch.Generator().manual_seed(seed)
    values = []
    for _ in range(draws):
        k = torch.randint(1, steps + 1, (len(x0),), generator=generator)
        t = k / steps
        mask = torch.rand(x0.shape, generator=generator) < t[:, None]
        xt = torch.where(mask, torch.full_like(x0, MASK_ID), x0)
        logp = F.log_softmax(model(xt, t), dim=-1)
        true_logp = logp.gather(-1, x0[..., None]).squeeze(-1)
        estimate = -(true_logp * mask).sum(-1) / t
        values.append(float(estimate.mean() / x0.shape[-1]))
    return np.array(values)

The primary Monte Carlo estimate uses 400 draws. Each averages over the full corpus with a new time and mask for each sequence. The variation across draws estimates uncertainty in the reported mean. The causal baseline shares the main transformer dimensions and uses BOS and a causal attention mask.

PythonIn [28]
CollapseExpand
class ARModel(nn.Module):
    """Causal transformer with the same main block dimensions as the denoiser."""

    def __init__(self, n_tokens, seq_len, d=64, heads=4, layers=2, ff=128):
        super().__init__()
        self.tok = nn.Embedding(n_tokens + 1, d)
        self.pos = nn.Embedding(seq_len, d)
        self.blocks = nn.TransformerEncoder(
            nn.TransformerEncoderLayer(
                d, heads, ff, dropout=0.0, batch_first=True, norm_first=True
            ),
            layers,
        )
        self.norm = nn.LayerNorm(d)
        self.head = nn.Linear(d, n_tokens)

    def forward(self, x):
        L = x.shape[1]
        causal = torch.full((L, L), float("-inf")).triu(1)
        h = self.tok(x) + self.pos(torch.arange(L))
        return self.head(self.norm(self.blocks(h, mask=causal)))


BOS_ID = K
ar = ARModel(K, SEQ_LEN)
opt_ar = torch.optim.AdamW(ar.parameters(), lr=3e-3, weight_decay=0.01)

for step in range(801):
    batch = corpus[torch.randint(0, len(corpus), (128,))]
    inp = torch.cat(
        [torch.full((batch.shape[0], 1), BOS_ID), batch[:, :-1]], dim=1
    )
    loss = F.cross_entropy(ar(inp).reshape(-1, K), batch.reshape(-1))
    opt_ar.zero_grad()
    loss.backward()
    opt_ar.step()

ar.eval()
PythonIn [29]
CollapseExpand
with torch.no_grad():
    inp = torch.cat(
        [torch.full((len(corpus), 1), BOS_ID), corpus[:, :-1]], dim=1
    )
    ar_logp = (
        F.log_softmax(ar(inp), dim=-1).gather(-1, corpus[..., None]).squeeze(-1)
    )
ar_nll = float(-ar_logp.sum(-1).mean())

exact_rows = []
for steps in [2, 3, 6, 12, 24]:
    exact_rows.append(
        {
            "steps": steps,
            "NELBO/token": float(nelbo_exact_model(model, corpus, steps).mean())
            / SEQ_LEN,
        }
    )

summary = pd.DataFrame(exact_rows)
mc = mc_estimates(model, corpus, steps=TRAIN_STEPS)
mc_se = mc.std(ddof=1) / math.sqrt(len(mc))
ConsoleOut [30]
CollapseExpand
data entropy (best possible NLL):    4.159 nats/seq   0.693 nats/token
autoregressive exact NLL:            4.166 nats/seq   0.694 nats/token

 steps  NELBO/token
     2        0.763
     3        0.743
     6        0.724
    12        0.714
    24        0.709
Diffusion NELBO, Monte Carlo at T=6: 0.723 nats/token (SE 0.003)
Trainable parameters, denoiser: 72,969
Trainable parameters, AR:       68,681

The entropy floor is log⁡(64)/6≈0.693\log(64)/6\approx0.693 nats per token in expectation under the uniform grammar. For the causal baseline we compute exact cross-entropy on that distribution. For the denoiser we compute an upper bound for the reverse model at each step count. Compare the Monte Carlo estimate with the row at T=6T=6. Their difference is sampling error, with the Monte Carlo standard error as a scale.

Changing TT changes the modeled reverse chain. The table reports a different bound at each budget. Exact likelihood would require summing the reverse path probabilities, as we did for the two-token example.

Limitations and Impact

The trade-offs depend on the trained model, the sampler, and the workload. Compare quality on the same evaluation data and compare performance under the same measured serving conditions.

Quality and efficiency. A full-sequence sampler evaluates each position at every denoising round in this example. A cached causal decoder processes a prompt and then produces successive updates, each of which still uses prior context. Position evaluations alone omit attention, memory movement, kernel overhead, and batching, all of which can affect runtime.

Likelihood and evaluation. A valid negative variational bound upper-bounds the exact negative log-likelihood. On the same test data and with the same normalization, an upper-bound score below a competitor's exact score establishes an ordering. The opposite comparison can be inconclusive. A Monte Carlo estimate of a bound also has sampling error, so report its estimator and uncertainty.

The reverse chain derived here keeps committed tokens visible. Confidence-ordered reveal changes that sampler, and revision changes the allowed transitions. ReMDM derives a remasking kernel explicitly. When reporting quality, give the model, transition rule, and step budget. ReMDM

The examples choose the number of positions before generation. Variable-length systems need a length policy, such as padding, termination symbols, or a blockwise procedure. The likelihood derivation also needs the scored symbols and boundaries. Discrete text diffusion can use character or subword units, as in D3PM and LLaDA respectively.

The same masked interface can expose context on both sides of a gap. The examples compare likelihood and validity under specified transitions. For an application, evaluate the completion policy and latency with the intended mask patterns, hardware and length distribution.

Summary

  • Absorbing corruption independently masks positions while preserving visible tokens. The derived reverse chain fills masks and copies visible tokens forward.
  • A product reverse transition can draw several positions in parallel. The independent draws can produce combinations absent from the data even when each marginal is exact.
  • With an all-mask prior and endpoint, masked reconstruction weighted by reveal probability gives the negative ELBO. The bound is on the NLL of that reverse model.
  • Exact likelihood sums path probabilities. An ELBO averages a path log ratio. Data surprisal is a separate reference.
  • Changing the reveal policy or adding guidance changes the sampler. Copying visible tokens preserves the infilling constraints. Exact conditioning of the unconditional model is a separate calculation.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about diffusion language models.

Diffusion Language Models

Question 1 of 80 of 8 completed
In the absorbing-mask forward process, what happens to a position once it has been masked?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 6

Comparing Architecture Families Fairly

Learn how to compare Transformer, SSM, and hybrid architectures fairly with matched compute, bits per byte, roofline cost models, and clustered uncertainty.

64 min read
Language AI Handbook · Vol. 6

Blockwise and Semi-Autoregressive Generation

Explore semi-autoregressive block generation, blockwise parallel decoding, and exact speculative sampling with acceptance and residual repair rules.

42 min read
Language AI Handbook · Vol. 6

Token-Free and Byte-Level Language Models

Explore token-free byte-level language models: UTF-8 encoding, byte factorization, patching architectures like ByT5, CANINE, MEGABYTE, BLT, and fair evaluation.

54 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026diffusionlanguage, author = {Michael Brenndoerfer}, title = {Diffusion Language Models}, year = {2026}, url = {https://mbrenndoerfer.com/writing/diffusion-language-models-masked-text-generation}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-11-25} }
APAAcademic
Michael Brenndoerfer (2026). Diffusion Language Models. Retrieved from https://mbrenndoerfer.com/writing/diffusion-language-models-masked-text-generation
MLAAcademic
Michael Brenndoerfer. "Diffusion Language Models." 2026. Web. November 25, 2026. <https://mbrenndoerfer.com/writing/diffusion-language-models-masked-text-generation>.
CHICAGOAcademic
Michael Brenndoerfer. "Diffusion Language Models." Accessed November 25, 2026. https://mbrenndoerfer.com/writing/diffusion-language-models-masked-text-generation.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Diffusion Language Models'. Available at: https://mbrenndoerfer.com/writing/diffusion-language-models-masked-text-generation (Accessed: November 25, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Diffusion Language Models. https://mbrenndoerfer.com/writing/diffusion-language-models-masked-text-generation
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy