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
- 19Diffusion ELBOOrder-agnostic autoregressive trainingVector-quantized VAEConditional flow matchingAutoregressive factorization
- 20Masked language modelingCausal language modeling objective
- 26Rate matrix (Q-matrix)Kolmogorov equations for CTMCs
- 18Encoder-only architectureEncoder block
- 07Cross-entropyPerplexity
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 be a row-stochastic matrix, and with . Then
By Bayes and the Markov property, for ,
The expression normalizes by summing over . If the denominator is zero, the conditioning event has zero probability and the formula is not used. With symbols, uniform corruption can use . Absorbing corruption uses a special symbol : , where remains absorbing. Austin and colleagues study structured matrix families in D3PM; Hoogeboom and colleagues develop multinomial diffusion.
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 remains visible with probability and is in with probability :
Assume 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 , if the position is masked at , the forward posterior gives
As , the probability of revealing in an infinitesimal interval contributes times its width. The continuous-bound cross-entropy term for a length- sequence is
Interpret the expression by limits where . 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 is the set of hidden positions, changing variables from to gives
Therefore the bound above becomes
A uniform permutation reveals one position of uniformly when 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.
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.
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 has nonnegative off-diagonal entries and rows summing to zero. For positive marginal distributions, the reverse-time rate from to is
The diagonal is chosen so each row sums to zero again. The ratio requires 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.
"""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.
"""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.
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.
"""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 uniformly and then a uniform subset of positions. Loss averages cross-entropies at those 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.
"""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()
npm run lab and open the connection link.Exercises
Step 1 of 3. What is q(xₜ=m|x₀)?
Step 1 of 2. After averaging the sum of losses over uniform subsets of size k, what is its integrated coefficient?
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
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.