Module contents
Lesson 26 of 28Research 110 min

Discrete diffusion and diffusion language models

Derive categorical diffusion transitions and masked-diffusion objectives, connect random reveal orders to autoregression, and compare parallel decoding and language-model evaluation.

After this lesson you can

  • Calculate discrete transition marginals and reverse posteriors.
  • Derive the absorbing-mask continuous objective.
  • Relate masked objectives to uniformly random autoregressive orders.
  • Explain discrete-time and continuous-time generation and parallel decoding.
  • Compare a masked diffusion language model with a causal GPT under stated protocols.

Before you start

Corrupt symbols without turning them into pixels

A word, character or molecular token belongs to a discrete set. Adding Gaussian noise to a token’s integer ID does not by itself define semantically meaningful corruption: renumbering the vocabulary would change distances. Diffusion can be constructed on embeddings or other continuous representations, but here we choose explicit categorical transitions.

In discrete diffusion we specify replacement probabilities, calculate marginals and train a reverse process. Different matrices can erase, replace uniformly or respect a chosen geometry among symbols. That geometry is part of the model, not determined by arbitrary ID order.

D3PM: matrices and posterior

Let Qt[i,j]=q(xt=j∣xt−1=i)Q_t[i,j]=q(x_t=j\mid x_{t-1}=i) be a row-stochastic matrix, and Qˉt=Q1⋯Qt\bar Q_t=Q_1\cdots Q_t with Qˉ0=I\bar Q_0=I. Then

q(xt=j∣x0=i)=(Qˉt)ij.q(x_t=j\mid x_0=i)=(\bar Q_t)_{ij}.

By Bayes and the Markov property, for (Qˉt)ij>0(\bar Q_t)_{ij}>0,

q(xt−1=k∣xt=j,x0=i)=(Qˉt−1)ik Qt[k,j](Qˉt)ij.q(x_{t-1}=k\mid x_t=j,x_0=i) =\frac{(\bar Q_{t-1})_{ik}\,Q_t[k,j]}{(\bar Q_t)_{ij}}.

The expression normalizes by summing over kk. If the denominator is zero, the conditioning event has zero probability and the formula is not used. With KK symbols, uniform corruption can use Qt=(1−βt)I+βt11⊤/KQ_t=(1-\beta_t)I+\beta_t\mathbf1\mathbf1^\top/K. Absorbing corruption uses a special symbol mm: Qt=(1−βt)I+βt1em⊤Q_t=(1-\beta_t)I+\beta_t\mathbf1 e_m^\top, where mm remains absorbing. Austin and colleagues study structured matrix families in D3PM; Hoogeboom and colleagues develop multinomial diffusion.

InteractiveDiscrete corruption matrices

Each row shows q(xₜ | x₀). The outline marks the selected step and darker cells indicate higher probability.

symbol xₜ012345670t=0, symbol 0: 0.00000t=0, symbol 1: 0.00000t=0, symbol 2: 1.00000t=0, symbol 3: 0.00000t=0, symbol 4: 0.00000t=0, symbol 5: 0.00000t=0, symbol 6: 0.00000t=0, symbol 7: 0.00000t=1, symbol 0: 0.01500t=1, symbol 1: 0.01500t=1, symbol 2: 0.89500t=1, symbol 3: 0.01500t=1, symbol 4: 0.01500t=1, symbol 5: 0.01500t=1, symbol 6: 0.01500t=1, symbol 7: 0.01500t=2, symbol 0: 0.02820t=2, symbol 1: 0.02820t=2, symbol 2: 0.80260t=2, symbol 3: 0.02820t=2, symbol 4: 0.02820t=2, symbol 5: 0.02820t=2, symbol 6: 0.02820t=2, symbol 7: 0.02820t=3, symbol 0: 0.03982t=3, symbol 1: 0.03982t=3, symbol 2: 0.72129t=3, symbol 3: 0.03982t=3, symbol 4: 0.03982t=3, symbol 5: 0.03982t=3, symbol 6: 0.03982t=3, symbol 7: 0.03982t=4, symbol 0: 0.05004t=4, symbol 1: 0.05004t=4, symbol 2: 0.64973t=4, symbol 3: 0.05004t=4, symbol 4: 0.05004t=4, symbol 5: 0.05004t=4, symbol 6: 0.05004t=4, symbol 7: 0.050045t=5, symbol 0: 0.05903t=5, symbol 1: 0.05903t=5, symbol 2: 0.58677t=5, symbol 3: 0.05903t=5, symbol 4: 0.05903t=5, symbol 5: 0.05903t=5, symbol 6: 0.05903t=5, symbol 7: 0.05903t=6, symbol 0: 0.06695t=6, symbol 1: 0.06695t=6, symbol 2: 0.53135t=6, symbol 3: 0.06695t=6, symbol 4: 0.06695t=6, symbol 5: 0.06695t=6, symbol 6: 0.06695t=6, symbol 7: 0.06695t=7, symbol 0: 0.07392t=7, symbol 1: 0.07392t=7, symbol 2: 0.48259t=7, symbol 3: 0.07392t=7, symbol 4: 0.07392t=7, symbol 5: 0.07392t=7, symbol 6: 0.07392t=7, symbol 7: 0.07392t=8, symbol 0: 0.08005t=8, symbol 1: 0.08005t=8, symbol 2: 0.43968t=8, symbol 3: 0.08005t=8, symbol 4: 0.08005t=8, symbol 5: 0.08005t=8, symbol 6: 0.08005t=8, symbol 7: 0.08005t=9, symbol 0: 0.08544t=9, symbol 1: 0.08544t=9, symbol 2: 0.40192t=9, symbol 3: 0.08544t=9, symbol 4: 0.08544t=9, symbol 5: 0.08544t=9, symbol 6: 0.08544t=9, symbol 7: 0.0854410t=10, symbol 0: 0.09019t=10, symbol 1: 0.09019t=10, symbol 2: 0.36869t=10, symbol 3: 0.09019t=10, symbol 4: 0.09019t=10, symbol 5: 0.09019t=10, symbol 6: 0.09019t=10, symbol 7: 0.09019t=11, symbol 0: 0.09436t=11, symbol 1: 0.09436t=11, symbol 2: 0.33945t=11, symbol 3: 0.09436t=11, symbol 4: 0.09436t=11, symbol 5: 0.09436t=11, symbol 6: 0.09436t=11, symbol 7: 0.09436t=12, symbol 0: 0.09804t=12, symbol 1: 0.09804t=12, symbol 2: 0.31371t=12, symbol 3: 0.09804t=12, symbol 4: 0.09804t=12, symbol 5: 0.09804t=12, symbol 6: 0.09804t=12, symbol 7: 0.09804t=13, symbol 0: 0.10128t=13, symbol 1: 0.10128t=13, symbol 2: 0.29107t=13, symbol 3: 0.10128t=13, symbol 4: 0.10128t=13, symbol 5: 0.10128t=13, symbol 6: 0.10128t=13, symbol 7: 0.10128t=14, symbol 0: 0.10412t=14, symbol 1: 0.10412t=14, symbol 2: 0.27114t=14, symbol 3: 0.10412t=14, symbol 4: 0.10412t=14, symbol 5: 0.10412t=14, symbol 6: 0.10412t=14, symbol 7: 0.1041215t=15, symbol 0: 0.10663t=15, symbol 1: 0.10663t=15, symbol 2: 0.25360t=15, symbol 3: 0.10663t=15, symbol 4: 0.10663t=15, symbol 5: 0.10663t=15, symbol 6: 0.10663t=15, symbol 7: 0.10663t=16, symbol 0: 0.10883t=16, symbol 1: 0.10883t=16, symbol 2: 0.23817t=16, symbol 3: 0.10883t=16, symbol 4: 0.10883t=16, symbol 5: 0.10883t=16, symbol 6: 0.10883t=16, symbol 7: 0.10883t=17, symbol 0: 0.11077t=17, symbol 1: 0.11077t=17, symbol 2: 0.22459t=17, symbol 3: 0.11077t=17, symbol 4: 0.11077t=17, symbol 5: 0.11077t=17, symbol 6: 0.11077t=17, symbol 7: 0.11077t=18, symbol 0: 0.11248t=18, symbol 1: 0.11248t=18, symbol 2: 0.21264t=18, symbol 3: 0.11248t=18, symbol 4: 0.11248t=18, symbol 5: 0.11248t=18, symbol 6: 0.11248t=18, symbol 7: 0.11248t=19, symbol 0: 0.11398t=19, symbol 1: 0.11398t=19, symbol 2: 0.20212t=19, symbol 3: 0.11398t=19, symbol 4: 0.11398t=19, symbol 5: 0.11398t=19, symbol 6: 0.11398t=19, symbol 7: 0.1139820t=20, symbol 0: 0.11530t=20, symbol 1: 0.11530t=20, symbol 2: 0.19287t=20, symbol 3: 0.11530t=20, symbol 4: 0.11530t=20, symbol 5: 0.11530t=20, symbol 6: 0.11530t=20, symbol 7: 0.11530step t

