Theory of diffusion: convergence, memorization and generalization
Connect score error to convergence, derive the empirical optimal denoiser, and investigate memorization, generalization and spectral structure in diffusion models.
After this lesson you can
- Explain the assumptions connecting score error to distances between probability laws.
- Derive the empirical optimal denoiser and its ideal zero-noise limit.
- Evaluate candidate memorization with training and test nearest neighbors.
- Discuss inductive biases and spectral views of generalization.
- Compare diffusion models trained on datasets of different sizes.
Before you start
- 19Reverse-time SDEProbability flow ODETweedie's formulaDiffusion U-NetFréchet Inception DistancePrecision and recall for generative models
- 04Total variation distanceCoupling
- 07Pinsker's inequalityChain rule for KL divergence
- 26Girsanov theoremKL divergence between diffusion path measures
- 13Random label memorization
- 09Discrete Fourier transform and FFT
The perfect-model paradox
A diffusion model can produce an image absent from its training set. Yet if we exactly fit the empirical distribution’s score and exactly solve the reverse process to zero noise, we recover that distribution: its only possible outcomes are training images. Is generalization an optimization failure? The question is subtler. Architecture, data quantity, minimum noise and discretization determine the problem actually solved.
This lesson distinguishes three objects: the unknown population distribution, the empirical distribution of a finite sample and the distribution produced by a particular algorithm. They are not interchangeable. A guarantee for a continuous process does not automatically guarantee a few-step implementation.
From score error to distance between laws
Consider forward SDE , with and marginals . The exact reverse SDE uses ; an approximation substitutes for that score. Assume existence of both solutions, identical diffusion, integrability and the absolute continuity conditions needed for Girsanov. The drift-change term has norm in the path-entropy formula. If the exact reverse starts at and the approximate one at , the chain rule gives
Direction matters: the expectation above is taken under the exact law. Projecting a trajectory onto its endpoint cannot increase KL, so when final laws satisfy the assumptions,
By Pinsker, . The first term measures terminal-prior mismatch; the second measures integrated score error. This compares continuous processes and does not itself include numerical error. Moreover, if is an atomic empirical measure and has density, their TV is one: the atoms have mass one under the former and zero under the latter. For singular data, control a positive stopping time or use another distance notion and treat the limit carefully.
More complete convergence guarantees add discretization and quantitative assumptions. Chen and colleagues study bounds under score regularity and mean squared error; Benton and colleagues obtain, with finite second moment, identity covariance in their formulation and sufficiently accurate score estimation, order steps to approximate marginal in KL to accuracy . Here is the positive early-stopping time of the Ornstein-Uhlenbeck process: . Notation hides logarithmic factors and the guarantee concerns the smoothed target and theorem’s algorithm. It does not turn the bound into a universal network-evaluation recipe.
The optimal denoiser of observed data
Let be distinct points and uniform over them. With , , Bayes gives responsibility
The squared-loss minimizer is the conditional mean, so the empirical optimal denoiser is . Tweedie’s identity expresses its score as . Away from Voronoi boundaries, as decreases the nearest point dominates; ties can persist exactly at a boundary.
For the variance-exploding process , the probability-flow ODE, parameterized by , is
If initialized exactly at and the exact ODE is integrated toward , its marginals are . These converge weakly to . We can prove more: each trajectory converges almost surely to one point. Indeed, under , . By Jensen and Fubini, expected total trajectory length between zero and is bounded by . Almost every trajectory has finite length and thus a limit as . Weak convergence of marginals identifies that limit’s law with the empirical distribution. Thus its points are recovered with their weights, almost surely.
The claim requires the correct prior and continuous limit; an approximate Gaussian prior, positive final noise or finite integration introduces another error. Kamb and Ganguli study this optimum and what changes under local, equivariant structure.
How to look for copies
Memorization detection starts with an operational question: does a copy mean pixel equality, a slight transformation or semantic similarity? Pixel-neighbor search can detect near duplicates, but cropping or color changes that distance greatly. A feature representation may be more robust to some transformations while confusing distinct images. No isolated metric proves an image was memorized.
Separate training and test, calculate neighbors in both spaces, inspect pairs and calibrate the threshold on examples not used for training. A small distance may reflect duplicates, naturally similar images within classes or extractor biases. If an example is repeated many times in training, an audit based only on unconditional samples may miss it. Carlini and colleagues find 1 280 unique reproduced images in their CIFAR study from one million generations of 16 models under their search protocol; this is not a universal rate. Deduplication, data controls and targeted audits reduce risks without guaranteeing no extraction.
Low FID compares feature moments between sets; it does not show individual images are novel or measure privacy risk by itself. A generator copying training data can look good on an aggregate metric. Also compare coverage, distances to training and test, duplicates and individual examples.
What can explain generalization
Observed generalization has no single established cause. Kadkhodaie and colleagues compare denoisers trained on disjoint subsets and study their convergence as dataset size increases. In face experiments they examine sizes from 1 to 100 000 images: they observe a transition around 1000 and similar training and test errors with 100 000. Behavior depends on resolution, architecture and data. They also connect local denoiser geometry with harmonic bases adapted to image structure. Agreement of two networks on shared inputs is a different test from nearest-neighbor distance.
For the Gaussian Bayesian denoiser, differentiating posterior mean with respect to gives . This matrix is symmetric positive semidefinite. Its eigenvectors show local directions of posterior variation and eigenvalues indicate sensitivity to observation changes. The authors study how networks approximate bases adapted to image geometries; that observation describes an inductive bias, not a guarantee the model recovered the true distribution.
In the analysis of Kamb and Ganguli, imposing locality and translation equivariance restricts the score that can be represented. The constrained optimum can combine information from patches seen in different images and generate novel configurations. In their comparison with a class-conditioned, zero-padded UNet on CIFAR-10, their theory’s fit to network outputs reaches a median with calibrated local scale. That explanation depends on architecture assumptions and does not prove every attention network or generated image generalizes by mosaics. Regularization, early stopping, data and optimization can also change the solution.
From coarse spectrum to detail
For with white noise independent of , centered and with unit variance, an orthonormal Fourier transform preserves noise variance in each coefficient. If , frequency-domain signal-to-noise ratio is ; the cross term vanishes in expectation, though not necessarily in a finite sample. Natural images often have more power at low frequencies than high ones: increasing noise makes many fine details fall below the noise floor before coarse structures.
The spectral view of Dieleman interprets image generation as roughly low-to-high-frequency refinement. It is not an exact factorization or a rule for all data: spectrum, correlations and preprocessing matter. A denoiser can use learned context to infer components individually below the noise level.
The open question: what distribution does the network learn?
Matching scores at examined noise levels and inputs does not by itself identify the population distribution or guarantee two discretized processes match at the endpoint. To test a hypothesis, compare networks with different seeds and disjoint subsets, measure errors on held-out data at several noise levels and repeat with different architectures and schedules. Neighbors, FID and visual samples provide complementary observations; none alone resolves what law the network learned or rules out every case of memorization.
Lab: the empirical optimum
The denoiser is an exact posterior mean of 20 points on a 2D ring. Check Tweedie using finite differences. The terminal sample for the empirical experiment comes from the exact mixture marginal, not a standard-normal approximation.
"""Denoiser empírico VE y dos controles analíticos."""
import numpy as np
def ring_sample(rng,n):
theta=rng.uniform(0,2*np.pi,n);radius=2+.12*rng.normal(size=n)
return np.stack((radius*np.cos(theta),radius*np.sin(theta)),axis=1)
train_pool=ring_sample(np.random.default_rng(2701),2000)
test_data=ring_sample(np.random.default_rng(2702),512)
points=train_pool[:20]
def center_mean(x,sigma,points,bandwidth=0.):
variance=sigma*sigma+bandwidth*bandwidth
delta=x[:,None,:]-points[None,:,:]
logits=-(delta*delta).sum(axis=-1)/(2*variance)
logits-=logits.max(axis=1,keepdims=True)
weights=np.exp(logits);weights/=weights.sum(axis=1,keepdims=True)
return weights@points
def denoise(x,sigma,points,bandwidth=0.):
center=center_mean(x,sigma,points,bandwidth)
v=bandwidth*bandwidth
return (v*x+sigma*sigma*center)/(v+sigma*sigma)
def local_denoise(x,sigma,points):
# Producto de marginales por coordenada, no una CNN entrenada.
delta=x[:,None,:]-points[None,:,:]
logits=-(delta*delta)/(2*sigma*sigma)
logits-=logits.max(axis=1,keepdims=True)
weights=np.exp(logits);weights/=weights.sum(axis=1,keepdims=True)
return (weights*points[None,:,:]).sum(axis=1)
def ddim(start,grid,model):
x=start.copy()
for sigma,next_sigma in zip(grid[:-1],grid[1:]):
D=model(x,sigma)
x=D+(next_sigma/sigma)*(x-D)
return x
def nearest(x,points):return np.sqrt(((x[:,None,:]-points[None,:,:])**2).sum(-1).min(axis=1))
# Identidad de Tweedie y suma de pesos verificadas de forma independiente.
x=np.array([[.2,-.4],[1.1,1.3]]);sigma=.6;h=1e-5
def log_density(x):
z=-((x[:,None,:]-points[None,:,:])**2).sum(-1)/(2*sigma*sigma)
peak=z.max(axis=1,keepdims=True)
return peak[:,0]+np.log(np.exp(z-peak).mean(axis=1))
score=np.column_stack([(log_density(x+np.eye(2)[j]*h)-log_density(x-np.eye(2)[j]*h))/(2*h) for j in range(2)])
error=np.max(np.abs(denoise(x,sigma,points)-(x+sigma*sigma*score)))
assert error<1e-8
print(f'Denoiser y Tweedie: error de diferencias finitas {error:.2e}.')
print('Datos: 20 primeros puntos de un anillo 2D; 2000 candidatos train y 512 test de semillas independientes.')Integrate the VE ODE using the DDIM update. Reduce final noise and refine the grid; neither positive noise nor finite integration necessarily produces an exact copy. Smoothing is a Gaussian mixture and locality is a product of coordinate marginals: these are analytical controls, not networks or proof of CNN theory.
"""Integración finita: medir convergencia sin declarar copias exactas."""
sample_rng=np.random.default_rng(2703);n_samples=128;sigma_max=1.5
index=sample_rng.integers(0,len(points),size=n_samples)
noise=sample_rng.normal(size=(n_samples,2))
emp_start=points[index]+sigma_max*noise
empirical_results={}
for sigma_min in (.4,.1,.02):
grid=np.geomspace(sigma_max,sigma_min,401)
out=ddim(emp_start,grid,lambda x,s:denoise(x,s,points))
empirical_results[str(sigma_min)]=out
d=nearest(out,points)
print(f'Empírico, σ mínimo={sigma_min:g}: distancia mediana/máxima al vecino {np.median(d):.6f}/{d.max():.6f}.')
fine=empirical_results['0.02'];coarse=ddim(emp_start,np.geomspace(sigma_max,.02,201),lambda x,s:denoise(x,s,points))
print(f'Refinamiento 200/400 pasos: diferencia máxima {np.max(np.linalg.norm(fine-coarse,axis=1)):.6f}.')
bandwidth=.3
smooth_start=points[index]+np.sqrt(sigma_max**2+bandwidth**2)*noise
smoothed=ddim(smooth_start,np.geomspace(sigma_max,.02,401),lambda x,s:denoise(x,s,points,bandwidth))
local_index=sample_rng.integers(0,len(points),size=(n_samples,2))
local_clean=np.column_stack((points[local_index[:,0],0],points[local_index[:,1],1]))
local_start=local_clean+sigma_max*noise
local=ddim(local_start,np.geomspace(sigma_max,.02,401),lambda x,s:local_denoise(x,s,points))
print(f'Suavizado h={bandwidth}: distancia mediana al conjunto {np.median(nearest(smoothed,points)):.6f}.')
print(f'Producto local de marginales: distancia mediana al conjunto {np.median(nearest(local,points)):.6f}.')
print('σ mínimo es positivo y la integración finita no produce copias exactas; los controles no son redes entrenadas.')Train a small network receiving the noisy image and log noise level. Its 20 points are a prefix of the same training set; evaluation uses another independent dataset and noise.
"""Red de denoising propia con condición de ruido."""
def net_init(seed):
r=np.random.default_rng(seed);d=32
return [r.normal(scale=np.sqrt(1/3),size=(3,d)),np.zeros(d),
r.normal(scale=np.sqrt(1/d),size=(d,d)),np.zeros(d),
r.normal(scale=np.sqrt(1/d),size=(d,2)),np.zeros(2)]
def network(x,sigma,p):
inp=np.concatenate((x,np.log(sigma)/2),axis=1)
h1=np.tanh(inp@p[0]+p[1]);h2=np.tanh(h1@p[2]+p[3])
residual=h2@p[4]+p[5]
return x+sigma*residual,(inp,h1,h2)
def gradient(x,sigma,target,p):
out,(inp,h1,h2)=network(x,sigma,p);error=out-target
d=2*error/error.size*sigma
w3=h2.T@d;b3=d.sum(0)
d=(d@p[4].T)*(1-h2*h2);w2=h1.T@d;b2=d.sum(0)
d=(d@p[2].T)*(1-h1*h1)
return np.mean(error**2),[inp.T@d,d.sum(0),w2,b2,w3,b3]
def train(n,seed):
r=np.random.default_rng(seed);pool=train_pool[:n];p=net_init(2710)
m=[np.zeros_like(v) for v in p];s=[np.zeros_like(v) for v in p]
for step in range(1,1501):
clean=pool[r.integers(0,n,96)]
sigma=np.exp(r.uniform(np.log(.05),np.log(1.5),(96,1)))
x=clean+sigma*r.normal(size=(96,2));_,g=gradient(x,sigma,clean,p)
for j,(par,grad) in enumerate(zip(p,g)):
m[j]=.9*m[j]+.1*grad;s[j]=.999*s[j]+.001*grad*grad
par-=.002*(m[j]/(1-.9**step))/(np.sqrt(s[j]/(1-.999**step))+1e-8)
return p
def denoise_test(p,data,seed):
r=np.random.default_rng(seed);sigma=np.exp(r.uniform(np.log(.05),np.log(1.5),(len(data),1)))
x=data+sigma*r.normal(size=data.shape)
return float(np.mean((network(x,sigma,p)[0]-data)**2))
probe=net_init(2710);probe_x=test_data[:8]+.1;probe_sigma=np.full((8,1),.3)
_,probe_grad=gradient(probe_x,probe_sigma,test_data[:8],probe);h=1e-5;max_error=0.
for j,p in enumerate(probe):
index=tuple(0 for _ in p.shape);original=p[index]
p[index]=original+h;plus=gradient(probe_x,probe_sigma,test_data[:8],probe)[0]
p[index]=original-h;minus=gradient(probe_x,probe_sigma,test_data[:8],probe)[0]
p[index]=original
max_error=max(max_error,abs((plus-minus)/(2*h)-probe_grad[j][index]))
assert max_error<1e-8
print(f'Red: comprobación de gradiente, error máximo {max_error:.2e}.')
model20=train(20,2711)
print(f'Red 20 datos: MSE train={denoise_test(model20,train_pool[:20],2720):.6f}, test={denoise_test(model20,test_data,2721):.6f}.')Train the same architecture with 200 points.
model200=train(200,2712)
print(f'Red 200 datos: MSE train={denoise_test(model200,train_pool[:200],2720):.6f}, test={denoise_test(model200,test_data,2721):.6f}.')Train the same architecture with 2000 points.
model2000=train(2000,2713)
print(f'Red 2000 datos: MSE train={denoise_test(model2000,train_pool[:512],2720):.6f}, test={denoise_test(model2000,test_data,2721):.6f}.')All three networks start from the same initial sample as the 20-point empirical control; that prior is not the exact marginal of the other two models. Final noise and step count are finite and neighbor distance alone does not prove generalization.
"""Muestras de las redes sobre el mismo punto inicial que el control empírico."""
grid=np.geomspace(sigma_max,.05,151)
network_outputs={}
for n,model in [(20,model20),(200,model200),(2000,model2000)]:
result=ddim(emp_start,grid,lambda x,s:network(x,np.full((len(x),1),s),model)[0])
network_outputs[n]=result
print(f'Red {n}: distancia mediana al train correspondiente {np.median(nearest(result,train_pool[:n])):.6f}; '
f'σ mínimo 0,05, 150 pasos.')
print('Los tres modelos usan el mismo punto inicial qσ máximo de los 20 datos; no se asume prior propio exacto.')Local lab: dataset size and copies
Train three U-Nets from scratch with lesson 18’s architecture on nested subsets of 500, 5000 and 50 000 CIFAR-10 images. Networks share initialization, 1000-step linear schedule and attempt count, with EMA. This matches optimization budget, not visits per image: smaller-set images repeat more. The reader can increase the budget or compare another training rule, declaring that choice. A brief model need not show the generalization transition observed elsewhere.
For each set generate samples from the same latents with deterministic DDIM and calculate FID against test images. The extractor is clean-fid==0.1.35 InceptionV3W with 8-bit RGB and PIL bicubic resizing; report the out-of-range component fraction before clipping. Few-sample FID is heavily biased and does not by itself distinguish memory and generalization. The report retains selection, seeds, extractor hash, checkpoints, features and generated images.
For each sample and held-out test image, find the two nearest train neighbors in normalized RGB pixel RMSE and Euclidean Inception-feature distance. In each space calculate and use the fifth percentile of ratios from that same test set as reference. The fraction of samples below that value is a candidate fraction, not a demonstrated copy fraction or universal rate. The threshold uses a finite set and is not calibrated on additional independent data; the CIFAR split also does not guarantee no cross-set duplicates. If duplicates make , the ratio is undefined: exclude and count it, rather than interpreting it as no copy. A perceptual space can group distinct images; pixel distance can miss position or color changes. Inspect pairs and duplicates before drawing conclusions.
Install PyTorch, torchvision, NumPy, SciPy, Pillow, Matplotlib and clean-fid==0.1.35. Download the inception-2015-12-05.pt extractor from NVIDIA or reuse the lesson 11 file and set ORYON_INCEPTION_PT to its full path including filename. Also set ORYON_DATA_ROOT and ORYON_OUTPUT_DIR. Optionally, ORYON_CIFAR_PARQUET reads CIFAR from local parquet and requires PyArrow. Full mode proposes 10 000 attempts per dataset, microbatch 8 with accumulation 4, 128 samples and 128 test images; ORYON_UPDATES, ORYON_SAMPLE_STEPS, ORYON_SAMPLE_IMAGES and ORYON_TEST_IMAGES adjust the budget. Checkpoints save weights and history and do not automatically resume the optimizer. Full training is for the reader; its result has not been measured here.
With ORYON_QUICK=1, use 16, 64 and 256 train images, width 8, 200 attempts per model, eight samples, 32 test images and 30 NFE. In a protected test all three models completed 200 updates without overflow. Their FIDs were about 513.84, 509.78 and 508.84; none of eight samples fell below candidate thresholds in both spaces. Between 99.18% and 99.26% of RGB components were clipped: the small networks do not yet produce useful images. The schedule matches full mode and ends at , so the problem is no longer the short-schedule prior; this test does not establish quality or a transition. Values only check that the pipeline works; they do not prove absence of memorization.
"""Memorización, vecinos y FID de tres U-Net CIFAR-10 comparables."""
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
from torch import nn
from torch.utils.data import Dataset, DataLoader, Subset
from torchvision import datasets, transforms
from torchvision.utils import save_image
from PIL import Image
from cleanfid.inception_torchscript import InceptionV3W
from cleanfid.resize import build_resizer
torch.set_num_threads(2)
def groups(channels):
return math.gcd(32, channels)
class AdaResidual(nn.Module):
def __init__(self, channels, embedding):
super().__init__()
self.norm1 = nn.GroupNorm(groups(channels), channels)
self.conv1 = nn.Conv2d(channels, channels, 3, padding=1)
self.norm2 = nn.GroupNorm(groups(channels), channels, affine=False)
self.condition = nn.Linear(embedding, 2 * channels)
self.conv2 = nn.Conv2d(channels, channels, 3, padding=1)
def forward(self, x, embedding):
h = self.conv1(F.silu(self.norm1(x)))
scale, shift = self.condition(embedding).chunk(2, dim=1)
h = self.norm2(h) * (1 + scale[:, :, None, None]) + shift[:, :, None, None]
return x + self.conv2(F.silu(h))
class SpatialAttention(nn.Module):
"""Atención de producto escalar solo en mapas de 16×16 y 8×8."""
def __init__(self, channels, head_dim=32):
super().__init__()
self.heads = max(1, channels // min(head_dim, channels))
if channels % self.heads:
raise ValueError('Los canales deben dividirse entre las cabezas')
self.norm = nn.GroupNorm(groups(channels), channels)
self.qkv = nn.Conv2d(channels, 3 * channels, 1)
self.output = nn.Conv2d(channels, channels, 1)
def forward(self, x):
batch, channels, height, width = x.shape
q, k, v = self.qkv(self.norm(x)).chunk(3, dim=1)
def arrange(z):
return z.reshape(batch, self.heads, channels // self.heads, height * width).transpose(2, 3)
h = F.scaled_dot_product_attention(arrange(q), arrange(k), arrange(v))
h = h.transpose(2, 3).reshape(batch, channels, height, width)
return x + self.output(h)
class DiffusionUNet(nn.Module):
"""CIFAR 32×32, niveles 32/16/8; ancho 128 en el modo completo."""
def __init__(self, width=128):
super().__init__()
if width < 8 or width % 8:
raise ValueError('El ancho debe ser un múltiplo de ocho')
embedding = 4 * width
self.width = width
self.time = nn.Sequential(nn.Linear(width, embedding), nn.SiLU(), nn.Linear(embedding, embedding))
self.input = nn.Conv2d(3, width, 3, padding=1)
self.enc32a = AdaResidual(width, embedding)
self.enc32b = AdaResidual(width, embedding)
self.down16 = nn.Conv2d(width, 2 * width, 3, stride=2, padding=1)
self.enc16a = AdaResidual(2 * width, embedding)
self.enc16b = AdaResidual(2 * width, embedding)
self.attn16_down = SpatialAttention(2 * width)
self.down8 = nn.Conv2d(2 * width, 3 * width, 3, stride=2, padding=1)
self.mid8a = AdaResidual(3 * width, embedding)
self.attn8 = SpatialAttention(3 * width)
self.mid8b = AdaResidual(3 * width, embedding)
self.up16 = nn.ConvTranspose2d(3 * width, 2 * width, 4, stride=2, padding=1)
self.merge16 = nn.Conv2d(4 * width, 2 * width, 1)
self.dec16a = AdaResidual(2 * width, embedding)
self.dec16b = AdaResidual(2 * width, embedding)
self.attn16_up = SpatialAttention(2 * width)
self.up32 = nn.ConvTranspose2d(2 * width, width, 4, stride=2, padding=1)
self.merge32 = nn.Conv2d(2 * width, width, 1)
self.dec32a = AdaResidual(width, embedding)
self.dec32b = AdaResidual(width, embedding)
self.out_norm = nn.GroupNorm(groups(width), width)
self.output = nn.Conv2d(width, 3, 3, padding=1)
def forward(self, x, t, T):
half = self.width // 2
freq = torch.exp(torch.linspace(0, -math.log(10000), half, device=x.device, dtype=x.dtype))
phase = (t.to(x.dtype) * (1000. / T))[:, None] * freq[None]
emb = self.time(torch.cat((phase.sin(), phase.cos()), dim=1))
h = self.input(x)
s32 = self.enc32b(self.enc32a(h, emb), emb)
h = self.down16(s32)
s16 = self.attn16_down(self.enc16b(self.enc16a(h, emb), emb))
h = self.mid8a(self.down8(s16), emb)
h = self.mid8b(self.attn8(h), emb)
h = self.merge16(torch.cat((self.up16(h), s16), dim=1))
h = self.attn16_up(self.dec16b(self.dec16a(h, emb), emb))
h = self.merge32(torch.cat((self.up32(h), s32), dim=1))
h = self.dec32b(self.dec32a(h, emb), emb)
return self.output(F.silu(self.out_norm(h)))
def make_schedule(kind, T, device, zero_terminal=False):
if T < 2 or kind not in ('linear', 'cosine'):
raise ValueError('Calendario o número de pasos inválidos')
if kind == 'linear':
beta = torch.linspace(1e-4, .02, T, dtype=torch.float64, device=device)
else:
t = torch.arange(T + 1, dtype=torch.float64, device=device) / T
f = torch.cos((t + .008) / 1.008 * math.pi / 2).square()
beta = (1 - f[1:] / f[:-1]).clamp(max=.999)
bar = torch.cumprod(1 - beta, dim=0)
if zero_terminal:
a = bar.sqrt()
# Preserva el primer nivel ruidoso, no el índice t=0 que se añade después.
a = (a - a[-1]) * a[0] / (a[0] - a[-1])
bar = a.square()
previous = torch.cat((torch.ones(1, dtype=bar.dtype, device=device), bar[:-1]))
beta = 1 - bar / previous
beta = torch.cat((torch.zeros(1, dtype=beta.dtype, device=device), beta))
bar = torch.cat((torch.ones(1, dtype=bar.dtype, device=device), bar))
previous = torch.cat((bar[:1], bar[:-1]))
return {'T': T, 'kind': kind, 'beta': beta, 'bar': bar, 'previous': previous,
'zero_terminal': zero_terminal}
def sha256(path):
d=hashlib.sha256()
with open(path,'rb') as f:
for block in iter(lambda:f.read(1024*1024),b''):d.update(block)
return d.hexdigest()
class ParquetCifar(Dataset):
def __init__(self,folder,split,count):
import pyarrow.parquet as pq
self.rows=[];self.files=[]
for path in sorted(Path(folder).glob(f'{split}-*.parquet')):
self.files.append(str(path))
for batch in pq.ParquetFile(path).iter_batches(batch_size=128,columns=['img']):
self.rows.extend(row['img']['bytes'] for row in batch.to_pylist())
if len(self.rows)>=count:break
if len(self.rows)>=count:break
if len(self.rows)<count:raise ValueError('Faltan imágenes en parquet')
self.rows=self.rows[:count]
def __len__(self):return len(self.rows)
def __getitem__(self,index):
with Image.open(io.BytesIO(self.rows[index])) as img:
return transforms.ToTensor()(img.convert('RGB')),0
def get_data(root,parquet,n_train,n_test):
if parquet:
train=ParquetCifar(parquet,'train',n_train);test=ParquetCifar(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.files+test.files]}
train=datasets.CIFAR10(root,train=True,download=True,transform=transforms.ToTensor())
test=datasets.CIFAR10(root,train=False,download=True,transform=transforms.ToTensor())
return Subset(train,range(n_train)),Subset(test,range(n_test)),{'source':'torchvision CIFAR-10',
'train':'primeras filas antes de permutación','test':'primeras filas'}
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 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 materialize(dataset):
images=torch.empty((len(dataset),3,32,32),dtype=torch.uint8)
for i in range(len(dataset)):
image,_=dataset[i]
images[i]=(image*255).round().clamp(0,255).to(torch.uint8)
return images
def extract_features(images,inception,device):
output=None
for start in range(0,len(images),128):
features=image_features(images[start:start+128].float()/255,inception,device).astype(np.float32)
if output is None:output=np.empty((len(images),features.shape[1]),dtype=np.float32)
output[start:start+len(features)]=features
return output
def nearest_two(query,reference,pixels=False,chunk=512):
"""Dos vecinos de train distintos; distancias en float64 y búsqueda por bloques."""
if len(reference)<2:raise ValueError('Se necesitan al menos dos referencias')
q=np.asarray(query,dtype=np.float64).reshape(len(query),-1)
if pixels:q=q/255.
best=np.full((len(q),2),np.inf);best_idx=np.full((len(q),2),-1,dtype=np.int64)
qnorm=np.sum(q*q,axis=1)[:,None]
for start in range(0,len(reference),chunk):
r=np.asarray(reference[start:start+chunk],dtype=np.float64).reshape(-1,q.shape[1])
if pixels:r=r/255.
distances=np.maximum(qnorm+np.sum(r*r,axis=1)[None,:]-2*q@r.T,0.)
if pixels:distances/=q.shape[1]
distances=np.concatenate((best,distances),axis=1)
indices=np.broadcast_to(np.arange(start,start+len(r)),(len(q),len(r)))
indices=np.concatenate((best_idx,indices),axis=1)
select=np.argpartition(distances,1,axis=1)[:,:2]
selected=np.take_along_axis(distances,select,axis=1)
ids=np.take_along_axis(indices,select,axis=1)
order=np.argsort(selected,axis=1)
best=np.take_along_axis(selected,order,axis=1)
best_idx=np.take_along_axis(ids,order,axis=1)
return np.sqrt(best),best_idx
def ratios(distances):
valid=distances[:,1]>1e-12
values=np.divide(distances[:,0],distances[:,1],out=np.zeros(len(distances)),where=valid)
return values,valid
def verify():
reference=np.array([[0.,0.],[3.,0.],[0.,4.],[3.,4.]])
query=np.array([[.1,.2],[2.8,3.8]])
distance,index=nearest_two(query,reference,chunk=2)
exact=np.sqrt(((query[:,None]-reference[None])**2).sum(-1))
assert np.allclose(distance,np.sort(exact,axis=1)[:,:2])
assert np.allclose(np.take_along_axis(exact,index,axis=1),distance)
dup=np.array([[0.,0.],[0.,0.],[1.,1.]])
d,_=nearest_two(np.array([[0.,0.]]),dup)
_,valid=ratios(d);assert not valid[0]
with torch.device('meta'):model=DiffusionUNet(128)
assert sum(p.numel() for p in model.parameters())==18_477_315
print('Controles: vecinos por bloques frente a cálculo directo, duplicados y parámetros.',flush=True)
def train_model(images,indices,device,quick,out,size):
torch.manual_seed(2701)
width=8 if quick else 128;T=1000
model=DiffusionUNet(width).to(device).train()
ema=copy.deepcopy(model).eval().requires_grad_(False)
optimizer=torch.optim.AdamW(model.parameters(),lr=2e-4)
scaler=torch.amp.GradScaler('cuda',enabled=device.type=='cuda')
source=torch.Generator().manual_seed(2702)
noise=torch.Generator(device=device).manual_seed(2703)
bars=make_schedule('linear',T,device)['bar'].float()
attempts=int(os.environ.get('ORYON_QUICK_UPDATES','200')) if quick else int(os.environ.get('ORYON_UPDATES','10000'))
microbatch=8;accumulation=1 if quick else 4;effective=skipped=0;history=[]
for step in range(attempts):
optimizer.zero_grad(set_to_none=True);loss_sum=0.
for _ in range(accumulation):
selected=torch.randint(len(indices),(microbatch,),generator=source)
x=images[indices[selected]].to(device).float()/127.5-1
t=torch.randint(1,T+1,(microbatch,),device=device,generator=noise)
eps=torch.randn(x.shape,device=device,generator=noise)
a=bars[t].sqrt()[:,None,None,None];s=(1-bars[t]).sqrt()[:,None,None,None]
xt=a*x+s*eps
with torch.autocast(device_type=device.type,enabled=device.type=='cuda'):
loss=F.mse_loss(model(xt,t,T).float(),eps)/accumulation
if not torch.isfinite(loss):raise FloatingPointError('Pérdida no finita')
scaler.scale(loss).backward();loss_sum+=float(loss.detach())
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 a,b in zip(ema.parameters(),model.parameters(),strict=True):a.lerp_(b,1-decay)
for a,b in zip(ema.buffers(),model.buffers(),strict=True):a.copy_(b)
if step==0 or (step+1)%max(1,attempts//10)==0:
history.append({'attempt':step+1,'loss':loss_sum,'effective_updates':effective,'skipped':skipped})
print(f'train={size} paso {step+1}/{attempts}: MSE {loss_sum:.5f}',flush=True)
checkpoint={'ema':{k:v.detach().cpu() for k,v in ema.state_dict().items()},
'model':{k:v.detach().cpu() for k,v in model.state_dict().items()},
'width':width,'T':T,'schedule':'linear','seed_init':2701,'seed_data':2702,'seed_noise':2703,
'size':size,'attempts':attempts,'effective_updates':effective,'skipped':skipped,
'microbatch':microbatch,'accumulation':accumulation,'history':history}
torch.save(checkpoint,out/f'model-{size}.pt')
del model,ema,optimizer,scaler
if device.type=='cuda':torch.cuda.empty_cache()
return checkpoint
@torch.no_grad()
def generate(ckpt,count,device,quick):
model=DiffusionUNet(ckpt['width']).to(device).eval();model.load_state_dict(ckpt['ema'])
T=ckpt['T'];bars=make_schedule('linear',T,device)['bar']
nfe=int(os.environ.get('ORYON_QUICK_SAMPLE_STEPS','30')) if quick else int(os.environ.get('ORYON_SAMPLE_STEPS','50'))
if not 1<=nfe<=T:raise ValueError('Número de pasos inválido')
levels=np.rint(np.linspace(T,0,nfe+1)).astype(int).tolist()
gen=torch.Generator(device=device).manual_seed(2704);output=[]
for start in range(0,count,8):
n=min(8,count-start);x=torch.randn((n,3,32,32),device=device,generator=gen)
for t,s in zip(levels[:-1],levels[1:]):
a,sigma=bars[t].sqrt(),(1-bars[t]).sqrt()
eps=model(x,torch.full((n,),t,device=device,dtype=torch.long),T)
clean=(x-sigma*eps)/a
x=bars[s].sqrt()*clean+(1-bars[s]).sqrt()*eps
if not torch.isfinite(x).all():raise FloatingPointError('Muestras no finitas')
output.append(x.cpu())
del model
if device.type=='cuda':torch.cuda.empty_cache()
return torch.cat(output),nfe,float(bars[-1])
def score_neighbors(sample_images,test_images,train_images,sample_features,test_features,train_features):
result={}
for space in ('pixel','inception'):
if space=='pixel':
q=sample_images.numpy();v=test_images.numpy();reference=train_images.numpy()
else:q=sample_features;v=test_features;reference=train_features
gen_dist,gen_index=nearest_two(q,reference,pixels=space=='pixel')
test_dist,_=nearest_two(v,reference,pixels=space=='pixel')
gen_ratio,gen_valid=ratios(gen_dist);test_ratio,test_valid=ratios(test_dist)
threshold=float(np.quantile(test_ratio[test_valid],.05)) if np.any(test_valid) else None
hits=(float(np.mean(gen_ratio[gen_valid]<threshold))
if threshold is not None and np.any(gen_valid) else None)
result[space]={'metric':'RMSE RGB [0,1]' if space=='pixel' else 'distancia euclídea de Inception',
'test_ratio_p05':threshold,'candidate_fraction':hits,
'generated_invalid_ratios':int((~gen_valid).sum()),'test_invalid_ratios':int((~test_valid).sum()),
'test_distances':test_dist.tolist(),
'test_ratios':[float(v) if valid else None for v,valid in zip(test_ratio,test_valid)],
'distances':gen_dist,'indices':gen_index,'ratios':gen_ratio,'valid':gen_valid}
return result
def main():
quick=os.environ.get('ORYON_QUICK','0')=='1';verify()
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
inception_path=Path(os.environ['ORYON_INCEPTION_PT'])
if inception_path.name!='inception-2015-12-05.pt':raise ValueError('Extractor inesperado')
out=Path(os.environ.get('ORYON_OUTPUT_DIR','oryon-l27'));out.mkdir(parents=True,exist_ok=True)
sizes=[16,64,256] if quick else [500,5000,50000]
pool=sizes[-1];n_test=32 if quick else int(os.environ.get('ORYON_TEST_IMAGES','128'))
n_eval=8 if quick else int(os.environ.get('ORYON_SAMPLE_IMAGES','128'))
if min(n_test,n_eval)<2 or n_test>10000:raise ValueError('Tamaños de evaluación inválidos')
train_ds,test_ds,data_info=get_data(os.environ.get('ORYON_DATA_ROOT','./data'),
os.environ.get('ORYON_CIFAR_PARQUET'),pool,n_test)
train_images=materialize(train_ds);test_images=materialize(test_ds)
permutation=torch.randperm(pool,generator=torch.Generator().manual_seed(2700))
inception=InceptionV3W(str(inception_path.parent),download=False,resize_inside=False).to(device).eval()
train_features=extract_features(train_images,inception,device)
test_features=extract_features(test_images,inception,device)
feature_store={'train':train_features,'test':test_features}
cases=[]
for size in sizes:
indices=permutation[:size];checkpoint=train_model(train_images,indices,device,quick,out,size)
generated,nfe,terminal=generate(checkpoint,n_eval,device,quick)
clipped_fraction=float(((generated<-1)|(generated>1)).float().mean())
quantized=((generated+1)*127.5).round().clamp(0,255).to(torch.uint8)
features=extract_features(quantized,inception,device)
feature_store[f'generated_{size}']=features
selected_images=train_images[indices];selected_features=train_features[indices.numpy()]
neighbor=score_neighbors(quantized,test_images,selected_images,features,test_features,selected_features)
case_dir=out/f'size-{size}';case_dir.mkdir(exist_ok=True)
items=[]
for i in range(min(8,n_eval)):
sample=f'sample-{i}.png';save_image(quantized[i].float()/255,case_dir/sample)
item={'sample':f'size-{size}/{sample}'}
for space in ('pixel','inception'):
info=neighbor[space];idx=int(info['indices'][i,0])
name=f'neighbor-{space}-{i}.png'
save_image(selected_images[idx].float()/255,case_dir/name)
item[space]={'image':f'size-{size}/{name}','source_train_index':int(indices[idx]),
'd1':float(info['distances'][i,0]),'d2':float(info['distances'][i,1]),
'ratio':float(info['ratios'][i]) if info['valid'][i] else None}
items.append(item)
summary={}
for space,info in neighbor.items():
summary[space]={k:v for k,v in info.items() if k not in ('distances','indices','ratios','valid')}
summary[space]['generated_ratios']=[float(r) if v else None for r,v in zip(info['ratios'],info['valid'])]
cases.append({'train_count':size,'nfe':nfe,'terminal_alpha_bar':terminal,'fid':fid(test_features,features),
'fraction_clipped':clipped_fraction,'training':{k:v for k,v in checkpoint.items() if k not in ('ema','model')},
'subset_seed':2700,'subset_indices_sha256':hashlib.sha256(indices.numpy().tobytes()).hexdigest(),
'neighbors':summary,'items':items})
print('Datos',size,'FID',cases[-1]['fid'],'razones candidatas',
{space:summary[space]['candidate_fraction'] for space in summary},flush=True)
del checkpoint,generated,features,selected_images,selected_features,neighbor
report={'quick':quick,'data':data_info,'inception_sha256':sha256(inception_path),
'inception_protocol':'clean-fid InceptionV3W, uint8 RGB, bicúbico PIL 299',
'test_count':n_test,'sample_count':n_eval,'sample_seed':2704,'sizes':sizes,
'threshold_protocol':'Percentil 5 de razón d1/d2 del test al train del mismo caso; fracción bajo umbral son candidatos, no copias verificadas.',
'warning':'FID y umbrales con muestras pequeñas son inestables; no prueban generalización ni extracción. Razones con d2=0 se excluyen.',
'cases':cases}
(out/'report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
np.savez_compressed(out/'features.npz',**feature_store)
import matplotlib.pyplot as plt
fig,axes=plt.subplots(1,2,figsize=(9,4))
axes[0].plot(sizes,[c['fid'] for c in cases],marker='o');axes[0].set(xscale='log',xlabel='Imágenes de entrenamiento',ylabel='FID Inception')
for space in ('pixel','inception'):
vals=[c['neighbors'][space]['candidate_fraction'] for c in cases]
axes[1].plot(sizes,vals,marker='o',label=space)
axes[1].set(xscale='log',xlabel='Imágenes de entrenamiento',ylabel='Fracción candidata',ylim=(0,1));axes[1].legend()
fig.suptitle('Muestras finitas; estos indicadores no demuestran una transición')
fig.tight_layout();fig.savefig(out/'comparison.png',dpi=140);plt.close(fig)
del inception,train_images,test_images,train_features,test_features
if device.type=='cuda':torch.cuda.empty_cache()
print('Informe:',out/'report.json',flush=True)
if __name__=='__main__':main()
npm run lab and open the connection link.Exercises
Step 1 of 4. What minimizes squared loss conditioned on Yσ=y?
Step 1 of 3. What is the difference between reverse drifts?
import numpy as np
def memorization_rate(samples, train_feats, ratio_threshold):
pass
A perfect empirical score recovers empirical data in the ideal limit. A particular model’s generalization depends on its constraints and training and sampling procedure; a continuous bound and low FID are insufficient to prove it.