Latent diffusion and Diffusion Transformers
Study latent diffusion, first-stage compression and scaling, diffusion transformers and adaLN-Zero; train a DiT on precomputed latents and examine a text-to-image pipeline.
After this lesson you can
- Explain spatial compression and the first-stage reconstruction tradeoff.
- Calculate latent scaling and its effect on signal-to-noise ratio.
- Analyze patch token counts, attention cost and adaLN-Zero conditioning.
- Train and evaluate a diffusion transformer on precomputed latents.
- Identify the components and conventions of a text-to-image pipeline.
Before you start
- 19Perceptual and adversarial lossTwo-stage generationDiffusion U-NetClassifier-free guidancev-parameterizationNoise level conditioning
- 18Transformer blockCross-attention
- 16Vision TransformerPatch embedding
- 24Contrastive language-image pretraining
- 21Mixed-precision trainingActivation (gradient) checkpointing
Two problems, two models
An image contains 262,144 positions per channel. Diffusing directly over all of them forces the network to process many local details at each sampler evaluation. Latent diffusion divides the work: an autoencoder learns a compressed spatial representation and a generative model learns its distribution. To generate, first sample a latent and then decode it to pixels.
There is no universal boundary between perceptible and imperceptible bits. A small detail may be crucial, such as a letter or an eye. The first stage determines what information can be retained; the second learns to distribute the codes produced by that stage. Compression saves compute, but also changes the statistical problem and can discard details. Rombach and colleagues studied this division with perceptual losses and diffusion in spatial representations.
Spatial compression and fidelity
For an image, a first stage with spatial factor and latent channels produces, when and are divisible by , a representation of . The scalar-count ratio is
With and it is . This counts scalars, not bytes or file compression ratio: a floating-point latent channel and an 8-bit image channel do not necessarily occupy the same space. Nor does it claim the diffusion network is 48 times faster. Internal channels, attention, batch and architecture affect cost.
A first-stage autoencoder learns an encoder and decoder. A KL variant softly regularizes a continuous posterior; a VQ variant replaces vectors with entries from a discrete dictionary. In both cases perceptual and adversarial losses may favor visual details that squared error misses, but do not guarantee retention of small text or identity. PSNR compares pixel errors, LPIPS compares perceptual features, and reconstruction FID compares distributions: each metric answers a different question.
In figure 1 of LDM, the authors show a comparison with PSNR 27.4 for their autoencoder, 22.8 for DALL-E and 19.9 for VQGAN . Illustrated images come from DIV2K-val at ; the caption says PSNR and reconstruction FID are calculated on ImageNet-val. These are different models: the figures do not isolate the effect of changing in one network. Also evaluate real autoencoder reconstructions before attributing an artifact already present after encoding and decoding to the latent generator.
Scale is part of the model
Let be the first-stage output. If the diffusion model was trained with , decoding must reverse that convention and pass to the decoder. The latent scaling factor belongs to the checkpoint and pipeline: do not replace it with a constant from another family. Diffusers documents 0.18215 as the default AutoencoderKL configuration and explains scaling and descaling; check the actual model configuration.
For , with independent unit-variance noise, coordinate-wise SNR is
Multiplying the latent by multiplies its variance by and shifts log SNR by , for . An incorrect scale changes the signal–noise mixture seen by the network. If the terminal endpoint retains appreciable signal but we start from an independent normal, there is also a training–sampling mismatch. Whether variance 10 leaves much signal depends on the schedule: it is not true for every terminal endpoint.
From latents to tokens
A latent U-Net can incorporate text through cross-attention: image positions query embeddings from a text encoder. A Diffusion Transformer, or DiT, replaces that backbone with a transformer processing latent patches. For positions and patch , with divisible dimensions, there are tokens. Each patch is projected to hidden dimension and positional information is added.
Each head’s dense attention matrix contains entries. Reducing patch side from 4 to 2 in an latent quadruples , from 64 to 256, and multiplies attention pairs by 16. Total block cost also includes projections and MLP: it need not multiply by 16. Actual memory depends on implementation; attention that avoids materializing the full matrix changes that memory budget.
adaLN-Zero: a gate initially closed
Let be the combined time and class embedding and a per-token normalization. An adaLN-Zero block obtains shifts, scales and gates for the two residual branches from . Schematically,
Gates are broadcast over tokens and act per channel. If , exactly , even if and are nonzero. For a loss , the derivative with respect to each gate is the product of the gradient arriving at the residual sum and its branch output, summed over tokens sharing that gate. Gates can therefore receive gradients in the first step while branch parameters receive zero gradient through those closed branches. The actual gradient can be zero for other reasons, such as zero loss gradient or branch output. If an additional output layer is also zero-initialized, its first-step consequences must be analyzed separately.
Peebles and Xie compare several conditionings and use adaLN-Zero in their DiTs. Their table 1 specifies DiT-S with 12 blocks, dimension 384 and 6 heads. On ImageNet, guided DiT-XL/2 reaches FID-50K 2.27 after 7 million steps according to the study; that figure belongs to their model, data and protocol, not this lesson’s short run.
Text, modalities and resolution
A text-to-image pipeline typically includes tokenizer, text encoder, denoiser, scheduler and latent decoder. Text becomes embeddings, the denoiser predicts a quantity such as noise or velocity for each level, and the scheduler updates the latent. Finally, the decoder receives the latent at its expected scale. Replacing a scheduler requires respecting parameterization, schedule and expected inputs; classifier-free guidance combines branches as in the previous lesson, with a specified scale convention.
Text encoders and autoencoder can be frozen while training the second stage to keep a stable representation and save gradient and optimizer memory. This is a design choice, not a law: they can be jointly fine-tuned if objective, data and budget justify it. The MMDiT architecture of Esser and colleagues retains modality-specific parameters and exchanges information through joint attention; it is not identical to a U-Net with cross-attention.
When resolution changes, the distribution of spatial signals changes too. The same work studies shifting the time distribution and uses a 3.0 shift at in its experiment. Its justification includes a simplified model of constant images; this is not a universal formula for every dataset or scheduler. Modern variants may use flows instead of VP noise prediction: do not swap their solvers without reviewing equations.
Precompute without hiding the budget
Precomputing latents with the frozen autoencoder avoids running it at every DiT update. Save scale, resolution, checkpoint and whether codes are posterior means or samples: repeating one fixed sample changes training variation relative to resampling. Subsequent training needs memory for weights, gradients, optimizer states, activations and attention; mixed precision, microbatches, gradient accumulation and checkpointing can reduce peak memory but must be checked on the actual GPU. Precomputing consumes disk and does not make the first pass free.
Lab: patches and adaLN-Zero
The first check requires exactly inverting each patch. For the second, the condition enters through a projection whose weights start at zero. Calculate gradients of its gate columns using the chain rule and check against central differences; scale and shift columns have zero initial gradient. The linear loss and data are a small test, not training.
"""Parches reversibles y bloque DiT pequeño con adaLN-Zero en NumPy."""
import numpy as np
rng = np.random.default_rng(2210)
def patchify(x, p):
if x.ndim != 4 or p < 1:
raise ValueError('Se espera un lote NCHW y un parche positivo')
b, c, h, w = x.shape
if h % p or w % p:
raise ValueError('Las dimensiones espaciales deben dividirse entre p')
return x.reshape(b,c,h//p,p,w//p,p).transpose(0,2,4,3,5,1).reshape(b,(h//p)*(w//p),p*p*c)
def unpatchify(tokens, p, h, w, c):
b, n, d = tokens.shape
if p < 1 or h % p or w % p or n != h//p*(w//p) or d != p*p*c:
raise ValueError('Forma incompatible con el tamaño del latente')
return tokens.reshape(b,h//p,w//p,p,p,c).transpose(0,5,1,3,2,4).reshape(b,c,h,w)
latent = rng.normal(size=(2,4,8,8))
for p in (1,2,4,8):
tokens = patchify(latent,p)
assert np.array_equal(unpatchify(tokens,p,8,8,4),latent)
print(f'p={p}: {tokens.shape[1]} tokens de dimensión {tokens.shape[2]}, inversión exacta')
def layernorm(x):
mu = x.mean(axis=-1,keepdims=True)
return (x-mu)/np.sqrt(((x-mu)**2).mean(axis=-1,keepdims=True)+1e-5)
def attention(x, weights):
q, k, v = (x @ a for a in weights[:3])
logits = q @ k.swapaxes(-1,-2) / np.sqrt(x.shape[-1])
logits -= logits.max(axis=-1,keepdims=True)
prob = np.exp(logits); prob /= prob.sum(axis=-1,keepdims=True)
return (prob @ v) @ weights[3]
def mlp(x, weights):
return np.tanh(x @ weights[0]) @ weights[1]
def dit_block(x, condition, modulation, weights):
# La salida de la proyección se agrupa como shift, scale y gate por rama.
shift_a, scale_a, gate_a, shift_m, scale_m, gate_m = np.split(condition @ modulation,6,axis=-1)
a = attention(layernorm(x)*(1+scale_a[:,None,:])+shift_a[:,None,:],weights[:4])
y = x + gate_a[:,None,:]*a
m = mlp(layernorm(y)*(1+scale_m[:,None,:])+shift_m[:,None,:],weights[4:])
return y+gate_m[:,None,:]*m
b,n,d = 2,5,4
x = rng.normal(size=(b,n,d)); condition = rng.normal(size=(b,d))
weights = [rng.normal(scale=.3,size=(d,d)) for _ in range(4)]
weights += [rng.normal(scale=.3,size=(d,2*d)),rng.normal(scale=.3,size=(2*d,d))]
modulation = np.zeros((d,6*d))
y = dit_block(x,condition,modulation,weights)
assert np.array_equal(y,x)
# Pérdida lineal elegida para que las derivadas de las compuertas sean visibles.
probe = rng.normal(size=x.shape)
a = attention(layernorm(x),weights[:4]); m = mlp(layernorm(x),weights[4:])
gate_grad = np.concatenate(((probe*a).sum(axis=1),(probe*m).sum(axis=1)),axis=1)
expected = np.zeros_like(modulation)
expected[:,2*d:3*d] = condition.T @ gate_grad[:,:d]
expected[:,5*d:6*d] = condition.T @ gate_grad[:,d:]
def loss(matrix):
return float((probe*dit_block(x,condition,matrix,weights)).sum())
eps = 1e-5
numeric = np.zeros_like(modulation)
for i in range(d):
for j in range(6*d):
delta = np.zeros_like(modulation); delta[i,j] = eps
numeric[i,j] = (loss(modulation+delta)-loss(modulation-delta))/(2*eps)
error = np.max(np.abs(numeric-expected))
assert error < 1e-8
assert np.linalg.norm(expected[:,2*d:3*d]) > 0 and np.linalg.norm(expected[:,5*d:6*d]) > 0
print(f'Bloque inicial: identidad exacta; error máximo de gradiente {error:.2e}')
print('Normas de gradientes de compuertas:', *(f'{np.linalg.norm(expected[:,s:s+d]):.6f}' for s in (2*d,5*d)))
print('Las columnas de escala y desplazamiento no reciben gradiente en este primer paso.')Local lab: DiT on precomputed latents
Encode CIFAR-10 with the posterior mean of the frozen sd-vae-ft-mse VAE and save scaled latents and labels before training. Here images are enlarged from 32 to 128 pixels with bicubic interpolation, without claiming added detail. The VAE reduces by 8 and produces latents; the factor is read from its configuration and applied during encoding and reversed during decoding. The VAE is evaluated separately from diffusion and never updated.
Full mode uses the DiT-S/2 core of Peebles and Xie: 12 blocks, dimension 384, six heads, patches and adaLN-Zero. This implementation uses ten CIFAR classes, one null label and predicts only ; it does not include the learned-variance head or the original model’s thousand ImageNet identifiers. It has 32,478,736 parameters. Blocks start exactly as identity and their gate gradients are tested. The final projector also starts at zero, so gradients reaching the backbone can appear after the projector’s first update. Training uses AMP, accumulation, activation checkpointing and EMA with microbatches of two; the reader can adjust ORYON_UPDATES and ORYON_TRAIN_COUNT. The checkpoint saves optimizer and EMA for inspection, but the cell does not resume automatically.
Held-out test images measure reconstruction and evaluate generated samples with the same labels. FID uses clean-fid 0.1.35 InceptionV3W and lesson 18’s bicubic RGB protocol. Reconstruction FID is a diagnostic reference for the VAE stage, not a universal mathematical bound on generative FID. Full mode defaults to 2048 train images, 128 test images and 20,000 attempts; these are teaching choices, not the paper’s training or FID-50K. Upscaled CIFAR and finite sampling do not represent ImageNet. Save latents-train.pt, latents-test.pt, dit.pt, features, comparison.png and a report with seeds, parameters and scales.
Install PyTorch, torchvision, NumPy, SciPy, Pillow, compatible diffusers and clean-fid==0.1.35. ORYON_VAE accepts the VAE identifier or local snapshot path; set ORYON_OFFLINE=1 if already available and downloads should be prevented. Set the Inception file with ORYON_INCEPTION_PT; ORYON_DATA_ROOT and ORYON_OUTPUT_DIR control directories. The VAE model card declares MIT licensing; also check the license and conditions for the data used.
ORYON_QUICK=1 uses 16 train and 8 test images, a reduced two-block DiT and two updates, and accepts ORYON_CIFAR_PARQUET with pyarrow to reuse local data. In an actual check run, VAE scale was 0.18215 and aggregate train latent variance 0.84941; reconstruction FID was 84.7821 and generative FID 455.8397 using only eight images. These figures are highly biased and two steps do not demonstrate image learning. A separate real forward, backward and AdamW step of full DiT with microbatch two, AMP, EMA and checkpointing was also checked; peak CUDA tensor memory in that test was about 790 MiB, not a memory guarantee for other sizes or environments. ORYON_VERIFY_FULL=1 repeats that check without starting training.
"""Entrenamiento DiT sobre latentes precomputados, CIFAR y VAE SD."""
import copy, hashlib, io, json, math, os
from pathlib import Path
os.environ.setdefault('OPENBLAS_NUM_THREADS','1')
import numpy as np
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
from torch.utils.data import Dataset, DataLoader, Subset, TensorDataset
from torchvision import datasets, transforms
from torchvision.utils import save_image
from PIL import Image
from diffusers import AutoencoderKL
from huggingface_hub import snapshot_download
from cleanfid.inception_torchscript import InceptionV3W
from cleanfid.resize import build_resizer
torch.set_num_threads(2)
def timestep_embedding(t, dim=256):
half=dim//2
frequency=torch.exp(-math.log(10000)*torch.arange(half,device=t.device,dtype=torch.float32)/half)
phase=t.float()[:,None]*frequency[None]
return torch.cat([phase.cos(),phase.sin()],dim=1)
def position_embedding(side,dim):
if dim%4: raise ValueError('La dimensión debe ser múltiplo de cuatro')
y,x=torch.meshgrid(torch.arange(side),torch.arange(side),indexing='ij')
freq=torch.exp(-math.log(10000)*torch.arange(dim//4,dtype=torch.float32)/(dim//4))
px=x.reshape(-1,1)*freq[None];py=y.reshape(-1,1)*freq[None]
return torch.cat([px.sin(),px.cos(),py.sin(),py.cos()],dim=1)[None]
def modulate(x,shift,scale):
return x*(1+scale[:,None,:])+shift[:,None,:]
class Attention(nn.Module):
def __init__(self,width,heads):
super().__init__()
if width%heads:raise ValueError('Dimensión incompatible con cabezas')
self.heads=heads
self.qkv=nn.Linear(width,3*width,bias=True)
self.proj=nn.Linear(width,width)
def forward(self,x):
B,N,D=x.shape; d=D//self.heads
q,k,v=self.qkv(x).reshape(B,N,3,self.heads,d).permute(2,0,3,1,4).unbind(0)
y=F.scaled_dot_product_attention(q,k,v).transpose(1,2).reshape(B,N,D)
return self.proj(y)
class DiTBlock(nn.Module):
def __init__(self,width,heads):
super().__init__()
self.norm1=nn.LayerNorm(width,elementwise_affine=False,eps=1e-6)
self.norm2=nn.LayerNorm(width,elementwise_affine=False,eps=1e-6)
self.attn=Attention(width,heads)
self.mlp=nn.Sequential(nn.Linear(width,4*width),nn.GELU(approximate='tanh'),nn.Linear(4*width,width))
self.mod=nn.Sequential(nn.SiLU(),nn.Linear(width,6*width))
nn.init.zeros_(self.mod[-1].weight);nn.init.zeros_(self.mod[-1].bias)
def forward(self,x,c):
sh1,sc1,gate1,sh2,sc2,gate2=self.mod(c).chunk(6,dim=1)
x=x+gate1[:,None,:]*self.attn(modulate(self.norm1(x),sh1,sc1))
return x+gate2[:,None,:]*self.mlp(modulate(self.norm2(x),sh2,sc2))
class DiT(nn.Module):
def __init__(self,side=16,width=384,depth=12,heads=6,classes=10,patch=2,checkpoint_blocks=True):
super().__init__()
if side%patch: raise ValueError('El latente debe dividirse en parches enteros')
self.width,self.side,self.patch,self.checkpoint_blocks=width,side,patch,checkpoint_blocks
self.patchify=nn.Conv2d(4,width,kernel_size=patch,stride=patch)
self.register_buffer('pos',position_embedding(side//patch,width),persistent=True)
self.time=nn.Sequential(nn.Linear(256,width),nn.SiLU(),nn.Linear(width,width))
self.label=nn.Embedding(classes+1,width)
self.blocks=nn.ModuleList([DiTBlock(width,heads) for _ in range(depth)])
self.norm=nn.LayerNorm(width,elementwise_affine=False,eps=1e-6)
self.final_mod=nn.Sequential(nn.SiLU(),nn.Linear(width,2*width))
self.final=nn.Linear(width,patch*patch*4)
nn.init.zeros_(self.final_mod[-1].weight);nn.init.zeros_(self.final_mod[-1].bias)
nn.init.zeros_(self.final.weight);nn.init.zeros_(self.final.bias)
def forward(self,z,t,labels):
x=self.patchify(z).flatten(2).transpose(1,2)+self.pos
c=self.time(timestep_embedding(t))+self.label(labels)
for block in self.blocks:
if self.training and self.checkpoint_blocks:
x=torch.utils.checkpoint.checkpoint(block,x,c,use_reentrant=False)
else:x=block(x,c)
shift,scale=self.final_mod(c).chunk(2,dim=1)
x=self.final(modulate(self.norm(x),shift,scale))
B=x.shape[0];n=self.side//self.patch;p=self.patch
return x.reshape(B,n,n,p,p,4).permute(0,5,1,3,2,4).reshape(B,4,self.side,self.side)
class CifarParquet(Dataset):
def __init__(self,folder,split,count):
import pyarrow.parquet as pq
self.rows=[];self.used=[]
for path in sorted(Path(folder).glob(f'{split}-*.parquet')):
self.used.append(str(path))
for batch in pq.ParquetFile(path).iter_batches(batch_size=128,columns=['img','label']):
for row in batch.to_pylist():
self.rows.append((row['img']['bytes'],int(row['label'])))
if len(self.rows)>=count:break
if len(self.rows)>=count:break
if len(self.rows)>=count:break
if len(self.rows)<count:raise ValueError('No hay suficientes imágenes en parquet')
def __len__(self):return len(self.rows)
def __getitem__(self,index):
image,label=self.rows[index]
with Image.open(io.BytesIO(image)) as img:
return transforms.ToTensor()(img.convert('RGB')),label
def get_cifar(root,quick,parquet,n_train,n_test):
if parquet:
if not quick:raise ValueError('El parquet es solo para verificación corta')
train=CifarParquet(parquet,'train',n_train);test=CifarParquet(parquet,'test',n_test)
return train,test,{'source':'parquet CIFAR-10','train':'primeras filas','test':'primeras filas',
'files':[{'name':Path(p).name,'sha256':sha256(p)} for p in train.used+test.used]}
train=datasets.CIFAR10(root,train=True,download=True,transform=transforms.ToTensor())
test=datasets.CIFAR10(root,train=False,download=True,transform=transforms.ToTensor())
ids=torch.randperm(len(train),generator=torch.Generator().manual_seed(2210))[:n_train].tolist()
return Subset(train,ids),Subset(test,range(n_test)),{'source':'torchvision CIFAR-10',
'train':'permutación con semilla 2210','test':'primeras filas'}
def sha256(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()
@torch.no_grad()
def encode_data(vae,data,batch_size,device,scale,keep_images=True):
latents=[];labels=[];real=[];recon=[]
for images,y in DataLoader(data,batch_size=batch_size,shuffle=False,num_workers=0):
images=F.interpolate(images.to(device),size=(128,128),mode='bicubic',align_corners=False).clamp(0,1)
z=vae.encode(images*2-1).latent_dist.mode()*scale
latents.append(z.cpu().float());labels.append(y)
if keep_images:
r=vae.decode(z/scale).sample
real.append(images.cpu());recon.append(((r+1)/2).cpu())
return torch.cat(latents),torch.cat(labels),torch.cat(real) if keep_images else None,torch.cat(recon) if keep_images else None
def image_features(images,inception,device):
resize=build_resizer('clean');out=[]
with torch.inference_mode():
for i in range(0,len(images),4):
pixels=(images[i:i+4].clamp(0,1)*255).round().to(torch.uint8)
arrays=pixels.permute(0,2,3,1).cpu().numpy()
resized=np.stack([resize(a).transpose(2,0,1) for a in arrays])
out.append(inception(torch.from_numpy(resized).to(device)).cpu().numpy())
return np.concatenate(out)
def fid(real,fake):
a,b=np.asarray(real,np.float64),np.asarray(fake,np.float64)
x,y=a-a.mean(0),b-b.mean(0)
cross=np.linalg.svd(x@y.T,compute_uv=False).sum()/math.sqrt((len(x)-1)*(len(y)-1))
value=np.square(a.mean(0)-b.mean(0)).sum()+(x*x).sum()/(len(x)-1)+(y*y).sum()/(len(y)-1)-2*cross
if value < -1e-7:raise ValueError('FID negativo fuera de tolerancia')
return max(float(value),0.)
def verify(device):
torch.manual_seed(2201)
block=DiTBlock(32,4).to(device)
x=torch.randn(2,5,32,device=device);c=torch.randn(2,32,device=device)
result=block(x,c)
assert torch.equal(result,x)
result.square().sum().backward()
bias_grad=block.mod[-1].bias.grad
assert bias_grad is not None and bias_grad[64:96].abs().sum()>0 and bias_grad[160:192].abs().sum()>0
network=DiT(side=16,width=48,depth=2,heads=4,checkpoint_blocks=True).to(device)
z=torch.randn(2,4,16,16,device=device)
output=network(z,torch.tensor([5,10],device=device),torch.tensor([0,1],device=device))
assert output.shape==z.shape and torch.count_nonzero(output)==0
output.square().mean().backward()
with torch.device('meta'):
full=DiT(side=16,width=384,depth=12,heads=6,checkpoint_blocks=False)
params=sum(p.numel() for p in full.parameters())
assert 30_000_000<params<40_000_000
print(f'Controles: identidad adaLN-Zero, gradiente de compuertas, formas; DiT-S/2 {params:,} parámetros.',flush=True)
del block,network,full,x,c,z,output
if device.type=='cuda':torch.cuda.empty_cache()
return params
def verify_full(device):
if device.type!='cuda':raise ValueError('La prueba de memoria completa requiere CUDA')
torch.manual_seed(2202)
torch.cuda.reset_peak_memory_stats(device)
model=DiT(side=16,width=384,depth=12,heads=6,checkpoint_blocks=True).to(device).train()
ema=copy.deepcopy(model).requires_grad_(False)
optimizer=torch.optim.AdamW(model.parameters(),lr=.0001)
scaler=torch.amp.GradScaler('cuda')
z=torch.randn(2,4,16,16,device=device);target=torch.randn_like(z)
with torch.autocast(device_type='cuda',dtype=torch.float16):
loss=F.mse_loss(model(z,torch.tensor([10,15],device=device),torch.tensor([3,7],device=device)).float(),target)
scaler.scale(loss).backward();scaler.unscale_(optimizer)
assert all(torch.isfinite(p.grad).all() for p in model.parameters() if p.grad is not None)
scaler.step(optimizer);scaler.update()
print(f'DiT-S/2 completo: paso forward/backward/AdamW, lote 2, pico CUDA {torch.cuda.max_memory_allocated()/2**20:.1f} MiB.',flush=True)
del model,ema,optimizer,scaler,z,target,loss
torch.cuda.empty_cache()
@torch.no_grad()
def sample(ema,bars,labels,steps,seed,device):
T=len(bars)-1;ids=np.rint(np.linspace(T,0,steps+1)).astype(int)
if np.any(np.diff(ids)>=0):raise ValueError('Demasiados pasos de muestreo')
gen=torch.Generator(device=device).manual_seed(seed)
out=[]
for start in range(0,len(labels),4):
y=labels[start:start+4].to(device)
x=torch.randn((len(y),4,16,16),device=device,generator=gen)
for t,s in zip(ids[:-1],ids[1:]):
ts=torch.full((len(y),),int(t),device=device,dtype=torch.long)
eps=ema(x,ts,y)
bt,bs=float(bars[t]),float(bars[s])
x0=(x-math.sqrt(1-bt)*eps)/math.sqrt(bt)
x=math.sqrt(bs)*x0+math.sqrt(1-bs)*eps
out.append(x.cpu())
return torch.cat(out)
@torch.no_grad()
def decode_latents(vae,latents,device,scale):
result=[]
for start in range(0,len(latents),4):
output=vae.decode(latents[start:start+4].to(device)/scale).sample
result.append(((output+1)/2).cpu())
return torch.cat(result)
def main():
quick=os.environ.get('ORYON_QUICK')=='1'
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'dispositivo {device}; quick {quick}',flush=True)
params=verify(device)
if os.environ.get('ORYON_VERIFY_FULL')=='1':
verify_full(device)
return
n_train,n_test=(16,8) if quick else (int(os.environ.get('ORYON_TRAIN_COUNT','2048')),
int(os.environ.get('ORYON_EVAL_COUNT','128')))
if not 8<=n_train<=50000 or not 2<=n_test<=1000:raise ValueError('Tamaños de muestra inválidos')
dataset_train,dataset_test,selection=get_cifar(os.environ.get('ORYON_DATA_ROOT','./data'),quick,
os.environ.get('ORYON_CIFAR_PARQUET'),n_train,n_test)
output=Path(os.environ.get('ORYON_OUTPUT_DIR','./dit-latent'));output.mkdir(parents=True,exist_ok=True)
vae_id=os.environ.get('ORYON_VAE','stabilityai/sd-vae-ft-mse')
vae_dir=Path(vae_id)
if not vae_dir.is_dir():
vae_dir=Path(snapshot_download(vae_id,local_files_only=os.environ.get('ORYON_OFFLINE')=='1',
allow_patterns=['config.json','diffusion_pytorch_model.safetensors']))
vae_weights=vae_dir/'diffusion_pytorch_model.safetensors'
vae_config=vae_dir/'config.json'
if not vae_weights.is_file() or not vae_config.is_file():
raise ValueError('El snapshot VAE debe contener config.json y diffusion_pytorch_model.safetensors')
vae_weight_hash,vae_config_hash=sha256(vae_weights),sha256(vae_config)
vae=AutoencoderKL.from_pretrained(str(vae_dir),local_files_only=True,use_safetensors=True).to(device).eval().requires_grad_(False)
scale=float(vae.config.scaling_factor)
if not math.isfinite(scale) or scale<=0:raise ValueError('Escala VAE inválida')
train_z,train_labels,_,_=encode_data(vae,dataset_train,4,device,scale,False)
test_z,test_labels,real,recon=encode_data(vae,dataset_test,4,device,scale,True)
assert train_z.shape==(n_train,4,16,16) and test_z.shape==(n_test,4,16,16)
assert torch.isfinite(train_z).all() and torch.isfinite(recon).all()
torch.save({'latents_scaled':train_z,'labels':train_labels,'vae':vae_id,'vae_weights_sha256':vae_weight_hash,'scale':scale,
'posterior':'mode','split':'CIFAR-10 train'},output/'latents-train.pt')
torch.save({'latents_scaled':test_z,'labels':test_labels,'vae':vae_id,'vae_weights_sha256':vae_weight_hash,'scale':scale,
'posterior':'mode','split':'CIFAR-10 test'},output/'latents-test.pt')
print(f'Latentes precomputados: train={n_train}, test={n_test}, escala={scale:.5f}, '
f'varianza agregada train={train_z.var().item():.5f}.',flush=True)
vae.to('cpu')
if device.type=='cuda':torch.cuda.empty_cache()
torch.manual_seed(2212)
width,depth,heads=(48,2,4) if quick else (384,12,6)
model=DiT(16,width,depth,heads,checkpoint_blocks=True).to(device)
ema=copy.deepcopy(model).eval().requires_grad_(False)
optimizer=torch.optim.AdamW(model.parameters(),lr=.0001)
scaler=torch.amp.GradScaler('cuda',enabled=device.type=='cuda')
loader=DataLoader(TensorDataset(train_z,train_labels),batch_size=2,shuffle=True,drop_last=True,
generator=torch.Generator().manual_seed(2213),num_workers=0)
batches=iter(loader);rng=torch.Generator(device=device).manual_seed(2214)
T=20 if quick else 1000;steps=2 if quick else int(os.environ.get('ORYON_UPDATES','20000'))
accumulation=1 if quick else 4
if steps<1:raise ValueError('ORYON_UPDATES debe ser positivo')
bars=np.r_[1.,np.cumprod(1-np.linspace(.0001,.02,T,dtype=np.float64))]
bars_tensor=torch.as_tensor(bars,device=device,dtype=torch.float32)
effective=skipped=dropped=seen=0;history=[]
for attempt in range(1,steps+1):
optimizer.zero_grad(set_to_none=True);average=0.
for _ in range(accumulation):
try:z,y=next(batches)
except StopIteration:batches=iter(loader);z,y=next(batches)
z=z.to(device);y=y.to(device)
dropped_mask=torch.rand((len(y),),device=device,generator=rng)<.1
dropped+=int(dropped_mask.sum());seen+=len(y);y=torch.where(dropped_mask,10,y)
t=torch.randint(1,T+1,(len(z),),generator=rng,device=device)
noise=torch.randn(z.shape,device=device,generator=rng)
b=bars_tensor[t,None,None,None];zt=b.sqrt()*z+(1-b).sqrt()*noise
with torch.autocast(device_type=device.type,dtype=torch.float16,enabled=device.type=='cuda'):
prediction=model(zt,t,y);loss=F.mse_loss(prediction.float(),noise.float())
if not torch.isfinite(loss):raise FloatingPointError('Pérdida no finita')
scaler.scale(loss/accumulation).backward();average+=loss.item()/accumulation
scaler.unscale_(optimizer);torch.nn.utils.clip_grad_norm_(model.parameters(),1.)
old=scaler.get_scale();scaler.step(optimizer);scaler.update()
if scaler.get_scale()<old:skipped+=1
else:
effective+=1;decay=min(.9999,(1+effective)/(10+effective))
with torch.no_grad():
for avg,current in zip(ema.parameters(),model.parameters(),strict=True):avg.mul_(decay).add_(current,alpha=1-decay)
if attempt in (1,steps) or attempt%500==0:
history.append({'attempt':attempt,'loss':average,'effective':effective,'skipped':skipped})
print(f'Intento {attempt}: pérdida {average:.6f}, efectivos {effective}, saltados {skipped}',flush=True)
if effective==0:raise RuntimeError('Ningún paso efectivo de entrenamiento')
checkpoint={'model':model.state_dict(),'ema':ema.state_dict(),'optimizer':optimizer.state_dict(),
'scaler':scaler.state_dict(),'width':width,'depth':depth,'heads':heads,'T':T,
'vae':vae_id,'scale':scale,'effective':effective,'history':history}
ckpt=output/'dit.pt';torch.save(checkpoint,ckpt)
restored=torch.load(ckpt,map_location='cpu',weights_only=True)
assert torch.equal(restored['ema']['final.weight'],ema.final.weight.cpu())
del model,optimizer,scaler,checkpoint,restored,batches,loss,prediction
ema.eval().checkpoint_blocks=False
sampled=sample(ema,bars,test_labels,10 if quick else 30,2215,device)
assert torch.isfinite(sampled).all()
del ema
if device.type=='cuda':torch.cuda.empty_cache()
vae.to(device);generated=decode_latents(vae,sampled,device,scale)
save_image(torch.cat([real[:4],recon[:4],generated[:4]]).clamp(0,1),output/'comparison.png',nrow=4)
del vae
if device.type=='cuda':torch.cuda.empty_cache()
inception_path=Path(os.environ['ORYON_INCEPTION_PT'])
if inception_path.name!='inception-2015-12-05.pt' or not inception_path.is_file():raise ValueError('Ruta Inception inválida')
inception=InceptionV3W(str(inception_path.parent),download=False,resize_inside=False).to(device).eval()
fr=image_features(real,inception,device);frec=image_features(recon,inception,device);fg=image_features(generated,inception,device)
fid_rec=fid(fr,frec);fid_gen=fid(fr,fg)
np.savez_compressed(output/'features.npz',reference=fr,reconstruction=frec,generated=fg)
report={'quick':quick,'dataset':selection,'vae':vae_id,'vae_weights_sha256':vae_weight_hash,
'vae_config_sha256':vae_config_hash,'vae_scale':scale,'latent_posterior':'mode',
'input_resize':'CIFAR 32 a 128, bicúbico','latent_shape':[4,16,16],'train_count':n_train,
'test_count':n_test,'full_model_parameters':params,'width':width,'depth':depth,'heads':heads,
'patch':2,'learn_sigma':False,'train_attempts':steps,'effective':effective,'skipped_amp':skipped,
'history':history,'label_dropout_probability':.1,'labels_dropped':dropped,'labels_seen':seen,
'latent_train_variance':float(train_z.var()),'sample_seed':2215,
'seeds':{'data_selection':2210,'initialization':2212,'data_shuffle':2213,
'noise_timestep_dropout':2214,'sampling':2215},'fid_reconstruction':fid_rec,
'fid_generated':fid_gen,'inception_sha256':sha256(inception_path),'checkpoint_sha256':sha256(ckpt),
'fid_protocol':'InceptionV3W clean-fid 0.1.35, RGB uint8, PIL bicúbico 299',
'warning':'FID con muestras escasas sesgado; reconstrucción no es cota matemática universal.'}
(output/'report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
print(f'FID reconstrucción={fid_rec:.4f}; FID generación={fid_gen:.4f}. Tamaño pequeño: no es benchmark.',flush=True)
del inception
if device.type=='cuda':torch.cuda.empty_cache()
if __name__=='__main__':main()
npm run lab and open the connection link.Local lab: take apart a text-to-image pipeline
The next cell separates tokenizer, frozen text encoder, conditional U-Net, scheduler and VAE. It uses DPMSolverMultistepScheduler with DPM-Solver++ 2M and combines branches as in the previous lesson: ; the usual pipeline scale is . Compare 15 and 30 steps and or , always with the same initial noise. U-Net calls and processed examples are counted and pixel MSE against the first case is measured; this difference is not a quality metric. If the pipeline has a safety checker, it remains in use; the report records its presence. Images and report-pipeline.json are saved in ORYON_OUTPUT_DIR.
Install diffusers, transformers, accelerate, PyTorch and model requirements; ORYON_SD_MODEL can select a local path or accessible identifier. By default Stable Diffusion 1.5 is proposed; its model card declares CreativeML OpenRAIL-M and describes its data and restrictions: review it before using the weights. The first full-model download may take several gigabytes; ORYON_OFFLINE=1 requires it locally. The cell uses fp16 on CUDA and attention and VAE slicing to reduce peak memory; actual resolution and model also matter.
The full pipeline was not cached on this machine, so we did not measure its images or quality. With ORYON_SMOKE_ONLY=1, or ORYON_QUICK=1 without selecting a model, run a from-scratch check with tiny diffusers conditional U-Net and VAE, random weights, synthetic embeddings, DPM-Solver++ and double-batch guidance. Image shape, finite values, repeatability and counts are checked. This demonstrates that pieces connect; it does not verify Stable Diffusion download or quality.
"""Desmonta un pipeline texto-imagen; el control reducido no contiene pesos aprendidos."""
import json, os
from pathlib import Path
os.environ.setdefault('OPENBLAS_NUM_THREADS','1')
import numpy as np
import torch
from diffusers import DPMSolverMultistepScheduler
torch.set_num_threads(2)
@torch.no_grad()
def manual_sample(unet,scheduler,cond,uncond,initial,steps,w):
if w<0:raise ValueError('w debe ser no negativo')
scheduler.set_timesteps(steps,device=initial.device)
x=initial.clone()*scheduler.init_noise_sigma
calls=processed=0
for t in scheduler.timesteps:
model_x=scheduler.scale_model_input(x,t)
if w==0:
eps=unet(model_x,t,encoder_hidden_states=cond).sample
processed+=len(x)
else:
both=unet(torch.cat([model_x,model_x]),t,
encoder_hidden_states=torch.cat([uncond,cond])).sample
null,positive=both.chunk(2)
eps=positive+w*(positive-null)
processed+=2*len(x)
calls+=1
x=scheduler.step(eps,t,x).prev_sample
return x,calls,processed
def smoke_test():
# Componentes diffusers diminutos de pesos aleatorios, no modelos aprendidos.
from diffusers import UNet2DConditionModel, AutoencoderKL
torch.manual_seed(2204)
model=UNet2DConditionModel(sample_size=8,in_channels=4,out_channels=4,
down_block_types=('DownBlock2D','CrossAttnDownBlock2D'),
up_block_types=('CrossAttnUpBlock2D','UpBlock2D'),
block_out_channels=(16,32),layers_per_block=1,cross_attention_dim=16,
attention_head_dim=4,norm_num_groups=4).eval()
vae=AutoencoderKL(in_channels=3,out_channels=3,latent_channels=4,sample_size=16,
down_block_types=('DownEncoderBlock2D','DownEncoderBlock2D'),
up_block_types=('UpDecoderBlock2D','UpDecoderBlock2D'),
block_out_channels=(16,32),layers_per_block=1,norm_num_groups=4).eval()
cond=torch.ones(1,3,16);null=torch.zeros_like(cond)
initial=torch.randn((1,4,8,8),generator=torch.Generator().manual_seed(2205))
def scheduler():return DPMSolverMultistepScheduler(num_train_timesteps=40,algorithm_type='dpmsolver++',solver_order=2)
first,calls,examples=manual_sample(model,scheduler(),cond,null,initial,4,0.)
repeat,_,_=manual_sample(model,scheduler(),cond,null,initial,4,0.)
guided,calls2,examples2=manual_sample(model,scheduler(),cond,null,initial,4,3.)
with torch.inference_mode(): image=vae.decode(guided/vae.config.scaling_factor).sample
assert torch.equal(first,repeat) and torch.isfinite(guided).all()
assert (calls,examples,calls2,examples2)==(4,4,4,8) and not torch.equal(first,guided)
assert image.shape==(1,3,16,16) and torch.isfinite(image).all()
print('Control diminuto diffusers: UNet condicional, VAE, DPM++ 2M y CFG; pesos aleatorios.',flush=True)
def main():
smoke_test()
if os.environ.get('ORYON_SMOKE_ONLY')=='1' or (os.environ.get('ORYON_QUICK')=='1' and not os.environ.get('ORYON_SD_MODEL')):
return
from diffusers import StableDiffusionPipeline
model_id=os.environ.get('ORYON_SD_MODEL','stable-diffusion-v1-5/stable-diffusion-v1-5')
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dtype=torch.float16 if device.type=='cuda' else torch.float32
pipe=StableDiffusionPipeline.from_pretrained(model_id,torch_dtype=dtype,
local_files_only=os.environ.get('ORYON_OFFLINE')=='1').to(device)
pipe.enable_attention_slicing();pipe.enable_vae_slicing()
pipe.unet.eval();pipe.vae.eval();pipe.text_encoder.eval()
# DPM-Solver++ midpoint de segundo orden como en la lección 20.
scheduler=DPMSolverMultistepScheduler.from_config(pipe.scheduler.config,
algorithm_type='dpmsolver++',solver_order=2,solver_type='midpoint')
prompts=[os.environ.get('ORYON_PROMPT','a small red house beside a lake')]
tokens=pipe.tokenizer(prompts,padding='max_length',max_length=pipe.tokenizer.model_max_length,
truncation=True,return_tensors='pt')
empty=pipe.tokenizer(['']*len(prompts),padding='max_length',max_length=pipe.tokenizer.model_max_length,
truncation=True,return_tensors='pt')
output=Path(os.environ.get('ORYON_OUTPUT_DIR','./text-pipeline'));output.mkdir(parents=True,exist_ok=True)
with torch.inference_mode():
cond=pipe.text_encoder(tokens.input_ids.to(device))[0]
null=pipe.text_encoder(empty.input_ids.to(device))[0]
gen=torch.Generator(device=device).manual_seed(2216)
side=512//pipe.vae_scale_factor
initial=torch.randn((1,pipe.unet.config.in_channels,side,side),device=device,dtype=dtype,generator=gen)
records=[];baseline=None
for steps in (15,30):
for w in (0.,3.):
latent,calls,examples=manual_sample(pipe.unet,scheduler,cond,null,initial,steps,w)
decoded=pipe.vae.decode(latent/pipe.vae.config.scaling_factor,return_dict=False)[0]
checked,flag=pipe.run_safety_checker(decoded,device,cond.dtype)
denormalize=[True] if flag is None else [not flag[0]]
image=pipe.image_processor.postprocess(checked,output_type='pil',do_denormalize=denormalize)[0]
name=f'steps-{steps}-w-{w:g}.png';image.save(output/name)
pixels=np.asarray(image,dtype=np.float32)/255
if baseline is None:baseline=pixels.copy()
mse=float(np.square(pixels-baseline).mean())
records.append({'steps':steps,'w_ho':w,'guidance_scale':1+w,'calls':calls,
'network_examples':examples,'image':name,'safety_result':flag,
'pixel_mse_vs_15_steps_w0':mse})
print(f'{steps} pasos, w={w:g}: llamadas={calls}, ejemplos={examples}, MSE respecto al control={mse:.6f}',flush=True)
report={'model':model_id,'prompt':prompts[0],'seed':2216,'scheduler':'DPM-Solver++ 2M midpoint',
'guidance':'epsilon_cond+w*(epsilon_cond-epsilon_null)',
'vae_scale':float(pipe.vae.config.scaling_factor),'safety_checker_present':pipe.safety_checker is not None,
'records':records,'note':'Mismas condiciones iniciales; no es benchmark ni una prueba de superioridad.'}
(output/'report-pipeline.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
del pipe
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 y if g=0?
import numpy as np
def dit_block(x, condition, attention, mlp, modulate):
pass
def latent_loss(model, z_raw, scale, alpha_bar, noise):
pass
Latent diffusion learns a distribution in a representation another network must be able to decode. In DiT, latent scale, patches and conditioning gates are part of the model’s mathematical and computational contract.