Selected row, symbols 0 to 7: 0.090 · 0.090 · 0.369 · 0.090 · 0.090 · 0.090 · 0.090 · 0.090.

The same matrix is applied for 20 steps: Q=(1−0.12)I+0.12B, with rows indexed by the previous state. B is uniform, sends every symbol to the absorbing state 7, or row-normalizes exp(−(i−j)²/(2·1.2²)) with no wraparound. In the absorbing case, symbol 7 denotes [MASK]. It is an ordinary symbol under the other rules. Each step multiplies the probability row vector by Q.

Transition
2
10
Probability sum
1.000000
P(initial symbol)
0.3687
P(symbol 7)
0.0902
Entropy, nats
1.8867
Change matrix and time; observe the marginal calculated by transition products.

The discrete ELBO decomposes NLL into reconstruction, divergence between forward terminal distribution and prior, and reverse-posterior KLs at interior steps. The exact posterior above constructs those terms. Network parameterization and handling impossible states matter: inserting a transition matrix into a Gaussian formula is insufficient.

Absorbing masks and continuous ELBO

In masked diffusion, a clean position x0≠mx_0\ne m remains visible with probability αt\alpha_t and is in mm with probability 1−αt1-\alpha_t:

q(xt∣x0)=αtδx0+(1−αt)δm,α0=1,α1=0.q(x_t\mid x_0)=\alpha_t\delta_{x_0}+(1-\alpha_t)\delta_m, \qquad \alpha_0=1,\quad \alpha_1=0.

Assume αt\alpha_t differentiable and decreasing, independent corruption per position, ideal endpoints and a reverse model preserving visible tokens and predicting a normalized distribution over clean symbols at each mask. For s<ts<t, if the position is masked at tt, the forward posterior gives

q(xs=x0∣xt=m,x0)=αs−αt1−αt,q(xs=m∣xt=m,x0)=1−αs1−αt.q(x_s=x_0\mid x_t=m,x_0)=\frac{\alpha_s-\alpha_t}{1-\alpha_t},\qquad q(x_s=m\mid x_t=m,x_0)=\frac{1-\alpha_s}{1-\alpha_t}.

As s↑ts\uparrow t, the probability of revealing in an infinitesimal interval contributes −αt′/(1−αt)-\alpha'_t/(1-\alpha_t) times its width. The continuous-bound cross-entropy term for a length-nn sequence is

