Score-based models: multiple noise levels and annealed Langevin dynamics
Study three obstacles to score-based generation: lower-dimensional data, low-density regions and local insensitivity to mixture weights. Perturb at multiple noise levels, sample with annealed Langevin dynamics, design noise schedules and steps, and connect discrete levels to continuous-time diffusion.
After this lesson you can
- Prove that a separated-mixture score is nearly blind to mixture weights near a mode.
- Train a σ-conditioned score network with weighted denoising score matching.
- Implement annealed Langevin dynamics with step proportional to σ² and final Tweedie denoising.
- Choose σ_max, σ_min, level count and step using Song and Ermon's rules.
- Train a local-GPU NCSN and evaluate it with the FID harness.
Before you start
A good local field is not enough
In the previous lesson, you learned to estimate a score without calculating the normalizing constant. Now try generating data with that field. A chain starting far from examples depends on the score where little training occurred. Even an exact score can leave a chain trapped in one mode for a long time behind a low-density barrier. If data lie on a lower-dimensional manifold, their clean distribution may lack positive ambient-volume density.
These are three distinct difficulties: existence of an ambient score, estimation error away from data and slow sampler mixing. Gaussian noise at multiple scales addresses all three in practice, although it does not automatically eliminate discretization bias or guarantee finite networks or chains work.
Why one mode hides the other’s weight
Consider mixture with . Write , and let be the second component’s posterior responsibility. Differentiating the mixture gives exactly
If , Cauchy-Schwarz bounds . Since :
With fixed and , the bound approaches zero as grows. Near the field approaches the first Gaussian’s field, approximately independently of its weight. The argument is analogous near with weights exchanged. If changes with or approaches zero very quickly, the weight ratio must also be controlled.
This does not mean the exact score loses all information about : responsibilities change between modes and the field does depend on weights there. The difficulty is that region can be extremely rare and a local chain may cross it very infrequently. For a smooth, positive, connected distribution, knowing the exact score throughout the domain determines log-density up to an additive constant fixed by normalization.
Smoothing at multiple scales and conditioning the network
For , define as the data distribution convolved with . Every level is smooth and positive even if original data lie on a manifold. Large levels spread data information and may connect rarely visited regions, but erase detail. Small levels retain more structure, but their score may be hard to estimate away from examples.
A noise-conditional score network, or NCSN, receives and and approximates . In Song and Ermon, 2019, the network trains on discrete noise levels with weighted denoising score matching. For example, if levels are uniformly selected:
This loss multiplies by the distance from target . Weighting is a design choice, not an identity making all levels equally difficult or equally accurate. If levels are sampled nonuniformly, state the compensation or how the objective changes.
Low average error under does not automatically control maximum error throughout the plane. Map results depend on model, data and training: increasing does not guarantee every pointwise error disappears. This matters especially when initializing particles where the field received little supervision.
Annealed Langevin: distribute before refining
Annealed Langevin dynamics performs several transitions per level, starting with the largest noise. For , use step and repeat:
The Song and Ermon, 2020 algorithm uses this convention with so is the final-level step. The 2019 work instead writes , with displacement and noise . For identical transitions, the 2019 parameter must be twice the one in this lesson. Mixing one convention’s step with the other’s noise changes the process.
The intuition resembles annealing: large levels let the cloud explore a blurred version and small levels refine positions. This is not a guarantee of equilibrium or exact proportions. Each level inherits a state and has finite steps; network error, initialization, step size and mixing time matter. Applying the score of also does not mean an arbitrary cloud follows after one transition.
Scales, budget and exponential averaging
Maximum scale must be large enough for perturbed components to overlap and initialization not to be isolated from data. Minimum scale should be small relative to desired resolution or detail, but not so small that network and chain become unstable. Level count determines how much the problem changes between consecutive scales; more levels increase cost if steps per level stay fixed.
For example, with endpoints 50 and 0.01 and , . These are endpoints and level count of a mathematical example, not a recipe valid for every data scale.
Song and Ermon, 2020 analyze overlap between high-dimensional levels and propose practical rules: select largest noise considering data separation, build a sequence with enough overlap, and tune Langevin step to budget and chain behavior. For an empirical distribution smoothed as a Gaussian mixture, they propose trying on the order of the greatest Euclidean distance between training examples. In their CIFAR-10 experiment they study versus 1. This simplified argument provides guidance, not a guarantee of mixing for every dataset. Units and preprocessing matter.
To make level separation concrete, the work studies one point in dimensions. An isotropic Gaussian norm concentrates near , and a normal approximation to its radius motivates measuring overlap with
The authors recommend approximately as a trade-off in that model; is the standard normal cumulative distribution. This guidance depends on and is not the exact mixing probability of an arbitrary NCSN. The original fit with pixels in used ten levels between 1 and 0.01; later analysis explains why those same ten can be insufficient in high dimensions.
Step and budget are also coupled. For the exact score of , a chain coordinate satisfies
The second equation calculates how variance approaches that of the level in steps. If , stationary variance of this discretization is , not exactly . With step proportional to , ratio is common to all levels. This explores the speed-bias trade-off in a simple case before validation with a learned score. The 2020 paper cites a previous configuration and ; check the specific code convention, scale and cost before transferring those numbers.
Exponential parameter averaging maintains an independent copy . After each optimization step update and use that copy for generation. The paper typically uses and observes greater stability in its experiments; save the copy in the checkpoint and declare its use in comparisons. EMA does not replace validation or guarantee improvement for every problem.
The final displacement and sample comparison
After the last chain, Tweedie denoising can be applied:
If the score is exact and comes from the noisy marginal, this expression is the posterior mean of clean data given that observation. With approximate score or a chain that has not reached the marginal, interpretation is approximate; the mean is not an exact clean sample and may smooth detail.
Song and Ermon, 2020, Table 1 reports CIFAR-10 FID 31.75 for NCSNv2 without that last step and 10.87 with it under their protocol and selected checkpoints. The same table shows a different relationship for the original NCSN, so this difference is not a universal law. When measuring FID, record preprocessing, extractor, example count, reference and whether EMA and denoising were used; small samples can introduce substantial bias. The evaluation lesson explains why FID alone does not summarize quality or coverage.
Toward continuous diffusion
Levels can be viewed as a grid of scales of a family of smoothed distributions. Refining that grid suggests studying continuous time, but the discrete algorithm does not automatically become a reverse diffusion equation simply by increasing : temporal dynamics and coefficients must be specified. Later lessons derive that relation and distinguish levelwise Langevin chains from SDE and ODE solvers.
Lab: a two-dimensional NCSN in NumPy
The clean distribution is a uniform four-Gaussian mixture with standard deviation 0.18 and centers on axes at distance 2 from the origin. Independent training and test sets are generated. An MLP receives coordinates and log σ and returns σ times the score. Loss is mean ½‖σ sθ(x + σε, σ) + ε‖², namely DSM weighted by σ². Check gradients of all parameters by finite differences and verify noise input changes output.
Train two networks with the same update count and examples per batch: one with five geometric levels, another with the minimum level only. Measure error against the analytical score on test. To sample, start from the same cloud and use the same number of network evaluations, step hᵢ = ε σᵢ²/σₘᵢₙ², transition x ← x + ½hᵢ score + √hᵢ z and final Tweedie correction. Here hᵢ is twice theoretical αᵢ; the ε values differ in meaning. Counting samples near centers is a partial diagnostic, not proof that the distribution was recovered. This short run does not assume one method wins.
"""Red condicionada y gradientes de DSM ponderado, desde cero."""
import numpy as np
SIGMAS = np.geomspace(1.2, 0.18, 5)
CENTERS = np.array([[2., 0.], [0., 2.], [-2., 0.], [0., -2.]])
DATA_STD = 0.18
def dataset(seed, n):
rng = np.random.default_rng(seed)
labels = rng.integers(len(CENTERS), size=n)
return CENTERS[labels] + DATA_STD * rng.normal(size=(n, 2))
def initialize(seed, width=24):
rng = np.random.default_rng(seed)
return [rng.normal(size=(3, width)) / np.sqrt(3), np.zeros(width),
rng.normal(size=(width, 2)) / np.sqrt(width), np.zeros(2)]
def predict(params, x, sigma):
# La salida representa σ sθ(x,σ), para estabilizar el objetivo ponderado.
sigma = np.broadcast_to(np.asarray(sigma), (len(x),))
inputs = np.column_stack((x, np.log(sigma)))
hidden = np.tanh(inputs @ params[0] + params[1])
return hidden @ params[2] + params[3], inputs, hidden
def loss_grad(params, clean, sigma, epsilon):
sigma = np.broadcast_to(np.asarray(sigma), (len(clean),))
predicted, inputs, hidden = predict(params, clean + sigma[:, None] * epsilon, sigma)
residual = predicted + epsilon
loss = 0.5 * np.mean(np.sum(residual ** 2, axis=1))
delta = residual / len(clean)
grad2 = hidden.T @ delta
db2 = delta.sum(axis=0)
delta_hidden = (delta @ params[2].T) * (1 - hidden ** 2)
return loss, [inputs.T @ delta_hidden, delta_hidden.sum(axis=0), grad2, db2]
def score(params, x, sigma):
return predict(params, x, sigma)[0] / sigma
def true_score(x, sigma):
variance = DATA_STD ** 2 + sigma ** 2
delta = CENTERS[None, :, :] - x[:, None, :]
logits = -np.sum(delta ** 2, axis=2) / (2 * variance)
weights = np.exp(logits - logits.max(axis=1, keepdims=True))
weights /= weights.sum(axis=1, keepdims=True)
return np.sum(weights[:, :, None] * delta, axis=1) / variance
# Todas las matrices y sesgos se contrastan con diferencias finitas.
test_rng = np.random.default_rng(1601)
test_params = initialize(1602, 5)
test_x = dataset(1603, 9)
test_sigmas = test_rng.choice(SIGMAS, size=len(test_x))
test_noise = test_rng.normal(size=test_x.shape)
_, analytical = loss_grad(test_params, test_x, test_sigmas, test_noise)
largest_error = 0.
for parameter, gradient in zip(test_params, analytical):
for index in np.ndindex(parameter.shape):
original = parameter[index]
parameter[index] = original + 1e-5
plus = loss_grad(test_params, test_x, test_sigmas, test_noise)[0]
parameter[index] = original - 1e-5
minus = loss_grad(test_params, test_x, test_sigmas, test_noise)[0]
parameter[index] = original
largest_error = max(largest_error, abs((plus - minus) / 2e-5 - gradient[index]))
assert largest_error < 1e-8
# En las entradas fijas, cambiar σ debe cambiar la salida escalada de la red.
assert np.max(np.abs(predict(test_params, test_x, SIGMAS[0])[0] -
predict(test_params, test_x, SIGMAS[-1])[0])) > 1e-6
print(f'Error máximo de gradiente: {largest_error:.2e}; la condición σ cambia la salida.')"""Dos ajustes con el mismo presupuesto y evaluación reservada."""
train = dataset(1610, 2048)
held_out = dataset(1611, 2048)
UPDATES = 500
BATCH = 96
def fit(levels):
params = initialize(1612)
rng = np.random.default_rng(1613)
first = [np.zeros_like(p) for p in params]
second = [np.zeros_like(p) for p in params]
for step in range(1, UPDATES + 1):
clean = train[rng.integers(len(train), size=BATCH)]
sigma = rng.choice(levels, size=BATCH)
epsilon = rng.normal(size=clean.shape)
loss, gradients = loss_grad(params, clean, sigma, epsilon)
for j in range(len(params)):
first[j] = .9 * first[j] + .1 * gradients[j]
second[j] = .999 * second[j] + .001 * gradients[j] ** 2
m = first[j] / (1 - .9 ** step)
v = second[j] / (1 - .999 ** step)
params[j] -= .003 * m / (np.sqrt(v) + 1e-8)
return params, loss
multi, multi_loss = fit(SIGMAS)
single, single_loss = fit(SIGMAS[-1:])
condition_change = np.max(np.abs(predict(multi, held_out[:64], SIGMAS[0])[0] -
predict(multi, held_out[:64], SIGMAS[-1])[0]))
assert condition_change > 1e-6
print(f'Presupuesto por red: {UPDATES} actualizaciones, lote {BATCH}; train={len(train)}, test={len(held_out)}.')
print(f'Última pérdida de lote: multinivel={multi_loss:.4f}, nivel único={single_loss:.4f}.')
print(f'Cambio máximo en σ·score al variar σ con x fijo, red entrenada: {condition_change:.4f}')
eval_rng = np.random.default_rng(1614)
for sigma in (SIGMAS[0], SIGMAS[-1]):
evaluation = held_out + sigma * eval_rng.normal(size=held_out.shape)
reference = true_score(evaluation, sigma)
error_multi = np.mean(np.sum((score(multi, evaluation, sigma) - reference) ** 2, axis=1))
print(f'σ={sigma:.3f}, error cuadrático total de score en test multinivel={error_multi:.4f}')
if sigma == SIGMAS[-1]:
error_single = np.mean(np.sum((score(single, evaluation, sigma) - reference) ** 2, axis=1))
print(f'σ mínimo, error de score en test nivel único={error_single:.4f}')"""Comparación de sampler con idéntico número de evaluaciones de score."""
N = 256
STEPS_EACH = 30
EPS = 0.0005
STEPS_TOTAL = len(SIGMAS) * STEPS_EACH
initial_rng = np.random.default_rng(1620)
initial = initial_rng.normal(size=(N, 2)) * SIGMAS[0]
def sample(params, levels, steps, initial_points, seed):
rng = np.random.default_rng(seed)
x = initial_points.copy()
for sigma in levels:
h = EPS * (sigma / SIGMAS[-1]) ** 2
for _ in range(steps):
x += .5 * h * score(params, x, sigma) + np.sqrt(h) * rng.normal(size=x.shape)
# Tweedie aproxima la media limpia posterior en el último nivel.
return x, x + levels[-1] ** 2 * score(params, x, levels[-1])
annealed_noisy, annealed = sample(multi, SIGMAS, STEPS_EACH, initial, 1621)
one_noisy, one = sample(single, SIGMAS[-1:], STEPS_TOTAL, initial, 1621)
def diagnostics(x):
distances = np.sqrt(np.sum((x[:, None, :] - CENTERS[None, :, :]) ** 2, axis=2))
nearest = np.argmin(distances, axis=1)
within = distances[np.arange(len(x)), nearest] < .5
return np.bincount(nearest[within], minlength=4), float(np.mean(within))
for name, points in (('recocido', annealed), ('un nivel', one), ('test real', held_out)):
counts, fraction = diagnostics(points)
print(f'{name}: n={len(points)}; fracción a menos de 0.5 de un centro={fraction:.3f}; cuentas={counts.tolist()}')
print(f'Cada sampler usa {STEPS_TOTAL} evaluaciones por partícula y una adicional para Tweedie; ε={EPS}.')
print('Son diagnósticos del experimento corto, no una medida completa de calidad ni garantía de convergencia.')Exercises
Step 1 of 3. How is the mixture score written?
import torch
def annealed_langevin(score_fn, sigmas, n_steps_each, eps, shape, x0=None, generator=None):
pass
Local lab: NCSN and image evaluation
Train a small U-Net on MNIST or CIFAR-10 at 32×32 pixels. It receives log noise level and returns the score with explicit scale . Each update selects a geometric level per image and minimizes , summing pixels and averaging images. After each Adam step update an EMA copy with factor 0.999 and use it to generate.
The minimum level is 0.01 for images scaled to . The maximum is estimated as the largest Euclidean distance among up to 256 training images: an approximation to Song and Ermon’s rule, not the full-dataset maximum or a mixing guarantee. In normal mode, level count and step follow their techniques 2 and 4 for a simplified one-point model: approximate radial overlap, fix a per-level step budget and search on a grid. This heuristic does not guarantee equilibrium with a learned network. Chains start uniformly in , use and evaluate state before and after final Tweedie correction. The correction estimates a conditional mean; it does not exactly recover a clean image or ensure better evaluation.
Install torch, torchvision, numpy, pillow and clean-fid==0.1.35. MNIST and CIFAR-10 run by default; ORYON_DATASET accepts mnist, cifar10 or both, ORYON_DATA_ROOT controls data cache and ORYON_OUTPUT_DIR output. For clean-fid’s extractor, ORYON_INCEPTION_PT may point to a path ending in inception-2015-12-05.pt; otherwise the program downloads NVIDIA’s published weights to the specified cache. On Windows set variables with $env:ORYON_QUICK='1' before execution. Normal training uses 20 epochs, batch 64, 20 steps per level and evaluates 1024 generated samples against 1024 test images; it can require substantial GPU time. The checkpoint contains parameters, EMA, optimizer and configuration, but this example does not implement automatic resumption.
Evaluation uses the same Inception extractor and clean bicubic resizing as lesson 11, with 2048 features. Both real and generated images receive the same clipping to , integer quantization and resizing to 299; MNIST is replicated into three channels. Report the fraction of generated components outside the interval before clipping. FID uses a low-rank identity equivalent to that lesson’s covariance formula and is checked against an independent small-dimensional calculation. The ImageNet extractor has limits on digits, and finite-sample FID is biased: report size and protocol and do not compare directly with another protocol’s figures. Features are saved to features.npz; FID, seeds, origin and weight hash go to evaluation.json.
ORYON_QUICK=1 limits each branch to 64 training images, one epoch, three fixed levels without the overlap heuristic, two steps per level and 16 samples per set. In one short CUDA check, FID before/after was approximately 453.1/453.3 for MNIST and 528.8/528.1 for CIFAR-10; roughly 99% of generated components lay outside before clipping. With eight updates EMA remains close to the initial network and this workflow does not demonstrate learning or generative quality. These are small-run figures, not paper results. CIFAR was read from parquet using ORYON_CIFAR_PARQUET: it takes the first examples and needs pyarrow. The torchvision alternative chooses different permuted examples; the parquet parameter is accepted only in quick mode.
Before training, check a DSM derivative by finite differences, dependence on , EMA update, each Langevin step and denoising with identical noise; also compare low-rank Fréchet against an independent matrix formula. Test images are used neither in hyperparameter selection nor training.
"""NCSN para MNIST/CIFAR-10 y FID Inception.
Dependencias: torch, torchvision, numpy, pillow y clean-fid==0.1.35.
ORYON_QUICK=1 verifica ambas ramas con pocas imágenes. ORYON_DATASET admite
mnist, cifar10 o both; ORYON_DATA_ROOT, ORYON_OUTPUT_DIR y ORYON_INCEPTION_PT
configuran datos, salida y pesos. ORYON_CIFAR_PARQUET solo se usa en quick.
"""
import copy
import csv
import hashlib
import io
import json
import math
import 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 PIL import Image
from torch import nn
from torch.utils.data import DataLoader, Dataset, Subset
from torchvision import datasets, transforms
from torchvision.utils import save_image
from cleanfid.inception_torchscript import InceptionV3W
from cleanfid.resize import build_resizer
torch.set_num_threads(2)
class Residual(nn.Module):
def __init__(self, channels, embedding):
super().__init__()
self.norm1 = nn.GroupNorm(4, channels)
self.conv1 = nn.Conv2d(channels, channels, 3, padding=1)
self.condition = nn.Linear(embedding, channels)
self.norm2 = nn.GroupNorm(4, channels)
self.conv2 = nn.Conv2d(channels, channels, 3, padding=1)
def forward(self, x, embedding):
h = self.conv1(F.silu(self.norm1(x)))
h = h + self.condition(embedding)[:, :, None, None]
return x + self.conv2(F.silu(self.norm2(h)))
class ScoreUNet(nn.Module):
"""U-Net didáctica: misma resolución de entrada y salida, condicionada por log σ."""
def __init__(self, channels, width=32):
super().__init__()
if width % 4:
raise ValueError('La anchura debe ser múltiplo de cuatro')
embedding = 4 * width
self.embedding = nn.Sequential(nn.Linear(1, embedding), nn.SiLU(), nn.Linear(embedding, embedding))
self.input = nn.Conv2d(channels, width, 3, padding=1)
self.encoder = Residual(width, embedding)
self.down = nn.Conv2d(width, 2 * width, 3, stride=2, padding=1)
self.middle = Residual(2 * width, embedding)
self.up = nn.ConvTranspose2d(2 * width, width, 4, stride=2, padding=1)
self.merge = nn.Conv2d(2 * width, width, 3, padding=1)
self.decoder = Residual(width, embedding)
self.output = nn.Conv2d(width, channels, 3, padding=1)
def forward(self, x, sigma):
if sigma.ndim != 1 or len(sigma) != len(x) or torch.any(sigma <= 0):
raise ValueError('sigma debe ser positiva y tener forma [B]')
embedding = self.embedding(sigma.log()[:, None])
skip = self.encoder(self.input(x), embedding)
h = self.middle(self.down(skip), embedding)
h = self.merge(torch.cat((self.up(h), skip), dim=1))
return self.output(self.decoder(h, embedding)) / sigma[:, None, None, None]
def weighted_dsm(model, clean, sigma, noise):
if noise.shape != clean.shape:
raise ValueError('El ruido debe tener la misma forma que la imagen')
scale = sigma[:, None, None, None]
score = model(clean + scale * noise, sigma)
# ½ E[σ² ||s + ε/σ||²], con suma por píxel y media de lote.
return 0.5 * (scale * score + noise).square().flatten(1).sum(1).mean()
@torch.no_grad()
def update_ema(ema, model, momentum):
if not 0 <= momentum < 1:
raise ValueError('El factor EMA debe estar en [0,1)')
for avg, current in zip(ema.parameters(), model.parameters(), strict=True):
avg.mul_(momentum).add_(current, alpha=1 - momentum)
for avg, current in zip(ema.buffers(), model.buffers(), strict=True):
avg.copy_(current)
def noise_schedule(sigma_max, sigma_min, dim, quick=False):
if not sigma_max > sigma_min > 0 or dim <= 0:
raise ValueError('Se requieren extremos positivos decrecientes y dimensión válida')
if quick:
return np.geomspace(sigma_max, sigma_min, 3)
# Aproximación radial de Song y Ermon (2020), técnica 2, modelo de un punto.
def phi(x):
return .5 * (1 + math.erf(x / math.sqrt(2)))
def overlap(gamma):
center = math.sqrt(2 * dim) * (gamma - 1)
return phi(center + 3 * gamma) - phi(center - 3 * gamma)
low, high = 1., 4.
for _ in range(80):
middle = (low + high) / 2
if overlap(middle) > .5:
low = middle
else:
high = middle
levels = max(2, math.ceil(math.log(sigma_max / sigma_min) / math.log((low + high) / 2)) + 1)
return np.geomspace(sigma_max, sigma_min, levels)
def step_for_gaussian(sigmas, steps):
"""Técnica 4: busca ε sobre rejilla con la varianza del caso de un punto."""
if len(sigmas) < 2 or steps < 1:
raise ValueError('Se necesitan dos niveles y al menos un paso')
gamma = float(sigmas[0] / sigmas[1])
candidates = np.geomspace(1e-4, 0.99, 512) # q = ε / σ_min², 0 < q < 2
limit = 2 / (2 - candidates)
variance = (1 - candidates) ** (2 * steps) * (gamma ** 2 - limit) + limit
q = float(candidates[np.argmin(abs(variance - 1))])
return q * float(sigmas[-1]) ** 2
def annealed(model, initial, sigmas, steps, epsilon, generator):
if len(sigmas) == 0 or steps < 1 or epsilon <= 0 or np.any(np.diff(sigmas) >= 0):
raise ValueError('Niveles estrictamente decrecientes, pasos y ε positivos')
x = initial.clone()
with torch.no_grad():
for sigma in sigmas:
scale = float(sigma)
alpha = epsilon * scale ** 2 / float(sigmas[-1]) ** 2
batch_sigma = torch.full((len(x),), scale, device=x.device, dtype=x.dtype)
for _ in range(steps):
noise = torch.randn(x.shape, device=x.device, dtype=x.dtype, generator=generator)
x = x + alpha * model(x, batch_sigma) + math.sqrt(2 * alpha) * noise
if not torch.isfinite(x).all():
raise FloatingPointError('Una cadena de Langevin dejó de ser finita')
final_sigma = torch.full((len(x),), float(sigmas[-1]), device=x.device, dtype=x.dtype)
denoised = x + float(sigmas[-1]) ** 2 * model(x, final_sigma)
return x, denoised
def low_rank_fid(real, fake):
"""FID entre gaussianas muestrales: identidad de rango bajo de m19-l11."""
real, fake = np.asarray(real, dtype=np.float64), np.asarray(fake, dtype=np.float64)
if real.ndim != 2 or fake.ndim != 2 or real.shape[1] != fake.shape[1] or min(len(real), len(fake)) < 2:
raise ValueError('Se necesitan al menos dos características por conjunto')
if not np.isfinite(real).all() or not np.isfinite(fake).all():
raise ValueError('Las características deben ser finitas')
x, y = real - real.mean(0), fake - fake.mean(0)
trace_x = (x * x).sum() / (len(x) - 1)
trace_y = (y * y).sum() / (len(y) - 1)
cross = np.linalg.svd(x @ y.T, compute_uv=False).sum() / math.sqrt((len(x) - 1) * (len(y) - 1))
value = float(((real.mean(0) - fake.mean(0)) ** 2).sum() + trace_x + trace_y - 2 * cross)
if value < -1e-7 * max(1., trace_x + trace_y):
raise ValueError('Fréchet negativo fuera de tolerancia numérica')
return max(value, 0.)
def checks(device):
torch.manual_seed(1601)
model = ScoreUNet(1, 8).to(device).double()
data = torch.rand((2, 1, 8, 8), device=device, dtype=torch.float64)
sigma = torch.tensor([.2, .5], device=device, dtype=torch.float64)
noise = torch.randn_like(data)
loss = weighted_dsm(model, data, sigma, noise)
gradient = torch.autograd.grad(loss, model.output.bias)[0][0].item()
with torch.no_grad():
model.output.bias[0] += 1e-5
plus = weighted_dsm(model, data, sigma, noise).item()
model.output.bias[0] -= 2e-5
minus = weighted_dsm(model, data, sigma, noise).item()
model.output.bias[0] += 1e-5
assert abs(gradient - (plus - minus) / 2e-5) < 1e-6
ema = copy.deepcopy(model)
before = ema.output.bias.detach().clone()
with torch.no_grad():
model.output.bias.add_(2)
update_ema(ema, model, .75)
assert torch.allclose(ema.output.bias, before + .5)
assert not torch.allclose(model(data, sigma), model(data, sigma.flip(0)))
class Constant(nn.Module):
def forward(self, x, sigma):
return torch.ones_like(x) * 2
start = torch.zeros((2, 1, 2, 2), device=device)
schedule = np.array([.5, .25])
epsilon = .001
gen_a = torch.Generator(device=device).manual_seed(1602)
gen_b = torch.Generator(device=device).manual_seed(1602)
raw, clean = annealed(Constant(), start, schedule, 1, epsilon, gen_a)
expected = start.clone()
for s in schedule:
alpha = epsilon * s ** 2 / schedule[-1] ** 2
expected = expected + 2 * alpha + math.sqrt(2 * alpha) * torch.randn(
expected.shape, device=device, generator=gen_b)
assert torch.allclose(raw, expected) and torch.allclose(clean, raw + 2 * schedule[-1] ** 2)
random = np.random.default_rng(1603)
a, b = random.normal(size=(12, 4)), random.normal(size=(10, 4))
ca, cb = np.cov(a, rowvar=False), np.cov(b, rowvar=False)
values, vectors = np.linalg.eigh(ca)
root = (vectors * np.sqrt(np.maximum(values, 0))) @ vectors.T
mid = root @ cb @ root
direct = ((a.mean(0) - b.mean(0)) ** 2).sum() + np.trace(ca) + np.trace(cb) - 2 * np.sqrt(
np.maximum(np.linalg.eigvalsh((mid + mid.T) / 2), 0)).sum()
assert np.allclose(low_rank_fid(a, b), direct, atol=1e-10)
assert low_rank_fid(a, a) < 1e-10
assert np.all(np.diff(noise_schedule(1., .01, 1024)) < 0)
print('Controles correctos: gradiente DSM, condicionamiento, EMA, pasos, Tweedie y Fréchet.', flush=True)
del model, ema
if device.type == 'cuda':
torch.cuda.empty_cache()
class ParquetCifar(Dataset):
def __init__(self, folder, split, count):
import pyarrow.parquet as pq
self.images = []
for path in sorted(Path(folder).glob(f'{split}-*.parquet')):
for batch in pq.ParquetFile(path).iter_batches(batch_size=128, columns=['img']):
self.images.extend(row['img']['bytes'] for row in batch.to_pylist())
if len(self.images) >= count:
break
if len(self.images) >= count:
break
if len(self.images) < count:
raise ValueError('Faltan imágenes CIFAR en parquet')
self.images = self.images[:count]
def __len__(self):
return len(self.images)
def __getitem__(self, i):
with Image.open(io.BytesIO(self.images[i])) as image:
return transforms.ToTensor()(image.convert('RGB')), 0
def load_data(kind, root, quick, parquet):
if kind == 'cifar10' and quick and parquet:
return ParquetCifar(parquet, 'train', 64), ParquetCifar(parquet, 'test', 16)
if kind == 'mnist':
transform = transforms.Compose([transforms.Resize((32, 32)), transforms.ToTensor()])
cls = datasets.MNIST
else:
transform, cls = transforms.ToTensor(), datasets.CIFAR10
train = cls(root, train=True, download=True, transform=transform)
test = cls(root, train=False, download=True, transform=transform)
order = torch.randperm(len(train), generator=torch.Generator().manual_seed(1610)).tolist()
return Subset(train, order[:64] if quick else order), Subset(test, range(16 if quick else len(test)))
def features(images, inception, device):
resize = build_resizer('clean')
result = []
with torch.inference_mode():
for start in range(0, len(images), 4):
batch = images[start:start + 4]
if batch.shape[1] == 1:
batch = batch.repeat(1, 3, 1, 1)
# Cuantización declarada: idéntica para reales y generadas.
arrays = (batch.clamp(0, 1) * 255).round().to(torch.uint8).permute(0, 2, 3, 1).cpu().numpy()
resized = np.stack([resize(array).transpose(2, 0, 1) for array in arrays])
result.append(inception(torch.from_numpy(resized).to(device)).cpu().numpy())
return np.concatenate(result)
def run_one(kind, root, output_root, quick, parquet, inception_path, device):
train, test = load_data(kind, root, quick, parquet)
channels, width = (1 if kind == 'mnist' else 3), (8 if quick else 32)
batch_size, epochs, steps, n_eval = (8, 1, 2, 16) if quick else (64, 20, 20, 1024)
loader = DataLoader(train, batch_size=batch_size, shuffle=True, num_workers=0,
generator=torch.Generator().manual_seed(1611))
reference = torch.stack([test[i][0] for i in range(n_eval)])
# La distancia máxima se estima con un subconjunto de train, nunca de test.
subset = torch.stack([train[i][0].flatten() for i in range(min(len(train), 256))])
sigma_max = float(torch.pdist(subset).max())
sigma_min = .01
sigmas = noise_schedule(sigma_max, sigma_min, channels * 32 * 32, quick)
epsilon = step_for_gaussian(sigmas, steps)
print(f'{kind}: σ máximo estimado en train {sigma_max:.4f}, σ mínimo {sigma_min}, '
f'niveles {len(sigmas)}, pasos/nivel {steps}, ε {epsilon:.8g}', flush=True)
torch.manual_seed(1612)
model = ScoreUNet(channels, width).to(device)
ema = copy.deepcopy(model).eval().requires_grad_(False)
optimizer = torch.optim.Adam(model.parameters(), lr=.0002)
generator = torch.Generator(device=device).manual_seed(1613)
sigma_tensor = torch.as_tensor(sigmas.copy(), dtype=torch.float32, device=device)
output = Path(output_root) / kind
output.mkdir(parents=True, exist_ok=True)
history = []
for epoch in range(1, epochs + 1):
total, count = 0., 0
for clean, _ in loader:
clean = clean.to(device)
levels = torch.randint(len(sigmas), (len(clean),), device=device, generator=generator)
sigma = sigma_tensor[levels]
noise = torch.randn(clean.shape, device=device, generator=generator)
loss = weighted_dsm(model, clean, sigma, noise)
optimizer.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 10., error_if_nonfinite=True)
optimizer.step()
update_ema(ema, model, .999)
total += loss.item() * len(clean)
count += len(clean)
history.append((epoch, total / count))
print(f'{kind} época {epoch}: pérdida ponderada por imagen {total/count:.5f}', flush=True)
with (output / 'history.csv').open('w', encoding='utf-8', newline='') as file:
writer = csv.writer(file)
writer.writerow(('epoch', 'loss'))
writer.writerows(history)
checkpoint = {'model': model.state_dict(), 'ema': ema.state_dict(), 'optimizer': optimizer.state_dict(),
'channels': channels, 'width': width, 'epochs': epochs, 'sigmas': sigmas.tolist(),
'steps': steps, 'epsilon': epsilon, 'dataset': kind, 'quick': quick}
torch.save(checkpoint, output / 'ncsn.pt')
restored = torch.load(output / 'ncsn.pt', map_location=device, weights_only=True)
eval_model = ScoreUNet(channels, width).to(device).eval()
eval_model.load_state_dict(restored['ema'])
assert all(torch.equal(eval_model.state_dict()[k], ema.state_dict()[k]) for k in ema.state_dict())
del model, ema, optimizer, restored, checkpoint, loss, clean, noise, sigma
if device.type == 'cuda':
torch.cuda.empty_cache()
sample_gen = torch.Generator(device=device).manual_seed(1614)
# Origen uniforme, como en los experimentos originales; no se declara equilibrio.
raw_batches, final_batches = [], []
for start in range(0, n_eval, 8 if quick else 32):
count = min(8 if quick else 32, n_eval - start)
initial = torch.rand((count, channels, 32, 32), device=device, generator=sample_gen)
raw, final = annealed(eval_model, initial, sigmas, steps, epsilon, sample_gen)
raw_batches.append(raw.cpu())
final_batches.append(final.cpu())
raw, final = torch.cat(raw_batches), torch.cat(final_batches)
raw_outside = float(((raw < 0) | (raw > 1)).float().mean())
final_outside = float(((final < 0) | (final > 1)).float().mean())
save_image(final[:16].clamp(0, 1), output / 'samples.png', nrow=4)
del eval_model
if device.type == 'cuda':
torch.cuda.empty_cache()
path = Path(inception_path)
if path.name != 'inception-2015-12-05.pt':
raise ValueError('ORYON_INCEPTION_PT debe terminar en inception-2015-12-05.pt')
if not path.is_file():
path.parent.mkdir(parents=True, exist_ok=True)
torch.hub.download_url_to_file(
'https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/metrics/inception-2015-12-05.pt',
str(path), progress=True)
digest = hashlib.sha256()
with path.open('rb') as file:
for block in iter(lambda: file.read(1024 * 1024), b''):
digest.update(block)
inception = InceptionV3W(str(path.parent), download=False, resize_inside=False).to(device).eval()
real_features = features(reference, inception, device)
raw_features = features(raw, inception, device)
final_features = features(final, inception, device)
fid_raw = low_rank_fid(real_features, raw_features)
fid_final = low_rank_fid(real_features, final_features)
np.savez_compressed(output / 'features.npz', real=real_features, raw=raw_features, denoised=final_features)
report = {'dataset': kind, 'quick': quick, 'reference_split': 'test',
'n_real': n_eval, 'n_generated': n_eval, 'training_images': len(train),
'sigma_max_from_train_subset': sigma_max, 'sigma_min': sigma_min,
'levels': len(sigmas), 'steps_per_level': steps, 'epsilon': epsilon,
'ema_momentum': .999, 'selection_seed': 1610, 'shuffle_seed': 1611,
'model_seed': 1612, 'training_noise_seed': 1613, 'sampling_seed': 1614,
'data_source': 'cifar_parquet_first_rows' if kind == 'cifar10' and parquet and quick else 'torchvision',
'fid_inception_raw': fid_raw, 'fid_inception_denoised': fid_final,
'fraction_outside_before_clip_raw': raw_outside,
'fraction_outside_before_clip_denoised': final_outside,
'extractor': 'InceptionV3W clean-fid 0.1.35, 2048 características',
'extractor_sha256': digest.hexdigest(),
'preprocessing': 'recorte [0,1], cuantización uint8, replicar canal MNIST y resize clean bicúbico a 299',
'torch_version': str(torch.__version__), 'numpy_version': np.__version__}
(output / 'evaluation.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(f'{kind}: FID Inception {n_eval} test / {n_eval} generadas: antes {fid_raw:.5f}, '
f'después {fid_final:.5f}; fuera de [0,1] antes {raw_outside:.4f}, después {final_outside:.4f}', flush=True)
print(f'Pesos Inception SHA256 {digest.hexdigest()}; resize clean-fid PIL float bicúbico 299×299.', flush=True)
print('FID finito es sesgado, no es benchmark, y denoising no garantiza mejora visual ni de FID.', flush=True)
del inception, train, test, loader, raw, final
if device.type == 'cuda':
torch.cuda.empty_cache()
def main():
quick = os.environ.get('ORYON_QUICK') == '1'
kind = os.environ.get('ORYON_DATASET', 'both').lower()
if kind not in ('mnist', 'cifar10', 'both'):
raise ValueError('ORYON_DATASET debe ser mnist, cifar10 o both')
root = os.environ.get('ORYON_DATA_ROOT', './data')
output = os.environ.get('ORYON_OUTPUT_DIR', './ncsn-results')
parquet = os.environ.get('ORYON_CIFAR_PARQUET')
if parquet and not quick:
raise ValueError('ORYON_CIFAR_PARQUET solo se utiliza en quick')
# Puede descargarse del origen oficial indicado si no existe en esta ruta.
default = Path.home() / '.cache' / 'huggingface' / 'oryon-generative-weights' / 'inception-2015-12-05.pt'
inception = os.environ.get('ORYON_INCEPTION_PT', str(default))
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'dispositivo {device}; quick {quick}', flush=True)
checks(device)
for name in ('mnist', 'cifar10') if kind == 'both' else (kind,):
run_one(name, root, output, quick, parquet, inception, device)
if __name__ == '__main__':
main()
npm run lab and open the connection link.Large scales extend data information and small scales refine structure. An NCSN shares a conditioned field across levels and annealed Langevin uses it sequentially; finite annealing and final denoising alone do not certify an exact sample.