Frontier: continuous autoregression, multiscale generation and unified models
Compare autoregressive and diffusion combinations, next-scale prediction, compact tokenizers and multimodal generation, then evaluate model claims through six explicit design decisions.
After this lesson you can
- Explain continuous conditional token generation with MAR and diffusion loss.
- Describe next-scale prediction and multiscale residual quantization.
- Compare tokenizer budgets and reconstruction versus generative quality.
- Analyze unified text-image generation and modality-specific constraints.
- Evaluate papers through objective, process, parameterization, architecture, sampler and evaluation.
Before you start
The family does not determine the whole architecture
A generator may decide autoregressively which image part to produce while using diffusion to decide that part’s value. Another may predict an entire resolution at each step. A third shares a transformer between text and image but changes loss by modality. Asking which label, “autoregression” or “diffusion,” wins hides decisions that can be combined.
Always separate generation order, representation, distribution modeled at each step and sampler cost. Transformer query count is not necessarily small-head query count or total time, which also includes tokenizer and decoder.
MAR: a continuous distribution for each token
In a two-stage generator, an encoder transforms an image into latent vectors , with . An autoregressive factorization in order is
Nothing in this identity requires to be an integer. The practical challenge is representing each multimodal continuous conditional: quadratic regression gives a mean that can lie between plausible alternatives. The per-token diffusion loss of Li and colleagues uses a transformer to build context and a small network to model the distribution of continuous vector conditioned on that context.
With noise-prediction parameterization, a representative objective for masked tokens is
Here and is calculated without revealing the clean value of the predicted position. This trains the denoiser; it is not exact log-likelihood evaluation. The masking procedure, schedule and specific weights are part of the method. During generation the transformer contextualizes masked positions and the diffusion head denoises their vectors; MAR can reveal several tokens at once. This reduces transformer passes, but conditional independence of tokens revealed in the same group and the group schedule affect the distribution.
In MAR table 1, for ImageNet 256 and the bidirectional variant predicting one token at a time, MAR-L obtains FID 8.75 with a discrete VQ-16 formulation and 3.43 with DiffLoss on KL-16 without guidance; with guidance the values are 3.50 and 1.84. Both representation and loss change: the entire difference cannot be attributed to one. The work also evaluates the tradeoff between transformer iterations and quality. MLP-head steps and transformer passes cost different amounts; batching several positions is not equivalent to an independent transformer pass per token.
VAR: predict the next scale
Next-scale prediction orders maps from coarse to fine resolution. If is the discrete map of scale , the model factorizes
In VAR each map is predicted in parallel conditioned on previous maps. The multiscale tokenizer represents residual left after adding earlier contributions, with a shared vocabulary and learned transformations. The decoder reconstructs from the sum of contributions. The lab implements a simple analogue to study the mechanism; it does not reproduce the weights or all interpolations and convolutions of the trained tokenizer of Tian and colleagues.
For sides , the sequence contains codes. There are ten sequential scale stages, not 680 sequential raster decisions. This does not imply equal stage costs: map size, attention, cache and decoder change.
In VAR table 1, VAR-d30 with approximately 2000 million parameters reports FID 1.92 on ImageNet 256; 1.73 corresponds to its rejection-sampling variant. These are conditional results and their protocols should be read before comparison with other work. The paper also studies capacity and data scaling, but an empirical curve does not guarantee the same law outside its measured range.
How many tokens does an image need?
Reducing tokens lowers some generator operations, but the encoder must retain what the decoder needs and produce a distribution the model can learn. Greater reconstruction capacity does not guarantee lower generation error: vocabulary, architecture, training budget and sampler also matter. A 2D grid of has tokens; a 1D representation can use a length chosen independently of a regular spatial grid.
Compact tokenizers by Yu and colleagues use a learned 1D sequence. In their preliminary study, TiTok-L with 32 tokens reports rFID 6.6 and gFID 6.3; with 128, rFID 3.0 and gFID 3.7 under the same protocol. rFID compares reconstructions and originals; gFID evaluates generated samples against the reference set. They are different objects, and numbers from different tables or recipes should not be mixed as one experimental curve.
One transformer for text and image
In Transfusion, a sequence may interleave discrete text and continuous image blocks. Text uses next-token loss; noisy image patches receive diffusion loss. The transformer shares parameters across modalities while input/output projections and losses respect data type. The attention mask preserves causality with respect to future sequence elements and allows bidirectional attention within the image block being processed.
In one ablation by Zhou and colleagues, table 5, with a 0.76-billion model and latent patches, the linear encoder obtains FID 61.3 with causal attention versus 20.3 with bidirectional attention within the image. With their U-Net encoder the figures are 16.8 and 16.7. This depends on encoder, mask and protocol: it does not prove one mask universally better for every architecture.
Changing modality changes constraints
In video, temporal order, frame-to-frame consistency and spatiotemporal attention cost become central. In audio, sample rate, windows and phase matter; in molecules, validity and structural symmetries. In 3D, choosing meshes, point clouds or fields affects equivariance, geometric consistency and available metrics. The same questions about representation, path, network, sampler and evaluation remain useful, but transferring an image FID figure is insufficient. See connections to multimodal representations and each domain’s specific constraints.
Read a paper as six decisions
When encountering a new model, identify what actually changed:
- Objective: What quantity is minimized and under what weighting?
- Process: What is corrupted, interpolated or revealed, and in what order?
- Parameterization: Is noise, score, velocity, clean data or a categorical distribution predicted?
- Architecture: Which network sees which context, with what attention and tokenizer?
- Sampler: How many stages and evaluations of each network are used, with what guidance and cache?
- Evaluation: What data, split, resolution, samples, metric and budget are compared?
A useful ablation changes one decision while controlling the others. If guidance, representation and size change together, a table can establish which system performs better under those recipes but does not identify the cause of the difference. Critical reading and falsifiable hypotheses connect to research.
Lab: multiscale residual quantization
The two digits are images at indices 0 and 1 of sklearn.datasets.load_digits(), with intensities divided by 16. They are included in the cell so it works offline. Encoder is identity, scalar codebook fixed and shared, downsampling is block mean, upsampling repeats each block and post-correction is identity. These are explicit teaching substitutes: VAR’s VAE uses learned vector embeddings, interpolation and residual convolutions; its trained tokenizer is not reproduced.
Each scale quantizes the current residual and the decoder reconstructs only from indices. In this example squared error cannot increase: choosing the codebook value nearest each block mean minimizes that block’s error, and zero is always a candidate. This property depends on these operators and is not a general VAR guarantee.
"""Cuantización residual multiescala didáctica sobre dígitos reales 8×8."""
import numpy as np
# Imágenes 0 y 1 de sklearn.datasets.load_digits(), intensidades enteras 0..16.
DIGITS=np.array([
[[0,0,5,13,9,1,0,0],[0,0,13,15,10,15,5,0],[0,3,15,2,0,11,8,0],
[0,4,12,0,0,8,8,0],[0,5,8,0,0,9,8,0],[0,4,11,0,1,12,7,0],
[0,2,14,5,10,12,0,0],[0,0,6,13,10,0,0,0]],
[[0,0,0,12,13,5,0,0],[0,0,0,11,16,9,0,0],[0,0,3,15,16,6,0,0],
[0,7,15,16,16,2,0,0],[0,0,1,16,16,3,0,0],[0,0,1,16,16,6,0,0],
[0,0,1,16,16,6,0,0],[0,0,0,11,16,10,0,0]]],dtype=float)/16
SIDES=(1,2,4,8)
CODEBOOK=np.array([-1.,-.5,-.25,-.125,0.,.125,.25,.5,1.])
def upsample(code_map):
side=code_map.shape[0]
if code_map.shape!=(side,side) or 8%side:raise ValueError('Escala incompatible')
return np.repeat(np.repeat(code_map,8//side,axis=0),8//side,axis=1)
def encode(image):
if image.shape!=(8,8):raise ValueError('Se requiere una imagen de 8×8')
residual=image.copy();tokens=[];reconstructions=[]
for side in SIDES:
width=8//side
low=residual.reshape(side,width,side,width).mean(axis=(1,3))
idx=np.argmin(np.abs(low[:,:,None]-CODEBOOK),axis=2)
contribution=upsample(CODEBOOK[idx])
residual-=contribution
tokens.append(idx)
reconstructions.append(image-residual)
return tokens,reconstructions
def decode(tokens):
reconstruction=np.zeros((8,8));progress=[]
for side,idx in zip(SIDES,tokens):
if idx.shape!=(side,side) or np.any(idx<0) or np.any(idx>=len(CODEBOOK)):
raise ValueError('Índices de escala inválidos')
reconstruction+=upsample(CODEBOOK[idx])
progress.append(reconstruction.copy())
return progress
assert sum(s*s for s in SIDES)==85
assert sum(s*s for s in (1,2,3,4,5,6,8,10,13,16))==680
for number,image in enumerate(DIGITS):
tokens,encoded=encode(image)
decoded=decode(tokens)
mse=np.array([np.mean((image-recon)**2) for recon in decoded])
assert all(np.array_equal(a,b) for a,b in zip(encoded,decoded))
assert np.all(np.diff(mse)<=1e-15)
assert all(idx.shape==(s,s) for idx,s in zip(tokens,SIDES))
print(f'Dígito índice {number}: tokens por escala {[s*s for s in SIDES]}, MSE acumulada',
' / '.join(f'{v:.8f}' for v in mse))
zero_tokens,zero=encode(np.zeros((8,8)))
assert all(np.all(frame==0) for frame in zero)
print('85 tokens; reconstrucción desde índices, residuo y caso nulo verificados. El ejemplo es escalar y no usa la VAE de VAR.')Local lab: miniature MAR and discrete prior
Train the lesson 7 VQ-VAE on Fashion-MNIST and freeze it. Its encoder reduces each 28×28 image to 49 vectors of 32 components; the quantizer chooses among 128 codes and the decoder receives their grid. The reference prior reproduces lesson 7’s causal architecture and generates 49 indices in raster order. The second prior receives continuous vectors before quantization. A bidirectional transformer sees only unmasked vectors and an MLP head learns to predict noise added to masked ones. During generation each group’s tokens are denoised in parallel and then added to context. This is a teaching version, not full MAR training or architecture.
The decoder was trained on quantized vectors: applying that same decoder to continuous vectors can introduce distribution shift. The cell measures test MSE of both reconstructions so you can see it; a sample difference cannot be attributed only to prior type. Latent mean and deviation are fit exclusively on training and reversed before decoding. Official train and test sets are separate. To detect leakage, the cell alters masked inputs and checks all contexts remain equal, and tests the causal mask and finite gradients.
Generated images are compared with the same held-out images using two metrics on one representation: each image is reduced by block averages to 7×7 pixels. Fréchet distance of those 49 features is not Inception FID. Unbiased Gaussian-kernel MMD uses a bandwidth computed only from training and can be negative in finite samples. No measure alone proves quality, coverage or absence of copies. Discrete-prior cross-entropy and continuous noise-prediction error are also reported: they measure different objectives and their figures are not comparable as image probabilities.
Defaults use all images, 12 epochs for VQ-VAE and 12 for both priors, 128 samples, 12 MAR groups and 20 head diffusion steps. The causal prior performs 49 transformer passes; MAR uses one per group and 20 MLP passes per group, which do not cost the same as a transformer pass. The report separately records parameters, updates, calls, seeds and versions and saves a checkpoint and grids in ORYON_OUTPUT_DIR. It does not measure actual tokenizer latency or establish equal compute. Guidance is disabled. Seeds fix the experiment, though CUDA operations and versions can produce small numerical differences.
Install PyTorch, torchvision and NumPy. Set ORYON_FASHION_ROOT or ORYON_DATA_ROOT for the data directory and ORYON_OUTPUT_DIR for results; Fashion-MNIST downloads if missing. ORYON_QUICK=1 uses 256 training images, 64 test images, one epoch per stage, 8 samples, 4 groups and 5 head steps. The quick test checks the pipeline, not full-training quality. ORYON_VQ_EPOCHS, ORYON_PRIOR_EPOCHS, ORYON_SAMPLE_IMAGES, ORYON_MAR_GROUPS and ORYON_MAR_DIFF_STEPS adjust the budget. You perform full training.
In one short run, test reconstruction MSE was 0.14322 with continuous latent and 0.15327 with quantized latent. Fréchet distances on reduced pixels were 6.0026 for the causal prior and 4.8757 for mini-MAR, with only eight samples per model. This calculation is not FID and the sample is too small to decide which is better. The causal prior made 49 transformer passes; mini-MAR made four transformer and 20 head passes, batching each group. Per-call costs differ.
"""Mini-MAR y prior VQ causal en Fashion-MNIST, con evaluación compartida."""
import json
import math
import os
import platform
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Subset, TensorDataset
from torchvision import datasets, transforms, utils
QUICK = os.environ.get('ORYON_QUICK') == '1'
SEED = 19
K, D, N = 128, 32, 49
BS = 32 if QUICK else 128
EPOCHS_VQ = int(os.environ.get('ORYON_VQ_EPOCHS', 1 if QUICK else 12))
EPOCHS_PRIOR = int(os.environ.get('ORYON_PRIOR_EPOCHS', 1 if QUICK else 12))
IMAGE_COUNT = int(os.environ.get('ORYON_SAMPLE_IMAGES', 8 if QUICK else 128))
GROUPS = int(os.environ.get('ORYON_MAR_GROUPS', 4 if QUICK else 12))
DIFF_STEPS = int(os.environ.get('ORYON_MAR_DIFF_STEPS', 5 if QUICK else 20))
T = 1000
ROOT = Path(os.environ.get('ORYON_FASHION_ROOT', os.environ.get('ORYON_DATA_ROOT', './data')))
OUT = Path(os.environ.get('ORYON_OUTPUT_DIR', './mar-lab-output'))
OUT.mkdir(parents=True, exist_ok=True)
torch.manual_seed(SEED)
np.random.seed(SEED)
torch.set_num_threads(1)
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
assert 1 <= GROUPS <= N and 1 <= DIFF_STEPS <= T and IMAGE_COUNT >= 2
train_all = datasets.FashionMNIST(ROOT, train=True, download=True, transform=transforms.ToTensor())
test_all = datasets.FashionMNIST(ROOT, train=False, download=True, transform=transforms.ToTensor())
train = Subset(train_all, range(256)) if QUICK else train_all
test = Subset(test_all, range(64)) if QUICK else test_all
assert IMAGE_COUNT <= len(test)
train_loader = DataLoader(train, batch_size=BS, shuffle=True, num_workers=0)
train_ordered = DataLoader(train, batch_size=BS, shuffle=False, num_workers=0)
test_loader = DataLoader(test, batch_size=BS, shuffle=False, num_workers=0)
class VQVAE(nn.Module):
def __init__(self):
super().__init__()
width = 32 if QUICK else 64
self.encoder = nn.Sequential(nn.Conv2d(1, width, 4, stride=2, padding=1), nn.ReLU(),
nn.Conv2d(width, width, 4, stride=2, padding=1), nn.ReLU(),
nn.Conv2d(width, D, 3, padding=1))
self.codebook = nn.Embedding(K, D)
nn.init.uniform_(self.codebook.weight, -1 / K, 1 / K)
self.decoder = nn.Sequential(nn.Conv2d(D, width, 3, padding=1), nn.ReLU(),
nn.ConvTranspose2d(width, width, 4, stride=2, padding=1), nn.ReLU(),
nn.ConvTranspose2d(width, 1, 4, stride=2, padding=1), nn.Sigmoid())
def encode(self, x):
z = self.encoder(x).permute(0, 2, 3, 1).contiguous()
flat, e = z.reshape(-1, D), self.codebook.weight
dist = flat.square().sum(1, keepdim=True) + e.square().sum(1) - 2 * flat @ e.T
indices = dist.argmin(1).reshape(-1, 7, 7)
return z, self.codebook(indices), indices
def forward(self, x):
z, q, indices = self.encode(x)
straight = z + (q - z).detach()
rec = self.decode(straight.reshape(-1, N, D))
return rec, F.mse_loss(q, z.detach()), F.mse_loss(z, q.detach()), indices
def decode(self, latents):
return self.decoder(latents.reshape(-1, 7, 7, D).permute(0, 3, 1, 2))
class CausalPrior(nn.Module):
def __init__(self):
super().__init__()
width = 64 if QUICK else 128
layer = nn.TransformerEncoderLayer(width, 4, 4 * width, dropout=0.1,
batch_first=True, norm_first=True)
self.tokens, self.positions = nn.Embedding(K + 1, width), nn.Embedding(N, width)
self.network = nn.TransformerEncoder(layer, 1 if QUICK else 4, enable_nested_tensor=False)
self.head = nn.Linear(width, K)
def forward(self, prefix):
n = prefix.size(1)
x = self.tokens(prefix) + self.positions(torch.arange(n, device=prefix.device))[None]
mask = torch.triu(torch.ones(n, n, dtype=torch.bool, device=prefix.device), diagonal=1)
return self.head(self.network(x, mask=mask))
def shifted(codes):
return torch.cat([torch.full_like(codes[:, :1], K), codes[:, :-1]], 1)
class MAR(nn.Module):
def __init__(self):
super().__init__()
width = 64 if QUICK else 128
layer = nn.TransformerEncoderLayer(width, 4, 4 * width, dropout=0.1,
batch_first=True, norm_first=True)
self.projection = nn.Linear(D, width)
self.mask_token = nn.Parameter(torch.zeros(width))
self.positions = nn.Embedding(N, width)
self.network = nn.TransformerEncoder(layer, 1 if QUICK else 4, enable_nested_tensor=False)
self.time = nn.Embedding(T, width)
self.head = nn.Sequential(nn.Linear(D + 2 * width, width), nn.SiLU(),
nn.Linear(width, width), nn.SiLU(), nn.Linear(width, D))
def context(self, z, hidden):
projected = self.projection(z)
x = torch.where(hidden[..., None], self.mask_token, projected)
x = x + self.positions(torch.arange(N, device=z.device))[None]
return self.network(x)
def eps(self, zt, t, context):
return self.head(torch.cat((zt, self.time(t), context), dim=-1))
def extract(model, loader):
zs, qs, indices, images = [], [], [], []
model.eval()
with torch.no_grad():
for x, _ in loader:
z, q, ids = model.encode(x.to(DEVICE))
zs.append(z.reshape(-1, N, D).cpu())
qs.append(q.reshape(-1, N, D).cpu())
indices.append(ids.reshape(-1, N).cpu())
images.append(x)
return torch.cat(zs), torch.cat(qs), torch.cat(indices), torch.cat(images)
def stats(model, tensors, images):
squared, count = 0., 0
with torch.no_grad():
for start in range(0, len(tensors), BS):
rec = model.decode(tensors[start:start + BS].to(DEVICE)).cpu()
delta = rec - images[start:start + BS]
squared += delta.square().sum().item()
count += delta.numel()
return squared / count
def features(x):
return F.avg_pool2d(x, 4).flatten(1).double().numpy()
def frechet(x, y):
# Traza de la raíz PSD mediante producto simétrico, incluso si la covarianza es singular.
m, n = x.mean(0), y.mean(0)
a, b = np.cov(x, rowvar=False), np.cov(y, rowvar=False)
e, u = np.linalg.eigh((a + a.T) / 2)
root = (u * np.sqrt(np.maximum(e, 0))) @ u.T
c = root @ b @ root
cross = np.sqrt(np.maximum(np.linalg.eigvalsh((c + c.T) / 2), 0)).sum()
return float(max(0., np.sum((m - n) ** 2) + np.trace(a) + np.trace(b) - 2 * cross))
def mmd(x, y, bandwidth):
def kernel(a, b):
dsq = np.maximum(((a[:, None, :] - b[None, :, :]) ** 2).sum(-1), 0)
return np.exp(-dsq / (2 * bandwidth ** 2))
xx, yy, xy = kernel(x, x), kernel(y, y), kernel(x, y)
return float((xx.sum() - np.trace(xx)) / (len(x) * (len(x) - 1))
+ (yy.sum() - np.trace(yy)) / (len(y) * (len(y) - 1)) - 2 * xy.mean())
vq = VQVAE().to(DEVICE)
opt = torch.optim.Adam(vq.parameters(), lr=2e-3)
for epoch in range(EPOCHS_VQ):
vq.train()
total = 0.
for x, _ in train_loader:
x = x.to(DEVICE)
rec, codebook, commitment, _ = vq(x)
loss = F.mse_loss(rec, x) + codebook + .25 * commitment
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
total += loss.item() * len(x)
print('VQ época', epoch + 1, 'pérdida', round(total / len(train), 5), flush=True)
ztrain, qtrain, ctrain, xtrain = extract(vq, train_ordered)
ztest, qtest, ctest, xtest = extract(vq, test_loader)
mean = ztrain.mean((0, 1))
std = ztrain.std((0, 1), unbiased=False).clamp_min(1e-5)
assert torch.allclose((ztest[:2] - mean) / std * std + mean, ztest[:2], atol=1e-6)
mse_cont = stats(vq, ztest, xtest)
mse_vq = stats(vq, qtest, xtest)
print('Reconstrucción MSE test z_e / z_q:', mse_cont, mse_vq, flush=True)
prior = CausalPrior().to(DEVICE)
mar = MAR().to(DEVICE)
prior.eval()
mar.eval()
with torch.no_grad():
original = ctest[:2].to(DEVICE)
changed = original.clone()
changed[:, 20:] = (changed[:, 20:] + 1) % K
assert torch.allclose(prior(shifted(original))[:, :21], prior(shifted(changed))[:, :21], atol=1e-6)
z = ((ztest[:2] - mean) / std).to(DEVICE)
hidden = torch.zeros(2, N, dtype=torch.bool, device=DEVICE)
hidden[:, 10:30] = True
changed_z = z.clone()
changed_z[hidden] += 1000
assert torch.allclose(mar.context(z, hidden), mar.context(changed_z, hidden), atol=1e-6)
print('Pruebas de causalidad y ocultación: superadas', flush=True)
opt_prior = torch.optim.AdamW(prior.parameters(), lr=3e-4)
opt_mar = torch.optim.AdamW(mar.parameters(), lr=3e-4)
alpha = (1 - torch.linspace(1e-4, .02, T, device=DEVICE)).cumprod(0)
assert alpha[-1] < 1e-3
data = TensorDataset(ctrain, (ztrain - mean) / std)
loader = DataLoader(data, batch_size=BS, shuffle=True, num_workers=0)
prior_updates = mar_updates = 0
for epoch in range(EPOCHS_PRIOR):
prior.train()
mar.train()
ce_sum = diff_sum = ntok = nvalues = 0
for codes, z in loader:
codes, z = codes.to(DEVICE), z.to(DEVICE)
logits = prior(shifted(codes))
ce = F.cross_entropy(logits.reshape(-1, K), codes.reshape(-1))
opt_prior.zero_grad(set_to_none=True)
ce.backward()
assert prior.head.weight.grad is not None and torch.isfinite(prior.head.weight.grad).all()
assert prior.head.weight.grad.abs().sum() > 0
nn.utils.clip_grad_norm_(prior.parameters(), 1.)
opt_prior.step()
prior_updates += 1
# Al menos una posición oculta por imagen; nunca se usa z oculto en el contexto.
prob = torch.rand(len(z), 1, device=DEVICE)
hidden = torch.rand(len(z), N, device=DEVICE) < prob
hidden[:, 0] = True
context = mar.context(z, hidden)
target = z[hidden]
ts = torch.randint(T, (len(target),), device=DEVICE)
noise = torch.randn_like(target)
at = alpha[ts, None]
zt = at.sqrt() * target + (1 - at).sqrt() * noise
loss = F.mse_loss(mar.eps(zt, ts, context[hidden]), noise)
opt_mar.zero_grad(set_to_none=True)
loss.backward()
assert mar.head[-1].weight.grad is not None and torch.isfinite(mar.head[-1].weight.grad).all()
assert mar.head[-1].weight.grad.abs().sum() > 0
assert mar.projection.weight.grad is not None and torch.isfinite(mar.projection.weight.grad).all()
nn.utils.clip_grad_norm_(mar.parameters(), 1.)
opt_mar.step()
mar_updates += 1
ce_sum += ce.item() * codes.numel()
diff_sum += loss.item() * target.numel()
ntok += codes.numel()
nvalues += target.numel()
print('Prior época', epoch + 1, 'nats/código', round(ce_sum / ntok, 4),
'MSE ruido MAR', round(diff_sum / nvalues, 4), flush=True)
prior.eval()
mar.eval()
vq.eval()
with torch.no_grad():
ce_sum = ce_count = 0
for codes in ctest.split(BS):
codes = codes.to(DEVICE)
ce_sum += F.cross_entropy(prior(shifted(codes)).reshape(-1, K), codes.reshape(-1), reduction='sum').item()
ce_count += codes.numel()
test_ce = ce_sum / ce_count
gen = torch.Generator(device=DEVICE).manual_seed(2027)
loss_sum = value_count = 0
for zcpu in ztest.split(BS):
z = ((zcpu - mean) / std).to(DEVICE)
hidden = torch.rand(z.shape[:2], generator=gen, device=DEVICE) < .5
hidden[:, 0] = True
targets = z[hidden]
ts = torch.randint(T, (len(targets),), generator=gen, device=DEVICE)
noise = torch.randn(targets.shape, generator=gen, device=DEVICE)
at = alpha[ts, None]
loss_sum += F.mse_loss(mar.eps(at.sqrt() * targets + (1 - at).sqrt() * noise,
ts, mar.context(z, hidden)[hidden]), noise, reduction='sum').item()
value_count += targets.numel()
loss_test = loss_sum / value_count
# La evaluación del prior discreto y la del score no son verosimilitudes comparables.
torch.manual_seed(2028)
ids = torch.full((IMAGE_COUNT, 1), K, dtype=torch.long, device=DEVICE)
for i in range(N):
probs = prior(ids).softmax(-1)[:, -1]
ids = torch.cat((ids, torch.multinomial(probs, 1)), dim=1)
vq_samples = vq.decode(vq.codebook(ids[:, 1:]))
torch.manual_seed(2029)
known = torch.zeros(IMAGE_COUNT, N, D, device=DEVICE)
hidden = torch.ones(IMAGE_COUNT, N, dtype=torch.bool, device=DEVICE)
# Una permutación común fija simplifica la comparación de costes entre muestras.
order = torch.randperm(N, device=DEVICE)
schedule = torch.linspace(T - 1, 0, DIFF_STEPS, device=DEVICE).round().long()
assert torch.unique(schedule).numel() == DIFF_STEPS
assert schedule[0] == T - 1 and (DIFF_STEPS == 1 or schedule[-1] == 0)
head_calls = context_calls = 0
for group in torch.tensor_split(order, GROUPS):
if not len(group):
continue
context = mar.context(known, hidden)[:, group]
context_calls += 1
current = torch.randn(IMAGE_COUNT, len(group), D, device=DEVICE)
for j, t in enumerate(schedule):
time = torch.full((IMAGE_COUNT, len(group)), int(t), device=DEVICE, dtype=torch.long)
eps = mar.eps(current, time, context)
head_calls += 1
a = alpha[t]
x0 = (current - (1 - a).sqrt() * eps) / a.sqrt()
if j + 1 == len(schedule):
current = x0
else:
a_next = alpha[schedule[j + 1]]
current = a_next.sqrt() * x0 + (1 - a_next).sqrt() * eps
known[:, group] = current
hidden[:, group] = False
assert not hidden.any() and context_calls == GROUPS and head_calls == GROUPS * DIFF_STEPS
mar_samples = vq.decode(known * std.to(DEVICE) + mean.to(DEVICE))
test_features = features(xtest[:IMAGE_COUNT])
training_features = features(xtrain[:min(256, len(xtrain))])
assert frechet(test_features, test_features) < 1e-5
pair = ((training_features[:, None] - training_features[None, :]) ** 2).sum(-1)
positive = pair[np.triu_indices(len(pair), 1)]
positive = positive[positive > 0]
bandwidth = float(np.sqrt(np.median(positive))) if len(positive) else 1.
results = {}
for name, samples in [('vq_causal', vq_samples), ('mar_continuo', mar_samples)]:
x = samples.cpu().clamp(0, 1)
f = features(x)
results[name] = {'frechet_pool_7x7': frechet(f, test_features),
'mmd_rbf_insesgado': mmd(f, test_features, bandwidth)}
utils.save_image(x, OUT / f'{name}.png', nrow=min(8, IMAGE_COUNT))
utils.save_image(xtest[:IMAGE_COUNT], OUT / 'test.png', nrow=min(8, IMAGE_COUNT))
report = {'seed_model': SEED, 'seed_test_noise_masks': 2027,
'seed_vq_generation': 2028, 'seed_mar_generation': 2029,
'versions': {'python': platform.python_version(), 'torch': torch.__version__,
'numpy': np.__version__},
'quick': QUICK, 'train': len(train), 'test': len(test), 'sample_count': IMAGE_COUNT,
'vq_epochs': EPOCHS_VQ, 'prior_epochs': EPOCHS_PRIOR,
'parameters': {'vq': sum(p.numel() for p in vq.parameters()),
'vq_prior': sum(p.numel() for p in prior.parameters()),
'mar': sum(p.numel() for p in mar.parameters())},
'updates': {'vq_prior': prior_updates, 'mar': mar_updates},
'test_reconstruction_mse_z_e': mse_cont, 'test_reconstruction_mse_z_q': mse_vq,
'test_ce_nats_per_code': test_ce, 'test_mar_noise_mse': loss_test,
'train_bandwidth_rbf': bandwidth, 'evaluation': results,
'generation_calls': {'vq_transformer': N, 'mar_transformer': context_calls,
'mar_mlp': head_calls, 'batch_size_images': IMAGE_COUNT,
'mar_tokens_total_per_image': N, 'decoder_each_method': 1},
'warning': 'Fréchet calculado en píxeles reducidos, no FID; MMD insesgado puede ser negativo.'}
with (OUT / 'report.json').open('w', encoding='utf-8') as f:
json.dump(report, f, ensure_ascii=False, indent=2)
torch.save({'vq': vq.state_dict(), 'vq_prior': prior.state_dict(), 'mar': mar.state_dict(),
'latent_mean': mean, 'latent_std': std, 'report': report}, OUT / 'checkpoint.pt')
print(json.dumps(report, ensure_ascii=False, indent=2), flush=True)
if DEVICE.type == 'cuda':
torch.cuda.empty_cache()
npm run lab and open the connection link.Exercises
import torch
def diffusion_token_loss(model, clean, context, alpha_bar, noise):
pass
Generation order and conditional distribution type are different decisions. Comparing systems also requires counting representation, costs and evaluation protocol.