L=∫01−αt′1−αt Eq(xt∣x0) ⁣[∑i:xt,i=m−log⁡pθ(x0,i∣xt,t)]dt.\mathcal L=\int_0^1\frac{-\alpha'_t}{1-\alpha_t}\, \mathbb E_{q(x_t\mid x_0)}\!\left[ \sum_{i:x_{t,i}=m}-\log p_\theta(x_{0,i}\mid x_t,t)\right]dt.

Interpret the expression by limits where 1−αt=01-\alpha_t=0. Simplifications depend on reverse parameterization and endpoints: a bound with another prior, remasking or reconstruction terms may have additional components. Sahoo and colleagues derive this form for MDLM; Shi and colleagues analyze its formulation and extensions. A BERT-style MLM objective also predicts hidden tokens, but mask distribution and weighting need not match this integral.

The connection to random orders

Now suppose prediction for a mask depends on visible content and position, but does not receive an extra time variable. If SS is the set of kk hidden positions, changing variables from tt to α\alpha gives

(nk)∫01(1−α)k−1αn−k dα=1k.\binom nk\int_0^1(1-\alpha)^{k-1}\alpha^{n-k}\,d\alpha=\frac1k.

Therefore the bound above becomes

∑k=1nES: ∣S∣=k[1k∑i∈S−log⁡pθ(x0,i∣x0,Sc,S)].\sum_{k=1}^n\mathbb E_{S:\,|S|=k}\left[ \frac1k\sum_{i\in S}-\log p_\theta(x_{0,i}\mid x_{0,S^c},S)\right].

A uniform permutation reveals one position of SS uniformly when kk remain unrevealed. The sum is therefore the expected NLL of an autoregressive factorization with random order. This is equality of averaged objectives, under the stated assumptions; it does not say that a bidirectional model with explicit time or a sampler revealing several tokens automatically has the same distribution as a left-to-right causal GPT. The arbitrary-order argument also appears in Shi and colleagues.

InteractiveGeneration order

Both orders reveal the same fixed Spanish sentence using the correct tokens as context. This is teacher forcing. The sentences mean “The cat sleeps peacefully” and “The dogs play happily.”

Autoregressive: left to right
[MASK][MASK][MASK][MASK]
Masked: permuted order
[MASK][MASK][MASK][MASK]
Frame 0 of 4

Exact AR NLL: 1.9163 nats per sentence. For the masked random-order model revealing one token per pass, the exact mixture NLL is 2.4854 and the mean NLL over all 24 orders is 2.4925. Jensen’s inequality makes the latter an upper bound on mixture NLL. The exact perplexity is 1.861 and the displayed bound is 1.865.

This explicit four-token experiment uses the previous widget’s joint grammar for AR. The masked model mixes each exact posterior with a uniform distribution, using uniform fractions 0.60, 0.10, 0.35 and 0.05 by position. Each of the 24 orderings is equally likely, and all are enumerated. Perplexity is exp(NLL/4). The models assign different probabilities under this toy setup.

The pass count assumes a hypothetical network that returns all masked marginals in one call. The upper bound applies to the sequential random-order sampler. Revealing groups in parallel changes the distribution and can break dependencies. A Monte Carlo estimate of a bound gives no deterministic bound for an individual run. See RADD for the link between masked diffusion and random orders.

Recorded text8 measurements on the same test block

Teacher-forced reconstruction follows one ordering of 32 characters for each network. “·” marks masked characters, and spaces are preserved.

AR, left prefix································Masked, fixed random order································
0 / 32 characters

For this block, exact AR NLL is 83.120 nats. The displayed masked ordering gives NLL 90.705 nats for that particular path. The marginal NLL and averaged bound are separate quantities.

The 8 test blocks were held out of training, and the AR context restarts with BOS for each. Mean exact AR NLL is 2.5768 nats per character and perplexity is 13.155. The masked objective uses 32 draws per block: 2.8451 ± 0.0156 nats per character, with Monte Carlo standard error conditional on these blocks. The estimated exponential is 17.203. This stochastic estimate cannot serve as a deterministic bound for an individual run or as the exact perplexity of the parallel sampler.

The two networks have 104,000 parameters each and were trained for 100 updates with batch size 8. Training uses primeros 200000 caracteres from text8 and testing starts at character 95,000,000. These measurements describe a very small trial. See text8-quick.json and masked_language_lab.py for sources and seeds.

Evaluation sentence
Masked passes
AR / masked passes
0 / 0
Exact AR perplexity
1.615
Sequential masked perplexity
≤ 1.865
Compare orders and probabilities with the model and protocol stated.

Revealing in parallel changes dependencies

In parallel iterative decoding, the network sees the current state and predicts distributions for several positions. We can reveal a fixed number per pass, select randomly or prioritize more confident predictions. If two tokens are drawn independently from marginals calculated from the same context, the dependence captured by conditioning the second draw on the first is lost. Confidence can be wrong and an early decision can propagate; remasking and alternative schedules change the algorithm.

InteractiveA sentence being unmasked

The Spanish prefix «Hoy:» means “Today:” and stays fixed. Each pass predicts every still-hidden token and reveals the selected group. Simultaneous decisions do not condition on each other.

Hoy:[MASK][MASK][MASK][MASK].
Pass 0 of 2

The toy model uses eight grammatical Spanish sentences combining singular/plural, cat/dog and sleep/play. Singular has probability 0.6, and animal and action are equally likely. To give every sentence positive probability, 98% of the mass follows the grammar and the remaining 2% is uniform over 128 possible combinations. Each token posterior sums the probabilities of all sentences compatible with the revealed tokens.

A parallel pass samples each position’s marginal before revealing the other positions. This can produce a low-probability or ungrammatical combination. Confidence is the maximum marginal probability and determines reveal order. Changing steps or seed changes the procedure, and more steps cannot guarantee a better sentence. A pass represents one hypothetical joint evaluation returning all marginals.

Short recorded text8 experiment

This is a recorded trace from a trained bidirectional network. “·” marks a hidden character, and the prompt stays fixed. This small network has not learned to produce coherent text.

Recorded passes
Recorded order
once upon a time ···············
NFE 0

The prompt is “once upon a time ” and generation seed is 2610. The trace reveals 15 characters and uses one network call per pass. The transformer has 104,000 parameters, context length 32, 2 layers, and only 100 training updates with batch size 8. The trace depends on the strategy and use of randomness. See text8-quick.json and masked_language_lab.py.

Unmasking steps
Criterion
2610
Conceptual passes
0 / 2
Grammar agreement
Pending
Joint probability
Pending
Change steps and criterion; observe dependencies in the stated explicit model.

MaskGIT applies parallel iterative generation to image tokens; its rules are not identical to all masked-diffusion chains. When conditioning text on a prompt, keep its positions fixed and mask only the region to generate. If using Gumbel perturbations to sample categories, generate noise and calculate logarithms with sufficient precision: low-precision ties, rounding or numerical extremes can change the distribution.

Continuous time and discrete flows

In a continuous-time Markov chain, rate matrix RtR_t has nonnegative off-diagonal entries and rows summing to zero. For positive marginal distributions, the reverse-time rate from jj to ii is

R~t[j,i]=Rt[i,j]pt(i)pt(j),i≠j.\widetilde R_t[j,i]=R_t[i,j]\frac{p_t(i)}{p_t(j)},\qquad i\ne j.

The diagonal is chosen so each row sums to zero again. The ratio requires pt(j)>0p_t(j)>0 and is not an ordinary spatial derivative. SEDD estimates probability ratios between neighboring states via score entropy, allowing reverse rates without defining a Euclidean gradient over labels. See Lou, Meng and Ermon and the continuous framework of Campbell and colleagues.

Discrete flow matching designs categorical distribution paths and jump rates satisfying a discrete continuity equation. As in the continuous case, it can construct marginal velocities from conditional paths, but a “velocity” here describes probability flow between states, not a sum of token vectors. Different generators can share marginals and produce different jump trajectories. Gat and colleagues develop this formulation and sampling.

Diffusion language models

A diffusion language model can use bidirectional attention to predict masks and reveal tokens iteratively. MDLM is a masked-diffusion formulation with a likelihood bound; LLaDA studies this family at larger scale. Nie and colleagues describe an approximately 8.020-billion-parameter LLaDA model and experiment with different sampling strategies. In their efficiency analysis, a 256-token output in 32, 64, 128 or 256 passes corresponds respectively to 8, 4, 2 or 1 token per pass on average. This is a configuration of that study, not a universal latency law.

To compare a GPT and a masked model, use the same tokenizer, corpus, length, split and budget, and state attention and pass count. Causal NLL is exact for its factorization; a diffusion variational bound bounds NLL in expectation under its assumptions, and its exponential is a corresponding perplexity bound, not an exact measurement of the same object. A finite Monte Carlo estimate can fluctuate. NFE alone excludes per-pass cost, cache use and latency of decoding a token.

As a published reference, Sahoo and colleagues, table 1 report for LM1B, with 33 000 million tokens and 110-million-parameter models, perplexity 22.32 for their causal Transformer and perplexity bound 27.04 for MDLM. The second figure is a bound, not exact MDLM perplexity. That result and the reduced experiment below address different scales and protocols.

Lab: D3PM in NumPy

Use rows for previous state and columns for new state. The last rate is one: the final prior is exactly uniform in one case and the absorbing symbol in the other. Check each posterior with Bayes’ identity, including impossible hypotheses.

[ ]Categorical D3PM, part 1Browser
"""D3PM categórico: matrices, marginales y posterior exactas."""
import numpy as np

K=4; CLASSES=3; LENGTH=4; T=5; MASK=3
BETAS=np.array([.15,.25,.35,.45,1.])

def matrices(kind):
    result=[np.eye(K)]
    for beta in BETAS:
        if kind=='uniforme':base=np.full((K,K),1/K)
        elif kind=='absorbente':
            base=np.zeros((K,K));base[:,MASK]=1
        else:raise ValueError('Proceso desconocido')
        result.append((1-beta)*np.eye(K)+beta*base)
    return np.stack(result)

def cumulative(Q):
    result=[np.eye(K)]
    for t in range(1,T+1):result.append(result[-1]@Q[t])
    return np.stack(result)

def posterior(Q,B,x0,xt,t):
    # q(x_{t-1}=j | x_t=k,x_0=i), también para hipótesis imposibles.
    prior=B[t-1][x0]
    likelihood=Q[t][:,xt].transpose(1,2,0)
    joint=prior*likelihood;normalizer=joint.sum(axis=-1,keepdims=True)
    return np.divide(joint,normalizer,out=np.zeros_like(joint),where=normalizer>0),normalizer[...,0]>0

for kind in ('uniforme','absorbente'):
    Q=matrices(kind);B=cumulative(Q)
    assert np.allclose(Q.sum(axis=2),1) and np.allclose(B.sum(axis=2),1)
    for t in range(1,T+1):
        x0=np.arange(CLASSES).reshape(-1,1)
        for xt in range(K):
            values=np.full_like(x0,xt);post,valid=posterior(Q,B,x0,values,t)
            assert np.allclose(post.sum(-1),valid.astype(float))
            assert np.allclose(post*B[t][x0,values][...,None],B[t-1][x0]*Q[t][:,xt])
    if kind=='absorbente':
        assert np.allclose(B[T][:,MASK],np.ones(K),rtol=0,atol=1e-15)
    else:assert np.allclose(B[T],np.full((K,K),1/K))
    print(f'{kind}: matrices, marginales y Bayes verificadas en {T} pasos.')

def data_sample(rng,n):
    a=rng.integers(0,CLASSES,size=n);b=rng.integers(0,CLASSES,size=n)
    return np.stack((a,b,a,b),axis=1)

def categorical(rng,prob):
    cumulative=prob.cumsum(axis=-1);u=rng.random(prob.shape[:-1])[...,None]
    return np.minimum((u>cumulative).sum(axis=-1),prob.shape[-1]-1)

def corrupt(rng,x0,B,t):return categorical(rng,B[t][x0])

train_data=data_sample(np.random.default_rng(2601),1024)
test_data=data_sample(np.random.default_rng(2602),512)
print('Secuencias [a,b,a,b], a y b uniformes en {0,1,2}; train/test con semillas independientes.')

A linear network observes the full sequence and time step and trains with auxiliary cross-entropy to predict each clean token; we do not claim it directly optimizes the ELBO.

[ ]Categorical D3PM, part 2Browser
"""Desenmascarador lineal que observa la secuencia y el tiempo."""
def features(xt,t):
    return np.concatenate((np.eye(K)[xt].reshape(len(xt),LENGTH*K),
                           np.broadcast_to(np.eye(T)[t-1],(len(xt),T))),axis=1)

def predict(params,xt,t):
    W,b=params
    logits=(features(xt,t)@W+b).reshape(-1,LENGTH,CLASSES)
    logits-=logits.max(axis=-1,keepdims=True)
    prob=np.exp(logits);return prob/prob.sum(axis=-1,keepdims=True)

def ce(params,xt,t,x0):
    p=predict(params,xt,t)
    return -np.log(np.take_along_axis(p,x0[...,None],axis=-1)[...,0]).mean()

def heldout(params,B,seed):
    rng=np.random.default_rng(seed)
    return np.mean([ce(params,corrupt(rng,test_data,B,t),t,test_data) for t in range(1,T+1)])

def train_model(kind,seed):
    rng=np.random.default_rng(seed);Q=matrices(kind);B=cumulative(Q)
    params=[rng.normal(scale=.01,size=(LENGTH*K+T,LENGTH*CLASSES)),np.zeros(LENGTH*CLASSES)]
    initial=heldout(params,B,2690)
    moments=[np.zeros_like(p) for p in params];squares=[np.zeros_like(p) for p in params]
    for step in range(1,1001):
        x0=train_data[rng.integers(0,len(train_data),128)]
        t=int(rng.integers(1,T+1));xt=corrupt(rng,x0,B,t)
        inp=features(xt,t);prob=predict(params,xt,t)
        prob[np.arange(len(x0))[:,None],np.arange(LENGTH)[None,:],x0]-=1
        delta=prob.reshape(len(x0),-1)/(len(x0)*LENGTH)
        grads=[inp.T@delta,delta.sum(axis=0)]
        for j,(p,g) in enumerate(zip(params,grads)):
            moments[j]=.9*moments[j]+.1*g;squares[j]=.999*squares[j]+.001*g*g
            p-=.025*(moments[j]/(1-.9**step))/(np.sqrt(squares[j]/(1-.999**step))+1e-8)
    final=heldout(params,B,2690)
    print(f'{kind}: CE test por token inicial/final {initial:.6f}/{final:.6f}; 1000 actualizaciones.')
    return params,Q,B

uniform_params,uniform_Q,uniform_B=train_model('uniforme',2610)

Train with the same scheme for absorbing corruption, with another seed.

[ ]Categorical D3PM, part 3Browser
absorb_params,absorb_Q,absorb_B=train_model('absorbente',2611)

For each token, mix exact posteriors according to origin prediction and renormalize after excluding impossible hypotheses. This is an explicitly stated valid reverse model. Sum reconstruction at t=1 and KLs for remaining steps; terminal KL is zero because of the last rate. Its expectation is negative ELBO and bounds NLL; here Monte Carlo estimates it on test, so the finite figure is not necessarily a pointwise bound or exact NLL.

[ ]Categorical D3PM, part 4Browser
"""ELBO categórico Monte Carlo y sampler paralelo."""
def reverse_distribution(params,Q,B,xt,t):
    p0=predict(params,xt,t)
    posteriors=[];valid=[]
    for symbol in range(CLASSES):
        candidate=np.full_like(xt,symbol)
        post,possible=posterior(Q,B,candidate,xt,t)
        posteriors.append(post);valid.append(possible)
    posteriors=np.stack(posteriors,axis=-2);valid=np.stack(valid,axis=-1)
    # Se eliminan hipótesis x0 incompatibles con el token observado y se renormaliza.
    weights=p0*valid;normalizer=weights.sum(axis=-1,keepdims=True)
    if np.any(normalizer==0):raise ValueError('No hay hipótesis de origen compatibles')
    result=np.sum(posteriors*(weights/normalizer)[...,None],axis=-2)
    assert np.allclose(result.sum(-1),1)
    return result

def variational_bound(params,Q,B,seed):
    rng=np.random.default_rng(seed);terms=[]
    for t in range(1,T+1):
        xt=corrupt(rng,test_data,B,t)
        model=reverse_distribution(params,Q,B,xt,t)
        if t==1:
            picked=np.take_along_axis(model,test_data[...,None],axis=-1)[...,0]
            value=-np.log(np.maximum(picked,1e-300))
        else:
            truth,valid=posterior(Q,B,test_data,xt,t);assert valid.all()
            value=np.sum(np.where(truth>0,truth*(np.log(np.maximum(truth,1e-300))-
                                 np.log(np.maximum(model,1e-300))),0),axis=-1)
        terms.append(float(value.sum(axis=1).mean()))
    # beta_T=1 hace que el prior declarado coincida exactamente con q(x_T|x_0).
    return np.array(terms)

def sample(params,Q,B,kind,seed,n):
    rng=np.random.default_rng(seed)
    xt=(rng.integers(0,K,size=(n,LENGTH)) if kind=='uniforme' else np.full((n,LENGTH),MASK))
    for t in range(T,0,-1):xt=categorical(rng,reverse_distribution(params,Q,B,xt,t))
    return xt

for kind,params,Q,B in [('uniforme',uniform_params,uniform_Q,uniform_B),
                         ('absorbente',absorb_params,absorb_Q,absorb_B)]:
    terms=variational_bound(params,Q,B,2620)
    generated=sample(params,Q,B,kind,2621,256)
    coherent=np.mean((generated[:,0]==generated[:,2])&(generated[:,1]==generated[:,3]))
    assert np.all(generated<CLASSES)
    print(f'{kind}: términos de −ELBO Monte Carlo por secuencia {np.round(terms,4)}; suma {terms.sum():.6f} nats.')
    print(f'{kind}: {coherent:.3f} de 256 muestras cumplen [a,b,a,b]; primeras 4 {generated[:4].tolist()}.')
print('Las cadenas y corruptelas test usan semillas separadas; −ELBO se estima, no es una NLL exacta.')

Local lab: masked diffusion versus GPT

Train two Transformers from scratch with the same architecture, initialization, data and budget: one has causal attention and predicts the next character; the other has bidirectional attention and predicts characters at masked positions. In full mode each network has 25,300,480 parameters, eight blocks, width 512 and a 128-character window. Output assigns probability only to the 27 real characters; [MASK] and [BOS] are input symbols. Input and output embeddings share weights. This small architecture studies the mechanism, not the large-scale recipe or results of Sahoo and colleagues.

Data comes from text8, normalized Wikipedia text: 26 lowercase letters and space. Split the first 90 million characters for train, the next five million for validation and the last five million for test. This code reserves validation without using it and evaluates contiguous, non-overlapping test blocks. Causal NLL is exact for each block’s distribution with [BOS] and reset context; it is not the full sequence’s NLL with unlimited context.

For the masked model choose k∈{1,…,L}k\in\{1,\ldots,L\} uniformly and then a uniform subset of kk positions. Loss averages cross-entropies at those kk positions. Its expectation equals, per character, the mean NLL of a model revealing characters one at a time in a uniform permutation. By Jensen, that expectation upper-bounds NLL of the mixture over sequential orders. Code exhaustively checks the equality and Jensen with three symbols. Evaluation uses multiple masks per block and reports Monte Carlo standard error conditional on those blocks. One finite realization can lie on either side of its expectation: its exponential is an estimate of the perplexity bound, not a guaranteed pointwise bound or exact parallel-sampler perplexity. Monte Carlo uncertainty excludes test-set variation.

With the same fixed prompt, the masked sampler reveals characters simultaneously in 1, 4 or 8 network evaluations and compares random or confidence selection. Categorical distributions are calculated in float32, visible tokens and prompt are preserved, and the report saves each state. GPT generates one character at a time and counts each call. Call count does not equal actual cost, since calls may work on different lengths and cache mechanisms; no cache is implemented here. Confidence selection and parallel generation can change distribution: the bound evaluated above corresponds to uniform sequential orders, not these heuristics. As additional exploration, the report scores each suffix with this trial’s GPT and counts distinct characters; one sample and an evaluator favoring its own distribution cannot determine which sampler has better quality or diversity.

Install PyTorch and NumPy. Code downloads text8 once to the shared cache or reads the file selected by ORYON_TEXT8_ZIP; it checks length and records SHA-256. Use ORYON_OUTPUT_DIR for results. Full mode proposes 50,000 attempts per model, batches of eight and accumulation of four, 128 test blocks and 64 Monte Carlo repetitions; adjust ORYON_UPDATES, ORYON_TEST_BLOCKS and ORYON_MC_REPS to your budget. Checkpoints save weights and history but do not automatically resume the optimizer. Full training is performed by the reader.

With ORYON_QUICK=1, each network has 104,000 parameters and trains for 100 attempts on the first 200,000 characters; evaluation uses eight 32-character blocks and 32 repetitions. In a protected run both completed 100 updates without AMP skips. Causal NLL was 2.5768 nats per character and character perplexity 13.16. Estimated masked objective was 2.8451 nats per character with conditional Monte Carlo standard error 0.0156; its exponential was 17.20. These figures do not measure the same likelihood or establish a quality comparison between well-trained models. Short outputs retained the prompt but were incoherent: 100 steps do not produce a useful language model.

[ ]Masked diffusion and GPT on text8Local GPU
"""Difusión absorbente y GPT sobre text8, con evaluación comparable por bloques."""
import copy, hashlib, itertools, json, math, os, urllib.request, zipfile
from pathlib import Path

os.environ.setdefault('OPENBLAS_NUM_THREADS','1')
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
torch.set_num_threads(2)

ALPHABET=' abcdefghijklmnopqrstuvwxyz'
MASK=27
BOS=28
VOCAB=len(ALPHABET)


def digest(path):
    h=hashlib.sha256()
    with open(path,'rb') as f:
        for block in iter(lambda:f.read(1024*1024),b''):h.update(block)
    return h.hexdigest()


def load_text8(path):
    if not path.exists():
        path.parent.mkdir(parents=True,exist_ok=True)
        temp=path.with_suffix('.download')
        try:
            print('Descargando text8 a',path,flush=True)
            urllib.request.urlretrieve('https://mattmahoney.net/dc/text8.zip',temp)
            temp.replace(path)
        finally:
            if temp.exists():temp.unlink()
    with zipfile.ZipFile(path) as archive:
        raw=archive.read('text8')
    if len(raw)!=100_000_000:raise ValueError('text8 debe contener 100 000 000 caracteres')
    lookup=np.full(256,255,dtype=np.uint8)
    lookup[np.frombuffer(ALPHABET.encode('ascii'),dtype=np.uint8)]=np.arange(VOCAB,dtype=np.uint8)
    ids=lookup[np.frombuffer(raw,dtype=np.uint8)]
    if np.any(ids==255):raise ValueError('text8 contiene caracteres fuera del vocabulario')
    return ids


class Block(nn.Module):
    def __init__(self,width,heads,causal):
        super().__init__()
        self.heads=heads;self.causal=causal
        self.norm1=nn.LayerNorm(width);self.qkv=nn.Linear(width,3*width)
        self.out=nn.Linear(width,width);self.norm2=nn.LayerNorm(width)
        self.mlp=nn.Sequential(nn.Linear(width,4*width),nn.GELU(),nn.Linear(4*width,width))

    def forward(self,x):
        b,l,d=x.shape;q,k,v=self.qkv(self.norm1(x)).chunk(3,dim=-1)
        def shape(z):return z.reshape(b,l,self.heads,d//self.heads).transpose(1,2)
        y=F.scaled_dot_product_attention(shape(q),shape(k),shape(v),is_causal=self.causal)
        x=x+self.out(y.transpose(1,2).contiguous().reshape(b,l,d))
        return x+self.mlp(self.norm2(x))


class Transformer(nn.Module):
    def __init__(self,width,layers,heads,length,causal):
        super().__init__()
        self.length=length;self.causal=causal
        self.token=nn.Embedding(VOCAB+2,width);self.position=nn.Embedding(length,width)
        self.blocks=nn.ModuleList([Block(width,heads,causal) for _ in range(layers)])
        self.norm=nn.LayerNorm(width)
        self.apply(self._initialize)

    @staticmethod
    def _initialize(module):
        if isinstance(module,(nn.Linear,nn.Embedding)):
            nn.init.normal_(module.weight,mean=0.,std=.02)
            if isinstance(module,nn.Linear) and module.bias is not None:nn.init.zeros_(module.bias)

    def forward(self,tokens):
        if tokens.shape[1]>self.length:raise ValueError('La secuencia supera la ventana')
        x=self.token(tokens)+self.position(torch.arange(tokens.shape[1],device=tokens.device))
        for block in self.blocks:x=block(x)
        return F.linear(self.norm(x),self.token.weight[:VOCAB])


def random_blocks(ids,count,length,generator,device):
    indices=torch.randint(0,len(ids)-length+1,(count,),generator=generator).numpy()
    batch=np.stack([ids[i:i+length] for i in indices]).astype(np.int64)
    return torch.from_numpy(batch).to(device)


def corruption(tokens,generator):
    batch,length=tokens.shape
    count=torch.randint(1,length+1,(batch,),generator=generator,device=tokens.device)
    rank=torch.rand((batch,length),generator=generator,device=tokens.device).argsort(dim=1).argsort(dim=1)
    masked=rank<count[:,None]
    return torch.where(masked,MASK,tokens),masked,count


def ar_input(tokens):
    return torch.cat((torch.full_like(tokens[:,:1],BOS),tokens[:,:-1]),dim=1)


def masked_loss(model,tokens,generator):
    corrupt,mask,count=corruption(tokens,generator)
    ce=F.cross_entropy(model(corrupt).transpose(1,2),tokens,reduction='none')
    return ((ce*mask).sum(dim=1)/count).mean()


def ar_loss(model,tokens):
    return F.cross_entropy(model(ar_input(tokens)).transpose(1,2),tokens)


def verify():
    model=Transformer(32,2,4,12,True).eval()
    ids=torch.tensor([[1,2,3,4,5,6]])
    changed=ids.clone();changed[0,4:]=torch.tensor([8,9])
    with torch.no_grad():
        a=model(ar_input(ids));b=model(ar_input(changed))
    assert torch.allclose(a[:,:5],b[:,:5],atol=1e-6)
    gen=torch.Generator().manual_seed(2600)
    corrupted,mask,n=corruption(ids.repeat(100,1),gen)
    assert torch.all(mask.sum(1)==n) and torch.equal(corrupted[~mask],ids.repeat(100,1)[~mask])
    # Control exhaustivo: promedio por cardinalidades y subconjuntos equivale
    # a la NLL media de las seis órdenes secuenciales de tres símbolos.
    def toy_nll(pos,remaining):return .1*(1+pos+sum(remaining))
    per_order=[]
    for permutation in itertools.permutations(range(3)):
        left=set(range(3));value=0.
        for pos in permutation:
            value+=toy_nll(pos,left);left.remove(pos)
        per_order.append(value)
    mask_mean=0.
    for k in range(1,4):
        subsets=list(itertools.combinations(range(3),k))
        mask_mean+=sum(sum(toy_nll(i,set(m)) for i in m)/k for m in subsets)/len(subsets)
    assert math.isclose(mask_mean,sum(per_order)/len(per_order),rel_tol=1e-12)
    assert mask_mean>=-math.log(sum(math.exp(-nll) for nll in per_order)/len(per_order))
    for causal in (False,True):
        with torch.device('meta'): full=Transformer(512,8,8,128,causal)
        params=sum(p.numel() for p in full.parameters())
        assert 20_000_000<params<40_000_000
        print('Arquitectura',('causal' if causal else 'bidireccional'),params,'parámetros',flush=True)
    print('Comprobados máscara causal, cardinalidad, seis órdenes y cota por Jensen.',flush=True)


def train(kind,train_ids,width,layers,heads,length,device,quick,out):
    torch.manual_seed(2601)
    model=Transformer(width,layers,heads,length,causal=kind=='ar').to(device).train()
    optimizer=torch.optim.AdamW(model.parameters(),lr=3e-4,weight_decay=.01)
    scaler=torch.amp.GradScaler('cuda',enabled=device.type=='cuda')
    data_gen=torch.Generator().manual_seed(2602)
    mask_gen=torch.Generator(device=device).manual_seed(2603)
    updates=100 if quick else int(os.environ.get('ORYON_UPDATES','50000'))
    batch=8;accumulation=1 if quick else 4
    completed=skipped=0;history=[]
    for step in range(updates):
        optimizer.zero_grad(set_to_none=True);acc=0.
        for _ in range(accumulation):
            tokens=random_blocks(train_ids,batch,length,data_gen,device)
            with torch.autocast(device_type=device.type,enabled=device.type=='cuda'):
                loss=(ar_loss(model,tokens) if kind=='ar' else masked_loss(model,tokens,mask_gen))/accumulation
            if not torch.isfinite(loss):raise FloatingPointError('Pérdida no finita')
            scaler.scale(loss).backward();acc+=float(loss.detach())
        old=scaler.get_scale();scaler.step(optimizer);scaler.update()
        if scaler.get_scale()<old:skipped+=1
        else:completed+=1
        if step==0 or (step+1)%max(1,updates//10)==0:
            history.append({'attempt':step+1,'loss':acc,'effective_updates':completed,'skipped':skipped})
            print(f'{kind}: intento {step+1}/{updates}; pérdida {acc:.4f}; saltos AMP {skipped}',flush=True)
    result={'model':{k:v.detach().cpu() for k,v in model.state_dict().items()},
        'width':width,'layers':layers,'heads':heads,'length':length,'kind':kind,
        'attempts':updates,'effective_updates':completed,'skipped':skipped,'history':history,
        'batch':batch,'accumulation':accumulation,'data_seed':2602,'mask_seed':2603}
    torch.save(result,out/f'{kind}.pt')
    del optimizer,scaler
    model.cpu()
    if device.type=='cuda':torch.cuda.empty_cache()
    return model,result


@torch.no_grad()
def evaluate(ar,masked,test,device,quick):
    ar.to(device).eval();masked.to(device).eval()
    tokens=test.to(device);N,L=tokens.shape
    ar_ce=F.cross_entropy(ar(ar_input(tokens)).transpose(1,2),tokens,reduction='none')
    nll=float(ar_ce.mean());blocks=ar_ce.mean(dim=1).cpu().numpy()
    reps=32 if quick else int(os.environ.get('ORYON_MC_REPS','64'))
    if reps<2:raise ValueError('Usa al menos dos repeticiones Monte Carlo')
    generator=torch.Generator(device=device).manual_seed(2604)
    mc=[]
    for _ in range(reps):
        corrupt,mask,k=corruption(tokens,generator)
        ce=F.cross_entropy(masked(corrupt).transpose(1,2),tokens,reduction='none')
        mc.append(((ce*mask).sum(1)/k).cpu().numpy())
    draws=np.stack(mc)
    estimate=float(draws.mean())
    mc_se=float(np.sqrt(np.var(draws,axis=0,ddof=1).sum()/(reps*N*N)))
    result={'ar_nll_per_token':nll,'ar_ppl_per_token':math.exp(nll),
        'masked_nelbo_per_token_mc':estimate,'masked_exp_nelbo_mc':math.exp(estimate),
        'masked_conditional_mc_standard_error':mc_se,'mc_repetitions':reps,'mc_seed':2604,
        'ar_first_block_nll':float(blocks[0]*L),'ar_first_block_nll_per_token':float(blocks[0]),
        'masked_first_block_nelbo_mc':float(draws[:,0].mean()*L),
        'masked_first_block_nelbo_mc_se':float(draws[:,0].std(ddof=1)/math.sqrt(reps)*L),
        'blocks':N,'block_length':L}
    return result,ar_ce.cpu().numpy()


def decode(tokens):
    return ''.join(ALPHABET[int(t)] if 0<=int(t)<VOCAB else '·' for t in tokens)


@torch.no_grad()
def masked_generate(model,prompt,length,steps,method,device,seed):
    prompt_ids=[ALPHABET.index(ch) for ch in prompt]
    if len(prompt_ids)>=length or steps<1:raise ValueError('Prompt demasiado largo o número de pasos inválido')
    x=torch.full((1,length),MASK,device=device,dtype=torch.long)
    x[0,:len(prompt_ids)]=torch.tensor(prompt_ids,device=device)
    gen=torch.Generator(device=device).manual_seed(seed)
    remaining=length-len(prompt_ids);trace=[{'nfe':0,'text':decode(x[0].tolist())}]
    steps=min(steps,remaining)
    for i in range(steps):
        probs=F.softmax(model(x).float(),dim=-1)[0]
        available=(x[0]==MASK).nonzero().flatten()
        remaining_after=round(remaining*(steps-i-1)/steps)
        take=len(available)-remaining_after
        if method=='random':
            order=torch.randperm(len(available),device=device,generator=gen)
            chosen=available[order[:take]]
        elif method=='confidence':chosen=available[torch.argsort(probs[available].max(-1).values,descending=True)[:take]]
        else:raise ValueError('Criterio desconocido')
        draws=torch.multinomial(probs[chosen],1,generator=gen).squeeze(1)
        x[0,chosen]=draws
        trace.append({'nfe':i+1,'text':decode(x[0].tolist()),'positions':chosen.cpu().tolist()})
    assert torch.equal(x[0,:len(prompt_ids)],torch.tensor(prompt_ids,device=device))
    assert not torch.any(x==MASK)
    return trace


@torch.no_grad()
def ar_generate(model,prompt,length,device,seed):
    gen=torch.Generator(device=device).manual_seed(seed)
    ids=[ALPHABET.index(ch) for ch in prompt]
    trace=[{'nfe':0,'text':decode(ids)+'·'*(length-len(ids))}]
    for _ in range(length-len(ids)):
        input_ids=torch.tensor([[BOS]+ids],device=device)
        probs=F.softmax(model(input_ids)[0,-1].float(),dim=-1)
        ids.append(int(torch.multinomial(probs,1,generator=gen)))
        trace.append({'nfe':len(ids)-len(prompt),'text':decode(ids)+'·'*(length-len(ids))})
    return trace


@torch.no_grad()
def true_order_trace(ar,masked,block,device):
    block=block.to(device);length=len(block)
    nll=F.cross_entropy(ar(ar_input(block[None]))[0],block,reduction='none').cpu().tolist()
    gen=torch.Generator(device=device).manual_seed(2605)
    order=torch.randperm(length,generator=gen,device=device).tolist()
    x=torch.full((1,length),MASK,device=device,dtype=torch.long);trace=[]
    for i,pos in enumerate(order):
        probs=F.log_softmax(masked(x)[0,pos].float(),dim=-1)
        loss=-float(probs[block[pos]])
        x[0,pos]=block[pos]
        trace.append({'nfe':i+1,'position':pos,'nll':loss,'text':decode(x[0].tolist())})
    return {'sequence':decode(block.tolist()),'random_order_seed':2605,'random_order':order,
        'masked_order_nll':sum(item['nll'] for item in trace),'masked_order_trace':trace,
        'ar_token_nll':nll,'ar_exact_nll':sum(nll)}


@torch.no_grad()
def score_suffix(ar,text,prompt_length,device):
    ids=torch.tensor([[ALPHABET.index(c) for c in text]],device=device)
    logits=ar(ar_input(ids))
    token_nll=F.cross_entropy(logits.transpose(1,2),ids,reduction='none')[0]
    suffix=text[prompt_length:]
    return {'gpt_nll_per_character':float(token_nll[prompt_length:].mean()),
            'distinct_characters':len(set(suffix)),'characters':len(suffix)}


def main():
    quick=os.environ.get('ORYON_QUICK','0')=='1'
    verify();device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    default_cache=Path.home()/'.cache'/'atlas-data'/'text8.zip'
    path=Path(os.environ.get('ORYON_TEXT8_ZIP',str(default_cache)))
    ids=load_text8(path)
    length=32 if quick else 128;width=64 if quick else 512;layers=2 if quick else 8;heads=4 if quick else 8
    train_ids=ids[:200_000] if quick else ids[:90_000_000]
    # Los bloques test comienzan en el límite oficial, sin ejemplos de train ni validación.
    n_test=8 if quick else int(os.environ.get('ORYON_TEST_BLOCKS','128'))
    if n_test<1 or n_test*length>5_000_000:raise ValueError('Cantidad de bloques test inválida')
    test=torch.from_numpy(ids[95_000_000:95_000_000+n_test*length].copy().astype(np.int64)).reshape(n_test,length)
    out=Path(os.environ.get('ORYON_OUTPUT_DIR','oryon-l26'));out.mkdir(parents=True,exist_ok=True)
    ar,ar_ckpt=train('ar',train_ids,width,layers,heads,length,device,quick,out)
    mdlm,mdlm_ckpt=train('masked',train_ids,width,layers,heads,length,device,quick,out)
    evaluation,per_token=evaluate(ar,mdlm,test,device,quick)
    prompt='once upon a time '
    generative={}
    for n in (1,4,8):
        for mode in ('random','confidence'):
            generative[f'{mode}_{n}']=masked_generate(mdlm,prompt,length,n,mode,device,2610)
    generative['ar']=ar_generate(ar,prompt,length,device,2610)
    generated_scores={name:score_suffix(ar,steps[-1]['text'],len(prompt),device)
                      for name,steps in generative.items()}
    trace=true_order_trace(ar,mdlm,test[0],device)
    report={'quick':quick,'source':'text8, Matt Mahoney: https://mattmahoney.net/dc/text8.zip',
        'archive_sha256':digest(path),'vocabulary':ALPHABET,'specials':{'MASK':MASK,'BOS':BOS},
        'split':{'train':'primeros 200000 caracteres' if quick else 'primeros 90000000 caracteres',
                 'validation':'caracteres 90000000 a 94999999, no usados',
                 'test':'desde carácter 95000000, bloques contiguos sin solapamiento'},
        'model':{'width':width,'layers':layers,'heads':heads,'length':length,
                 'ar_parameters':sum(p.numel() for p in ar.parameters()),
                 'masked_parameters':sum(p.numel() for p in mdlm.parameters())},
        'training':{'ar':{k:v for k,v in ar_ckpt.items() if k!='model'},
                    'masked':{k:v for k,v in mdlm_ckpt.items() if k!='model'}},
        'evaluation':evaluation,'first_block':trace,'prompt':prompt,'generation_seed':2610,
        'generation':generative,'generated_suffix_scores':generated_scores,
        'generated_score_note':'NLL bajo el GPT de este mismo ensayo, una muestra por configuración: proxy débil, sesgado hacia ese modelo y no una medida fiable de calidad.',
        'semantics':'NLL AR exacta para bloques con BOS y contexto reiniciado; objetivo enmascarado es cota en esperanza para mezcla uniforme de órdenes secuenciales, no NLL exacta del sampler paralelo ni garantía por realización MC.'}
    (out/'report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
    print('Evaluación:',json.dumps(evaluation,ensure_ascii=False),flush=True)
    for name,tr in generative.items():print(name,repr(tr[-1]['text']),generated_scores[name],flush=True)
    print('Informe:',out/'report.json',flush=True)
    del ar,mdlm,ar_ckpt,mdlm_ckpt,ids
    if device.type=='cuda':torch.cuda.empty_cache()


if __name__=='__main__':main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofThe absorbing posterior
Prove: Derive the absorbing marginal and continuous cross-entropy weight.
0
x₀ is not a mask, α₀=1, α₁=0 and positions are corrupted independently.

Step 1 of 3. What is q(xₜ=m|x₀)?

ProofFrom masks to permutations
Prove: Relate the continuous objective to a random-order factorization.
0
The predictor depends on the visible subset but not an additional t variable.

Step 1 of 2. After averaging the sum of losses over uniform subsets of size k, what is its integrated coefficient?

NumericParallel budget
If 256 tokens are revealed in 32 passes without remasking, how many are revealed per pass on average?
CodeMasked loss and revealing
Implement masked_diffusion_loss(model,tokens,mask_prob,mask_id,rng) and confidence_sample(model,initial,mask_id,n_steps). tokens has shape (B,L) and clean values between 0 and mask_id−1. For the loss, independently mask each position with probability p=mask_prob, where 0<p≤1; model(corrupted) returns logits (B,L,mask_id). Use stable logsumexp and return summed masked-position cross-entropies divided by B·p. In the sampler, initial contains visible tokens or mask_id: on each pass call the model once, compute normalized softmax, reveal per row ceil(remaining masks/remaining passes) highest-confidence positions with their argmax category and preserve visible ones. Return the sequence without modifying inputs; reject n_steps<1.
import numpy as np
from scipy.special import logsumexp

def masked_diffusion_loss(model, tokens, mask_prob, mask_id, rng):
  pass

def confidence_sample(model, initial, mask_id, n_steps):
  pass
Shift+Enter to run
QuizTwo blanks at once
What can be lost when sampling two tokens independently using marginals from the same pass?
Key idea

Matrices define categorical corruption and the reverse process. The masked bound connects to random orders under specific assumptions; revealing in parallel changes which dependencies are conditioned on and what is measured.