Module contents
Lesson 18 of 28Core 115 min

Diffusion in practice: U-Net, time conditioning, schedules and weightings

Build a diffusion U-Net with time conditioning, compare schedules in log SNR and correct terminal SNR, relate epsilon, x_0 and v parameterizations, study loss weighting, and use EMA and mixed precision in a practical training protocol.

After this lesson you can

  • Implement a diffusion U-Net with sinusoidal time embeddings and AdaGN modulation.
  • Describe and compare schedules in log SNR and correct nonzero terminal SNR.
  • Derive exact relationships between epsilon, x_0 and v errors in terms of SNR.
  • Calculate the effective log-SNR weight for combinations of parameterization, weighting and time distribution.
  • Train a diffusion model on CIFAR-10 with EMA and mixed precision and perform short ablations.

Before you start

The recipe defines the model too

Two implementations can use the same diffusion formula and behave very differently. The schedule determines the signals seen by the network; parameterization and time distribution decide how much each task weighs; architecture and budget constrain what it can learn. Before comparing results, identify those choices and record preprocessing, seeds, update count and generation weights.

A U-Net that knows the noise level

The diffusion U-Net retains the descending path, bottleneck and ascending path of the segmentation U-Net. An image input B×C×H×WB\times C\times H\times W is projected into internal channels. Residual blocks process features at several resolutions; downsampling aggregates context, and skip connections return detail to the ascending path. The output has the same spatial shape as the prediction target, not one class per pixel.

Spatial attention relates distant positions. On a grid with N=HWN=H W positions, the full attention affinity matrix has N2N^2 entries per head and example: doubling both image sides multiplies NN by four and the matrix by sixteen. Actual memory also depends on the attention kernel, saved activations, optimizer and precision. Placing attention at lower resolutions is a design choice to control that cost, not a guarantee of fitting on every GPU.

InteractiveA tensor travels through the U-Net

This is the architecture used in the lab. The module names use the resolutions for a 32 × 32 input.

Time embedding128 → 512 · AdaGN conditioning
↓ condiciona todos los bloques residuales ↓
Input and encoder32 × 32 · 128 channels
skip →
Decoder and output32 × 32 · 128 channels
↓
↑
Downsample and encode16 × 16 · 256 channels
skip →
Upsample and decode16 × 16 · 256 channels
↓
↑
Middle8 × 8 · 384 channels
1. Time embedding

Width-w sinusoidal features followed by two linear layers.

Module 1 / 23

At w = 128, the lab’s DiffusionUNet class has 18,477,315 parameters. The actual CIFAR input shape is [B, 3, 32, 32]. The 64 option computes hypothetical shapes for the same modules. Attention operates at half and one quarter of the input resolution. The skip connections retain the outputs of the second block at resolution 32 and the attention at resolution 16.

The output size counts B × channels × height × width × bytes, or B × channels × bytes for the embedding. Peak memory also includes skips, intermediate tensors, gradients, parameters, optimizer state, EMA and attention buffers. Effective precision depends on autocast and the operator.

Base width w
Input resolution
Tensor storage
1
Module output shape
[1, 512]
Module parameters
329 k
Network parameters
18.5 M
Output size
1.00 KiB
Follow shapes, skips and time injections. The figure states the architecture counted and the memory estimated.

The network must know how noisy its input is. A common noise-level conditioning transforms normalized tt or a continuous scale such as log⁡σ\log\sigma using sinusoidal frequencies and a small MLP. The resulting vector modulates each block. With adaptive GroupNorm, a common form is

h′=GN⁡(h)⊙(1+γ(e))+δ(e),h'=\operatorname{GN}(h)\odot(1+\gamma(e))+\delta(e),

where ee is the embedding and γ,δ\gamma,\delta are channel-wise projections broadcast spatially. This FiLM modulation lets the same block behave differently at different levels. Dhariwal and Nichol study adaptive modulation in diffusion U-Nets. The constants and exact injection method are part of the architecture.

GroupNorm does not depend on statistics from other batch examples. BatchNorm during training does couple them and uses different statistics at evaluation; this can cause discrepancies, especially with small batches, although it does not imply every BatchNorm network is unable to sample. Passing an integer tt without an embedding is not mathematically impossible, but its scale and representation can make optimization harder. Check that changing the level actually changes the output.

Signal, noise and schedule endpoints

Write the variance-preserving process as

xt=atx0+σtϵ,at2+σt2=1,ϵ∼N(0,I).x_t=a_t x_0+\sigma_t\epsilon,\qquad a_t^2+\sigma_t^2=1,\quad \epsilon\sim\Normal(0,I).

Here at=αˉta_t=\sqrt{\bar\alpha_t} and σt=1−αˉt\sigma_t=\sqrt{1-\bar\alpha_t}. The signal-to-noise ratio is SNR⁡(t)=at2/σt2\operatorname{SNR}(t)=a_t^2/\sigma_t^2 and its natural logarithm λ(t)=log⁡SNR⁡(t)\lambda(t)=\log\operatorname{SNR}(t) when both coefficients are positive. At exact endpoints it may be +∞+\infty or −∞-\infty; a finite plot must state the clipping used to represent them.

The previous lesson’s linear schedule distributes βt\beta_t linearly, not SNR. In the cosine schedule of Nichol and Dhariwal, one continuous form before clipping is

αˉ(u)=cos⁡2 ⁣(u+s1+sπ2)cos⁡2 ⁣(s1+sπ2),u=t/T,s=0,008.\bar\alpha(u)= \frac{\cos^2\!\left(\frac{u+s}{1+s}\frac{\pi}{2}\right)} {\cos^2\!\left(\frac{s}{1+s}\frac{\pi}{2}\right)}, \quad u=t/T,\quad s=0{,}008.

To construct a discrete schedule, calculate βt=1−αˉ(t/T)/αˉ((t−1)/T)\beta_t=1-\bar\alpha(t/T)/\bar\alpha((t-1)/T). If you clip βt\beta_t for stability, use the product of the clipped αt\alpha_t thereafter; it may leave nonzero terminal signal. The continuous and clipped discrete values are not necessarily identical.

InteractiveSchedules in log-SNR space

The image stays at 32 × 32. The resolution control changes the schedule applied to the image.

The cosine curves use 32 as the reference. The shifted log SNR is λ base + 2 log(32/d), because averaging independent noise reduces its variance. See Hoogeboom et al., Equation 5. Real image structure can depart from this assumption. The same shift can be applied to the image with the linear schedule. The graph clips values outside [−14, 14] for display.

The linear schedule increases β from 0.0001 to 0.02. The Nichol and Dhariwal cosine schedule uses s = 0.008 and clips β to 0.999 before accumulating ᾱ. Fixed noise uses seed 1810. The image is the first CIFAR-10 test example, a cat, normalized to [−1, 1] and clipped for display. It is the same image used in m19-l17.

Image schedule
Hypothetical resolution
200
Selected log SNR
2.1829
√ᾱₜ
0.9480
√(1 − ᾱₜ)
0.3183
Compare curves and image with their resolution and representation assumptions.

Averaging a block of pixels reduces independent noise while correlated spatial signal can remain visible. In the analysis of Hoogeboom, Heek and Salimans, this motivates shifting log SNR by approximately 2log⁡(dref/d)2\log(d_{\mathrm{ref}}/d) when changing side length from drefd_{\mathrm{ref}} to dd. It is guidance based on a specific downsampling model, not a universal law for every image or resampling method. Enlarging a small image for illustration does not create genuine high-resolution detail.

Lin and colleagues identify a discrepancy when training leaves aT>0a_T>0 but generation starts from pure noise; in their Stable Diffusion 2.1 experiments they observe restricted brightness. They propose several joint corrections, including zero terminal SNR and starting the sampler at the last step. For a discrete schedule with a1>aT≥0a_1>a_T\ge0, one correction rescales noisy levels:

at′=at−aTa1−aT a1,1≤t≤T,αˉt′=(at′)2,αˉ0′=1.a'_t=\frac{a_t-a_T}{a_1-a_T}\,a_1,\quad 1\le t\le T, \qquad \bar\alpha'_t=(a'_t)^2,\quad \bar\alpha'_0=1.

It preserves the first noisy level a1a_1 and makes aT′=0a'_T=0. Recover αt′=αˉt′/αˉt−1′\alpha'_t=\bar\alpha'_t/\bar\alpha'_{t-1} and βt′=1−αt′\beta'_t=1-\alpha'_t; the last step has βT′=1\beta'_T=1. Therefore the reverse mean formula dividing by αT\sqrt{\alpha_T} in the DDPM lesson is invalid at that endpoint. For vv prediction, reconstruct x^0\hat x_0 without dividing by aTa_T and use posterior coefficients; training and sampling must also use a consistent schedule.

Three targets, one rotation

The vv parameterization defines

vt=atϵ−σtx0,(xtvt)=(atσt−σtat)(x0ϵ).v_t=a_t\epsilon-\sigma_t x_0,\qquad \begin{pmatrix}x_t\\v_t\end{pmatrix}= \begin{pmatrix}a_t&\sigma_t\\-\sigma_t&a_t\end{pmatrix} \begin{pmatrix}x_0\\\epsilon\end{pmatrix}.

The matrix is orthogonal because at2+σt2=1a_t^2+\sigma_t^2=1. Its inverse gives

x0=atxt−σtvt,ϵ=σtxt+atvt.x_0=a_t x_t-\sigma_t v_t,\qquad \epsilon=\sigma_t x_t+a_t v_t.

Both conversions remain finite at at=0a_t=0 or σt=0\sigma_t=0. At the noisy endpoint vT=−x0v_T=-x_0; at the clean endpoint v=ϵv=\epsilon. The parameterization is used by Salimans and Ho. By contrast, solving for x0=(xt−σtϵ)/atx_0=(x_t-\sigma_t\epsilon)/a_t requires at>0a_t>0, and converting noise to score via s=−ϵ/σts=-\epsilon/\sigma_t requires σt>0\sigma_t>0. Actual noise thus gives the conditional score given x0x_0; −ϵθ/σt-\epsilon_\theta/\sigma_t defines the modeled field, which matches the marginal score at the DSM optimum under the previous lesson’s assumptions.

Interactiveε, x₀ and v as vectors

The arrows give coefficients in the (x₀, ε) basis. Their dot products with the point give the target values.

  • Target x₀
  • Target ε
  • Target v
  • State z
  • Pair (x₀, ε)

The variance-preserving path uses a = cos(πu/2), σ = sin(πu/2), z = ax₀ + σε, v = aε − σx₀ and u = noise level/100. This is a rotation, with x₀ = az − σv and ε = σz + av. At the endpoints, v goes from ε to −x₀. See Salimans and Ho, Section 4 for this parameterization.

For a fixed error δ in ε̂ and the same z, Δx₀ = −(σ/a)δ and Δv = δ/a. If δ were random with variance 1, the induced variances would be 1.000 for x̂₀ and 2.000 for v̂. The values come from propagating the chosen error. At a = 0 the conversions from ε are undefined. Predicting v directly still gives x₀ = az − σv.

50
1.0
0.6
0.20
State z
1.131
Target v
−0.283
Error in x̂₀
−0.200
Error in v̂
0.283
Move the level and compare targets and errors corresponding to the same converted prediction.

To compare errors, hold xtx_t fixed and convert the same prediction between parameterizations. If at,σt>0a_t,\sigma_t>0, errors satisfy atΔx0+σtΔϵ=0a_t\Delta x_0+\sigma_t\Delta\epsilon=0 and Δv=Δϵ/at\Delta v=\Delta\epsilon/a_t. Therefore:

∥Δx0∥2=1SNR⁡(t)∥Δϵ∥2,∥Δv∥2=(1+1SNR⁡(t))∥Δϵ∥2.\|\Delta x_0\|^2=\frac{1}{\operatorname{SNR}(t)}\|\Delta\epsilon\|^2,\qquad \|\Delta v\|^2=\left(1+\frac{1}{\operatorname{SNR}(t)}\right)\|\Delta\epsilon\|^2.

These are not equalities between errors from three independent networks. At zero SNR, do not directly substitute into divergent fractions: use division-free conversions or study limits under assumptions about errors.

What a loss actually weights

A diffusion weighting combines at least three choices: target parameterization, explicit weight and level sampling distribution. For comparison, first convert all errors to the same parameterization. If λ(t)\lambda(t) is monotonic and differentiable, tt has density q(t)q(t) and the noise loss has factor wtw_t, the weight with respect to dλd\lambda is

q(t(λ)) wt(λ)∣dtdλ∣.q(t(\lambda))\,w_{t(\lambda)} \left|\frac{dt}{d\lambda}\right|.

The same time curve can give a different log-SNR weight through the Jacobian. If you change qq but divide by its density to retain the same integral, you change Monte Carlo estimator variance without changing its expectation, provided qq is positive where the integrand contributes and the expectation exists. A discrete schedule sums masses per level: a continuous density is an approximation requiring an explicit convention.

InteractiveThe effective weight of your loss

Density of the squared ε error per unit of λ = log SNR. Each curve is normalized over the plotted interval.

The custom preset uses an ideal cosine VP path a = cos(πt/2), σ = sin(πt/2), over 0.02 ≤ t ≤ 0.98. The density is p(t) · direct weight · conversion factor / |dλ/dt|. The factors for ε, x₀, v and score are 1, σ²/a², 1/a² and 1/σ². Late-time sampling uses p(t) = 2t/(0.98² − 0.02²). The range excludes the endpoints, where conversion can be singular. Min-SNR with γ = 5 adjusts the direct weight so the parameterizations express the same weighted loss.

The DDPM preset uses the simple unweighted ε loss with uniform time and a truncated continuous cosine schedule. It is a continuous analogue. EDM uses log σ̃ ~ N(−1.2, 1.2²), σ̃² = exp(−λ), σ_data = 0.5 and x₀ weight (σ̃² + σ_data²)/(σ̃²σ_data²). FM-OT uses z = (1 − t)x₀ + tε, uniform t and target x₀ − ε. Its density with respect to ε error is exp(−λ/2)/2. The curves are normalized on their common plotting interval.

The ELBO line has constant density in λ with respect to ε error, up to the conventional factor of 1/2. The calculations and conversions follow Kingma and Gao, Equations 4 and 39–86 and Appendix D.6. Normalization removes overall scale differences and preserves differences in shape.

Preset
Target
Direct weighting
Distribution of t
Log SNR interval
[−6.92, 6.92]
Unnormalized integral
1.0000
Select target, weighting and sampling; curves state the measure and normalization used.

In the continuous formulation of Kingma and Gao, the reference variational objective has an especially simple log-SNR representation. Their theorem interprets a weighted loss as an ELBO on augmented data under specific assumptions, including a corresponding weight monotonic increasing in time, or decreasing in λ\lambda. An arbitrary weighting can still be written as a weighted integral, but is not automatically covered by that theorem. Comparing DDPM, EDM and flow-matching recipes requires stating the change of variables, signal normalization and preconditioning: their noise symbols are not interchangeable without conversion.

As an example, Hang and colleagues propose Min-SNR-γ\gamma. Under a convention weighting x0x_0 error by min⁡(SNR,γ)\min(\mathrm{SNR},\gamma), equivalent weights for linked errors are min⁡(SNR,γ)/SNR\min(\mathrm{SNR},\gamma)/\mathrm{SNR} for ϵ\epsilon and min⁡(SNR,γ)/(SNR+1)\min(\mathrm{SNR},\gamma)/(\mathrm{SNR}+1) for vv. At zero SNR their limits are 1 for ϵ\epsilon and 0 for x0x_0 and vv. The error conversion ceases to be invertible exactly there: if the discrete schedule includes that endpoint and you assign vv zero weight, that term does not supervise vTv_T. This alone does not prove model failure, but must be considered when designing the loss. Equivalent weights do not imply identical errors for models with different architectures or training.

Learned reverse variance

In fixed-variance DDPM, LsimpleL_{\mathrm{simple}} does not train a reverse variance. Nichol and Dhariwal propose predicting a parameter rr per coordinate and writing, for intermediate steps,

log⁡Σθ=rlog⁡βt+(1−r)log⁡β~t.\log\Sigma_\theta=r\log\beta_t+(1-r)\log\tilde\beta_t.

Their rr is not explicitly restricted to [0,1][0,1], so the expression may extrapolate. The case t=1t=1, with β~1=0\tilde\beta_1=0, requires specific treatment. Their hybrid objective adds Lsimple+0,001LVLBL_{\mathrm{simple}}+0{,}001 L_{\mathrm{VLB}} and stops the mean gradient in the variational term, letting that term guide the variance. This constant and gradient choice describe their experiment, not a mandatory rule for all models.

EMA, precision and memory

The exponential moving average of weights maintains a copy θˉ\bar\theta and updates θˉ←βθˉ+(1−β)θ\bar\theta\leftarrow\beta\bar\theta+(1-\beta)\theta after each optimizer step. Saving it alongside the checkpoint allows evaluation of raw and EMA weights. Warmup can gradually increase decay or copy weights initially: state the scheme, because starting a very slow average too early retains a large initialization influence.

With fixed β\beta, the contribution of an iterate from kk steps ago is proportional to βk\beta^k; its half-life is log⁡(1/2)/log⁡β\log(1/2)/\log\beta. For 50,000 updates, values such as 0.999 and 0.9999 average over different scales. No decay is universally optimal: compare them with the same protocol and budget. Karras and colleagues analyze training dynamics and EMA choices.

Mixed precision reduces the size of many activations and accelerates compatible operations. With float16, use gradient scaling and check whether overflow skips any steps; keep the schedule, sensitive accumulations and states that need it in suitable precision. Gradient accumulation simulates a larger effective batch only if losses are scaled correctly and each layer’s updates are considered; update EMA at the effective optimizer step. On an 8 GB GPU, measure the actual peak memory, including optimizer, gradients and buffers. An isolated activation calculation is an estimate, not a peak measurement.

Lab: parameterizations and log-SNR weights

In a VP process, xₜ = a x₀ + σ ε and a² + σ² = 1. The first cell transforms predictions between ε, x₀, v and score for the same xₜ. Verify their error relationships and distinguish conversions requiring division by a or σ. The v rotation also works at both endpoints: at a = 0 it recovers x₀ = −v without dividing by zero.

The second implements the discrete cosine schedule with β capped at 0.999 and then Lin rescaling. The first noisy level is preserved and the terminal level is checked to have ᾱ_T = 0 and β_T = 1. A sampler must explicitly handle this singular endpoint; formulas dividing by √α_T cannot be applied.

The third expresses losses relative to the ε error for the same predictor. In λ = log SNR, density includes the sampling density of t and the Jacobian 1/|dλ/dt|. Compare quadrature in t and λ and Monte Carlo for Min-SNR with γ = 5 over the interior interval [0.02, 0.98]. The interval excludes singular endpoints; this numerical equality is not extrapolated to an improper integral without checking convergence. Cells share variables and run in order.

[ ]Target conversion and endpointsBrowser
"""Conversiones exactas de objetivos VP, con extremos explícitos."""
import numpy as np


def require_vp(a, sigma):
    if a < 0 or sigma < 0 or not np.isclose(a * a + sigma * sigma, 1, atol=1e-12, rtol=0):
        raise ValueError('Se requieren a, σ no negativos y a² + σ² = 1')


def from_v(xt, v, a, sigma):
    require_vp(a, sigma)
    return a * xt - sigma * v, sigma * xt + a * v


def from_epsilon(xt, eps, a, sigma):
    require_vp(a, sigma)
    if a == 0:
        raise ValueError('No se puede recuperar x₀ desde ε cuando a=0')
    return (xt - sigma * eps) / a, eps


def from_x0(xt, x0, a, sigma):
    require_vp(a, sigma)
    if sigma == 0:
        raise ValueError('No se puede recuperar ε desde x₀ cuando σ=0')
    return x0, (xt - a * x0) / sigma


def from_score(xt, score, a, sigma):
    require_vp(a, sigma)
    if sigma == 0:
        raise ValueError('La conversión del score de ruido requiere σ>0')
    return from_epsilon(xt, -sigma * score, a, sigma)


def score_from_epsilon(eps, sigma):
    if sigma <= 0:
        raise ValueError('La conversión al score requiere σ>0')
    return -eps / sigma


rng = np.random.default_rng(1801)
x0 = rng.normal(size=(1024, 3))
eps = rng.normal(size=x0.shape)
a, sigma = .6, .8
xt = a * x0 + sigma * eps
v = a * eps - sigma * x0
conditional_score = -eps / sigma
for fn, target in ((from_epsilon, eps), (from_x0, x0), (from_v, v), (from_score, conditional_score)):
    x_rec, e_rec = fn(xt, target, a, sigma)
    assert np.allclose(x_rec, x0, atol=1e-12, rtol=0)
    assert np.allclose(e_rec, eps, atol=1e-12, rtol=0)
# Un mismo error de v produce errores relacionados entre las parametrizaciones.
v_hat = v + rng.normal(size=v.shape) * .3
x_hat, e_hat = from_v(xt, v_hat, a, sigma)
ev = np.mean(np.sum((v_hat - v) ** 2, axis=1))
ex = np.mean(np.sum((x_hat - x0) ** 2, axis=1))
ee = np.mean(np.sum((e_hat - eps) ** 2, axis=1))
es = np.mean(np.sum((score_from_epsilon(e_hat, sigma) - conditional_score) ** 2, axis=1))
snr = a * a / (sigma * sigma)
assert np.allclose([ex, ev, es], [ee / snr, ee / (a * a), ee / (sigma * sigma)])
print(f'SNR={snr:.5f}: error ε={ee:.6f}, x₀={ex:.6f}, v={ev:.6f}, score={es:.6f}.')
# La rotación por v conserva información también en ambos extremos.
assert all(np.allclose(u, w) for u, w in zip(from_v(x0, eps, 1., 0.), (x0, eps)))
assert all(np.allclose(u, w) for u, w in zip(from_v(eps, -x0, 0., 1.), (x0, eps)))
for fn, args in ((from_epsilon, (eps, eps, 0., 1.)),
                 (from_x0, (x0, x0, 1., 0.)),
                 (from_score, (x0, conditional_score, 1., 0.))):
    try:
        fn(*args)
        raise AssertionError('La conversión singular debe rechazarse')
    except ValueError:
        pass
print('Conversión v finita en σ=0 y a=0; divisiones singulares rechazadas.')
[ ]Cosine and zero terminal SNRBrowser
"""Coseno de Nichol y Dhariwal y rescalado de Lin para SNR terminal cero."""


def cosine_schedule(T, offset=.008, max_beta=.999):
    if T < 2 or offset < 0 or not 0 < max_beta < 1:
        raise ValueError('Parámetros de schedule inválidos')
    u = np.arange(T + 1, dtype=np.float64) / T
    f = np.cos((u + offset) / (1 + offset) * np.pi / 2) ** 2
    beta = np.minimum(1 - f[1:] / f[:-1], max_beta)
    return np.concatenate(([0.], beta))


def zero_terminal_snr(beta):
    beta = np.asarray(beta, dtype=np.float64)
    if len(beta) < 3 or beta[0] != 0 or np.any(beta[1:] <= 0) or np.any(beta[1:] >= 1):
        raise ValueError('Se esperan β₀=0 y 0<βₜ<1')
    root = np.sqrt(np.cumprod(1 - beta)[1:])
    first, last = root[0], root[-1]
    if first <= last:
        raise ValueError('El primer nivel debe contener más señal que el terminal')
    transformed = (root - last) * first / (first - last)
    new_bar = np.concatenate(([1.], transformed ** 2))
    new_beta = np.concatenate(([0.], 1 - new_bar[1:] / new_bar[:-1]))
    return new_beta, new_bar


original_beta = cosine_schedule(1000)
original_bar = np.cumprod(1 - original_beta)
fixed_beta, fixed_bar = zero_terminal_snr(original_beta)
assert np.isclose(original_bar[1], fixed_bar[1], atol=1e-15, rtol=0)
assert fixed_bar[-1] == 0 and fixed_beta[-1] == 1
assert np.all(fixed_beta[1:-1] > 0) and np.all(fixed_beta[1:-1] < 1)
assert np.all(np.diff(fixed_bar) < 0)
print(f'Coseno capado: ᾱ₁={original_bar[1]:.10f}, ᾱ_T={original_bar[-1]:.10g}.')
print(f'Lin: ᾱ₁={fixed_bar[1]:.10f}, ᾱ_T={fixed_bar[-1]:.1f}, β_T={fixed_beta[-1]:.1f}.')
# La conversión desde v es finita incluso al final de ruido puro.
terminal_x, terminal_eps = from_v(eps, -x0, np.sqrt(fixed_bar[-1]), np.sqrt(1 - fixed_bar[-1]))
assert np.all(np.isfinite(terminal_x)) and np.allclose(terminal_x, x0)
assert np.allclose(terminal_eps, eps)
print('En el terminal, v=-x₀ y la conversión a x₀ permanece finita.')
[ ]Weighting and log SNRBrowser
"""Cambio de variable a log SNR y control por cuadratura y Monte Carlo."""


def continuous_cosine(u, offset=.008):
    u = np.asarray(u, dtype=np.float64)
    theta = (u + offset) / (1 + offset) * np.pi / 2
    theta0 = offset / (1 + offset) * np.pi / 2
    abar = (np.cos(theta) / np.cos(theta0)) ** 2
    derivative = -np.pi / (2 * (1 + offset)) * np.sin(2 * theta) / np.cos(theta0) ** 2
    lam = np.log(abar) - np.log1p(-abar)
    dlam = derivative / (abar * (1 - abar))
    return abar, lam, dlam


def relative_factor(kind, abar):
    if np.any(abar <= 0) or np.any(abar >= 1):
        raise ValueError('Los factores se expresan solo en el interior 0<ᾱ<1')
    if kind == 'epsilon':
        return np.ones_like(abar)
    if kind == 'x0':
        return (1 - abar) / abar
    if kind == 'v':
        return 1 / abar
    if kind == 'score':
        return 1 / (1 - abar)
    raise ValueError('Parametrización desconocida')


def min_snr_weight(kind, abar, gamma=5.):
    snr = abar / (1 - abar)
    clipped = np.minimum(snr, gamma)
    if kind == 'epsilon':
        return clipped / snr
    if kind == 'x0':
        return clipped
    if kind == 'v':
        return clipped / (snr + 1)
    raise ValueError('Min-SNR aquí solo está definido para ε, x₀ y v')


def integral(y, x):
    return np.sum((y[1:] + y[:-1]) * np.diff(x) / 2)


lo, hi = .02, .98
u = np.linspace(lo, hi, 30001)
abar_grid, lam, dlam = continuous_cosine(u)
assert np.all(np.diff(lam) < 0) and np.all(dlam < 0)
pdf_uniform = np.full_like(u, 1 / (hi - lo))
pdf_tilted = 2 * u / (hi * hi - lo * lo)

# Para cada parametrización, su receta Min-SNR induce el mismo peso relativo
# al error de ε, siempre que las predicciones se correspondan exactamente.
effective = [min_snr_weight(kind, abar_grid) * relative_factor(kind, abar_grid)
             for kind in ('epsilon', 'x0', 'v')]
assert np.allclose(effective[0], effective[1]) and np.allclose(effective[0], effective[2])
weight = effective[0]
pdf = pdf_tilted
density = pdf * weight / np.abs(dlam)
by_time = integral(pdf * weight, u)
by_logsnr = integral(density[::-1], lam[::-1])
assert abs(by_time - by_logsnr) < 1e-7

# Muestra de un pdf proporcional a t en el intervalo acotado; nueva semilla.
mc_rng = np.random.default_rng(1802)
draws = np.sqrt(lo * lo + (hi * hi - lo * lo) * mc_rng.random(100000))
abar_mc = continuous_cosine(draws)[0]
mc = np.mean(min_snr_weight('v', abar_mc) * relative_factor('v', abar_mc))
assert abs(mc - by_time) < .006
print(f'Min-SNR γ=5 y p(t) proporcional a t: integral en t={by_time:.6f}; integral en log SNR={by_logsnr:.6f}; Monte Carlo={mc:.6f}.')
for name, p in (('uniforme', pdf_uniform), ('proporcional a t', pdf_tilted)):
    print(f'ε sin ponderar, p(t) {name}: integral={integral(p * relative_factor("epsilon", abar_grid), u):.6f}.')
print('La densidad expresada en log SNR incluye el jacobiano; no se evalúa en los extremos singulares.')

The next cell calculates continuous cosine log SNR halfway through the interval and compares EMA scales. It does not use the discrete β\beta clipping.

[ ]Cosine midpoint and EMA scalesBrowser
import numpy as np

s = 0.008
abar_half = (np.cos((0.5+s)/(1+s)*np.pi/2) /
             np.cos(s/(1+s)*np.pi/2))**2
logsnr_half = np.log(abar_half/(1-abar_half))
print(f'coseno continuo: ᾱ(0.5)={abar_half:.11f}; log SNR={logsnr_half:.11f}')
for decay in (0.999, 0.9999):
    print(f'EMA {decay}: semivida={np.log(0.5)/np.log(decay):.2f} pasos')

Exercises

ProofCompare the same predictor
Prove: Prove the relationships between ε, x₀ and v errors for a VP process.
0
Fix xₜ and a level with a > 0, σ > 0 and a² + σ² = 1. Convert the same prediction between parameterizations.

Step 1 of 3. What relationship must x₀ and ε errors satisfy?

NumericLog SNR halfway through
For the normalized continuous cosine with s = 0.008, what is log(ᾱ/(1−ᾱ)) at t/T = 0.5? Use the natural logarithm and give four decimal places.
QuizDetect a terminal discrepancy
In the case studied by Lin and colleagues, a chain is trained with positive terminal SNR and initialized from pure noise at generation. What diagnosis and correction are reasonable?
QuizChoose an EMA scale
You will train for 50,000 steps and want an average retaining information for hundreds of steps, with explicit startup. What is a reasonable starting choice?
CodeAn endpoint without division by zero
Implement cosine_schedule(T,s=0.008,max_beta=0.999), zero_terminal_snr(beta) and x0_from_v(xt,v,abar). The first returns beta and abar indexed 0..T: beta[0]=0, abar[0]=1, and each later beta comes from the cosine ratio and is clipped to max_beta before accumulation. The second rescales square roots of abar at times 1..T to preserve a₁ and set aT=0; reconstruct and return a new beta without modifying the input. The third uses x₀ = √abar·xt − √(1−abar)·v, even at abar=0.
import numpy as np

def cosine_schedule(T, s=0.008, max_beta=0.999):
  pass

def zero_terminal_snr(beta):
  pass

def x0_from_v(xt, v, abar):
  pass
Shift+Enter to run

Local lab: diffusion U-Net and CIFAR-10 ablations

Build a U-Net for 32 by 32 RGB images from scratch. The full model has width 128 and 18,477,315 parameters: it uses residual blocks, skips between resolutions, attention at 16 and 8, sinusoidal time embeddings and AdaGN. In each block the time projection produces scale and shift to modulate GroupNorm output, following Dhariwal and Nichol. The exact architecture is that of the tracer above.

The experiment trains four independent networks: linear or cosine schedule, each with ϵ\epsilon or vv prediction. They share initialization, data order, time and noise seeds, attempt count and batch size; this facilitates comparison but does not eliminate training variability. Each attempt accumulates four microbatches of eight images before updating. CUDA uses float16 autocast and GradScaler; the schedule and cumulative products are built in float64. The scaler can reject a step on overflow: code records attempts, skipped steps and effective updates. EMA starts as an exact copy, warms its coefficient up to 0.9999 and updates only after an effective step. CPU uses float32 without AMP scaling.

The ancestral sampler uses the posterior mean expressed through x^0\hat x_0 and variance βt\beta_t, without noise in the last step or internal clipping. With vv, x^0=atxt−σtv^\hat x_0=a_t x_t-\sigma_t\hat v remains finite when aT=0a_T=0. Optionally, ORYON_ZERO_SNR=1 applies the zero terminal SNR correction and requires selecting a linear-v or cosine-v case via ORYON_CASE. Conversion from ϵ\epsilon is rejected at that endpoint because it divides by aT=0a_T=0. The default ablation keeps positive terminal SNR to compare all four variants with the same schedule within each pair.

As in lesson 16’s Inception lab, evaluation uses 2048-dimensional Inception features from clean-fid==0.1.35, a separate CIFAR-10 test reference, clipping to [0,1][0,1], RGB quantization to uint8 and clean bicubic resizing to 299 by 299. Fréchet distance is calculated using the low-rank identity and checked against an independent matrix formula. Raw and EMA runs start from the same noise seeds; the fraction of generated values outside the interval before clipping is reported. Finite-sample FID results are biased and the full protocol must match before comparing models or papers. Extractor hash, seeds, sizes, data selection and configuration are saved in each report.json. Zero-terminal-SNR runs use the -zero-snr folder suffix to keep results alongside the conventional schedule.

Install torch, torchvision, numpy, pillow and clean-fid==0.1.35. By default ORYON_CASE=all runs all four combinations; it also accepts linear-epsilon, linear-v, cosine-epsilon and cosine-v. ORYON_DATA_ROOT controls the CIFAR-10 cache, ORYON_OUTPUT_DIR the output and ORYON_INCEPTION_PT the path ending in inception-2015-12-05.pt. If weights are missing, the program downloads them from NVIDIA’s source. By default full mode uses all CIFAR-10 training images, T=1000T=1000, 50,000 attempts per case and 1024 test and generated images; ORYON_UPDATES and ORYON_EVAL_COUNT change these budgets. The four training runs and ancestral sampling are expensive: a short test does not predict their duration or quality. Network, EMA, optimizer, scaler and configuration are saved, but the example does not implement automatic resume.

With ORYON_QUICK=1, use 64 training images, a smaller network, two attempts per case, 20 diffusion steps and 8 images per group. To reuse local parquet only in this mode, set ORYON_CIFAR_PARQUET and install pyarrow: the first 64 train rows and first 8 test rows are used. With torchvision, quick mode selects 64 examples from a train permutation with seed 1810 and the first 8 test images; both cases shuffle train with seed 1813. In a parquet check run, raw/EMA FIDs were approximately 553.2/553.1 for linear ϵ\epsilon, 555.9/555.7 for linear vv, 537.9/537.8 for cosine ϵ\epsilon and 548.0/548.0 for cosine vv. For cosine ϵ\epsilon almost all components were out of range before clipping. Those values with eight samples and two attempts only check the pipeline: they do not demonstrate learning, an EMA advantage or an ablation conclusion.

Before training, the parameter count, AdaGN gradients, a finite AMP update and an induced overflow that advances neither parameters nor EMA are checked. Conversions in both schedules, the zero-SNR endpoint, absence of final noise and the Fréchet formula are also checked. An independent synthetic single-update test with the full network and microbatch 8 checked its shapes and gradients; it does not replace training or guarantee peak memory for every phase.

[ ]Diffusion U-Net and CIFAR-10 ablationsLocal GPU
"""Ablación de U-Net de difusión en CIFAR-10.

Dependencias: torch, torchvision, numpy, pillow, scipy y clean-fid==0.1.35.
ORYON_QUICK=1 reduce arquitectura, datos y trabajo. ORYON_DATA_ROOT y
ORYON_OUTPUT_DIR controlan datos y resultados; ORYON_INCEPTION_PT localiza pesos.
ORYON_CIFAR_PARQUET solo reutiliza parquet en modo quick.
"""
import copy
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)


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 coeff(values, t, x):
    return values[t].to(dtype=x.dtype).reshape(-1, *([1] * (x.ndim - 1)))


def target(x0, noise, t, schedule, parameterization):
    bar = coeff(schedule['bar'], t, x0)
    if parameterization == 'epsilon':
        return noise
    if parameterization == 'v':
        return bar.sqrt() * noise - (1 - bar).sqrt() * x0
    raise ValueError('La parametrización debe ser epsilon o v')


def infer_x0(xt, prediction, t, schedule, parameterization):
    bar = coeff(schedule['bar'], t, xt)
    if parameterization == 'v':
        return bar.sqrt() * xt - (1 - bar).sqrt() * prediction
    if parameterization == 'epsilon':
        if torch.any(bar <= 0):
            raise ValueError('La predicción epsilon divide por cero con SNR terminal cero')
        return (xt - (1 - bar).sqrt() * prediction) / bar.sqrt()
    raise ValueError('La parametrización debe ser epsilon o v')


def posterior_mean(xt, x0_hat, t, schedule):
    beta = coeff(schedule['beta'], t, xt)
    bar = coeff(schedule['bar'], t, xt)
    prev = coeff(schedule['previous'], t, xt)
    return beta * prev.sqrt() / (1 - bar) * x0_hat + (1-beta).sqrt() * (1-prev) / (1-bar) * xt


def p_sample(model, xt, t, noise, schedule, parameterization):
    pred = model(xt, t, schedule['T'])
    x0_hat = infer_x0(xt, pred, t, schedule, parameterization)
    mean = posterior_mean(xt, x0_hat, t, schedule)
    beta = coeff(schedule['beta'], t, xt)
    mask = (t > 1).to(xt.dtype).reshape(-1, *([1] * (xt.ndim - 1)))
    return mean + mask * beta.sqrt() * noise


@torch.no_grad()
def update_ema(ema, model, step, max_decay=.9999):
    decay = min(max_decay, (1 + step) / (10 + step))
    for avg, current in zip(ema.parameters(), model.parameters(), strict=True):
        avg.mul_(decay).add_(current, alpha=1-decay)
    for avg, current in zip(ema.buffers(), model.buffers(), strict=True):
        avg.copy_(current)
    return decay


def optimizer_and_ema_step(scaler, optimizer, model, ema, completed):
    """No avanza EMA ni el contador si GradScaler rechaza la actualización."""
    previous_scale = scaler.get_scale()
    scaler.step(optimizer)
    scaler.update()
    skipped = scaler.get_scale() < previous_scale
    if skipped:
        return completed, True
    completed += 1
    update_ema(ema, model, completed)
    return completed, False


def low_rank_fid(real, fake):
    """Misma identidad de rango bajo empleada por la lección m19-l16."""
    real, fake = np.asarray(real, np.float64), np.asarray(fake, np.float64)
    if (real.ndim != 2 or fake.ndim != 2 or real.shape[1] != fake.shape[1] or
            min(len(real), len(fake)) < 2 or not np.isfinite(real).all() or not np.isfinite(fake).all()):
        raise ValueError('Las características deben ser finitas y compatibles')
    x, y = real - real.mean(0), fake - fake.mean(0)
    trace_x, trace_y = (x*x).sum() / (len(x)-1), (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))
    result = float(np.square(real.mean(0)-fake.mean(0)).sum() + trace_x + trace_y - 2 * cross)
    if result < -1e-7 * max(1., trace_x + trace_y):
        raise ValueError('Fréchet negativo fuera de tolerancia numérica')
    return max(result, 0.)


def check_all(device):
    # La cuenta se hace en meta, sin reservar la red completa en GPU o RAM.
    with torch.device('meta'):
        full = DiffusionUNet(128)
    count = sum(p.numel() for p in full.parameters())
    assert 15_000_000 <= count <= 35_000_000 and count == 18_477_315
    del full
    torch.manual_seed(1801)
    x0 = torch.randn((2, 3, 8, 8), device=device)
    noise = torch.randn_like(x0)
    for kind in ('linear', 'cosine'):
        schedule = make_schedule(kind, 20, device)
        corrected = make_schedule(kind, 20, device, zero_terminal=True)
        assert corrected['bar'][-1].item() == 0 and corrected['beta'][-1].item() == 1
        assert torch.allclose(corrected['bar'][1], schedule['bar'][1])
        assert torch.all(torch.diff(corrected['bar']) < 0)
        t = torch.tensor([7, 20], device=device, dtype=torch.long)
        abar = coeff(corrected['bar'], t, x0)
        xt = abar.sqrt() * x0 + (1 - abar).sqrt() * noise
        v = target(x0, noise, t, corrected, 'v')
        assert torch.allclose(infer_x0(xt, v, t, corrected, 'v'), x0, atol=1e-6)
        assert torch.isfinite(posterior_mean(xt, x0, t, corrected)).all()
        try:
            infer_x0(xt, noise, t, corrected, 'epsilon')
        except ValueError:
            pass
        else:
            raise AssertionError('Debe rechazarse epsilon en el extremo de SNR cero')
        t1 = torch.ones(2, device=device, dtype=torch.long)
        class Oracle(nn.Module):
            def forward(self, x, t, T):
                return torch.zeros_like(x)
        left = p_sample(Oracle(), x0, t1, torch.ones_like(x0), corrected, 'v')
        right = p_sample(Oracle(), x0, t1, -torch.ones_like(x0), corrected, 'v')
        assert torch.equal(left, right)
    # Proyección temporal AdaGN y backward genuino en la misma U-Net reducida.
    model = DiffusionUNet(8).to(device)
    model.train()
    example_t = torch.tensor([3, 10], device=device, dtype=torch.long)
    loss = model(x0, example_t, 20).square().mean()
    loss.backward()
    g = model.enc32a.condition.weight.grad
    assert g is not None and torch.isfinite(g).all() and g.abs().sum() > 0
    ema = copy.deepcopy(model).requires_grad_(False)
    before = ema.output.bias.detach().clone()
    with torch.no_grad():
        model.output.bias.add_(2)
    factor = update_ema(ema, model, 1)
    assert torch.allclose(ema.output.bias, before + 2 * (1 - factor), atol=1e-6)
    assert 0 < factor < .9999
    optimizer = torch.optim.AdamW(model.parameters(), lr=.0002)
    scaler = torch.amp.GradScaler('cuda', enabled=device.type == 'cuda')
    # GradScaler puede saltar pasos al ajustar su escala inicial; se comprueba
    # que, tras corregirla, una actualización real tenga gradientes finitos.
    for attempt in range(12):
        optimizer.zero_grad(set_to_none=True)
        with torch.autocast(device_type=device.type, dtype=torch.float16, enabled=device.type == 'cuda'):
            amp_loss = model(x0, example_t, 20).float().square().mean()
        scaler.scale(amp_loss).backward()
        scaler.unscale_(optimizer)
        finite = all(torch.isfinite(p.grad).all() for p in model.parameters() if p.grad is not None)
        scaler.step(optimizer)
        scaler.update()
        if finite:
            break
    assert finite
    # Induce desbordamiento para comprobar que no cambien ni parámetros ni EMA.
    if device.type == 'cuda':
        optimizer.zero_grad(set_to_none=True)
        with torch.autocast(device_type='cuda', dtype=torch.float16):
            deliberate = model(x0, example_t, 20).float().square().mean()
        scaler.scale(deliberate).backward()
        model.output.bias.grad.fill_(float('inf'))
        scaler.unscale_(optimizer)
        old_model = model.output.bias.detach().clone()
        old_ema = ema.output.bias.detach().clone()
        completed, skipped = optimizer_and_ema_step(scaler, optimizer, model, ema, 7)
        assert skipped and completed == 7
        assert torch.equal(model.output.bias, old_model) and torch.equal(ema.output.bias, old_ema)
    # Fréchet contra raíz simétrica en un ejemplo independiente de rango completo.
    rng = np.random.default_rng(1802)
    a, b = rng.normal(size=(12, 4)), rng.normal(size=(10, 4))
    ca, cb = np.cov(a, rowvar=False), np.cov(b, rowvar=False)
    eig, vec = np.linalg.eigh(ca)
    root = (vec * np.sqrt(np.maximum(eig, 0))) @ vec.T
    middle = root @ cb @ root
    expected = np.square(a.mean(0)-b.mean(0)).sum() + np.trace(ca) + np.trace(cb) - 2 * np.sqrt(
        np.maximum(np.linalg.eigvalsh((middle + middle.T) / 2), 0)).sum()
    assert abs(low_rank_fid(a, b) - expected) < 1e-10
    print(f'Controles: U-Net {count} parámetros, gradientes AdaGN, AMP (descensos iniciales {attempt}), '
          'salto de AMP/EMA, SNR cero, conversión y Fréchet correctos.', flush=True)
    del model, ema, optimizer
    if device.type == 'cuda':
        torch.cuda.empty_cache()


class ParquetCifar(Dataset):
    def __init__(self, folder, split, count):
        import pyarrow.parquet as pq
        self.images = []
        self.files_used = []
        for path in sorted(Path(folder).glob(f'{split}-*.parquet')):
            self.files_used.append(str(path))
            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, index):
        with Image.open(io.BytesIO(self.images[index])) as image:
            return transforms.ToTensor()(image.convert('RGB')), 0


def get_data(root, quick, parquet, n_eval):
    if quick and parquet:
        train = ParquetCifar(parquet, 'train', 64)
        test = ParquetCifar(parquet, 'test', n_eval)
        metadata = {'source': 'parquet', 'train_selection': 'primeras 64 filas de train',
                    'test_selection': f'primeras {n_eval} filas de test', 'selection_seed': None,
                    'train_files_used': train.files_used, 'test_files_used': test.files_used,
                    'training_shuffle_seed': 1813}
        return train, test, metadata
    train = datasets.CIFAR10(root, train=True, download=True, transform=transforms.ToTensor())
    test = datasets.CIFAR10(root, train=False, download=True, transform=transforms.ToTensor())
    if quick:
        order = torch.randperm(len(train), generator=torch.Generator().manual_seed(1810)).tolist()
        train = Subset(train, order[:64])
    metadata = {'source': 'torchvision CIFAR10',
                'train_selection': 'primeras 64 de una permutación' if quick else 'todos los ejemplos de train',
                'test_selection': f'primeras {n_eval} filas de test',
                'selection_seed': 1810 if quick else None, 'training_shuffle_seed': 1813,
                'data_root': str(root)}
    return train, Subset(test, range(n_eval)), metadata


def inception_file():
    default = Path.home() / '.cache' / 'huggingface' / 'oryon-generative-weights' / 'inception-2015-12-05.pt'
    path = Path(os.environ.get('ORYON_INCEPTION_PT', str(default)))
    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)
    return path


def image_features(images, inception, device):
    resize = build_resizer('clean')
    output = []
    with torch.inference_mode():
        for start in range(0, len(images), 4):
            pixels = (images[start:start+4].clamp(0, 1) * 255).round().to(torch.uint8)
            arrays = pixels.permute(0, 2, 3, 1).cpu().numpy()
            resized = np.stack([resize(array).transpose(2, 0, 1) for array in arrays])
            output.append(inception(torch.from_numpy(resized).to(device)).cpu().numpy())
    return np.concatenate(output)


def sampling(model, schedule, parameterization, count, device, seed, quick):
    generator = torch.Generator(device=device).manual_seed(seed)
    samples = []
    batch = 4 if quick else 16
    model.eval()
    with torch.no_grad():
        for start in range(0, count, batch):
            size = min(batch, count - start)
            x = torch.randn((size, 3, 32, 32), device=device, generator=generator)
            for step in range(schedule['T'], 0, -1):
                t = torch.full((size,), step, device=device, dtype=torch.long)
                noise = (torch.randn(x.shape, device=device, generator=generator)
                         if step > 1 else torch.zeros_like(x))
                x = p_sample(model, x, t, noise, schedule, parameterization)
                if not torch.isfinite(x).all():
                    raise FloatingPointError('La cadena ancestral dejó de ser finita')
            samples.append(x.cpu())
    return torch.cat(samples)


def train_case(kind, parameterization, train, data_metadata, reference_features, inception_path, inception_hash, output_root,
               quick, n_eval, device, zero_terminal):
    if zero_terminal and parameterization == 'epsilon':
        raise ValueError('En SNR terminal cero ejecuta v, no la conversión singular de epsilon')
    T, width, microbatch, accumulation = (20, 8, 4, 2) if quick else (1000, 128, 8, 4)
    updates = 2 if quick else int(os.environ.get('ORYON_UPDATES', '50000'))
    if updates < 1:
        raise ValueError('ORYON_UPDATES debe ser positivo')
    schedule = make_schedule(kind, T, device, zero_terminal)
    # Mismos pesos iniciales, orden y ruido para cada caso de la ablación.
    torch.manual_seed(1812)
    model = DiffusionUNet(width).to(device)
    ema = copy.deepcopy(model).eval().requires_grad_(False)
    optimizer = torch.optim.AdamW(model.parameters(), lr=.0002)
    scaler = torch.amp.GradScaler('cuda', enabled=device.type == 'cuda')
    loader = DataLoader(train, batch_size=microbatch, shuffle=True, drop_last=True, num_workers=0,
                        generator=torch.Generator().manual_seed(1813))
    batches = iter(loader)
    generator = torch.Generator(device=device).manual_seed(1814)
    run_id = f'{kind}-{parameterization}' + ('-zero-snr' if zero_terminal else '')
    out = Path(output_root) / run_id
    out.mkdir(parents=True, exist_ok=True)
    history, skipped, completed = [], 0, 0
    if device.type == 'cuda':
        torch.cuda.reset_peak_memory_stats(device)
    for step in range(1, updates + 1):
        model.train()
        optimizer.zero_grad(set_to_none=True)
        accumulated = 0.
        for _ in range(accumulation):
            try:
                images, _ = next(batches)
            except StopIteration:
                batches = iter(loader)
                images, _ = next(batches)
            clean = images.to(device) * 2 - 1
            t = torch.randint(1, T+1, (len(clean),), device=device, generator=generator)
            noise = torch.randn(clean.shape, device=device, generator=generator)
            bar = coeff(schedule['bar'], t, clean)
            xt = bar.sqrt() * clean + (1-bar).sqrt() * noise
            truth = target(clean, noise, t, schedule, parameterization)
            with torch.autocast(device_type=device.type, dtype=torch.float16, enabled=device.type == 'cuda'):
                prediction = model(xt, t, T)
                loss = (prediction.float() - truth).square().mean()
            if not torch.isfinite(loss):
                raise FloatingPointError('La pérdida dejó de ser finita')
            scaler.scale(loss / accumulation).backward()
            accumulated += loss.item() / accumulation
        scaler.unscale_(optimizer)
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.)
        completed, was_skipped = optimizer_and_ema_step(scaler, optimizer, model, ema, completed)
        if was_skipped:
            skipped += 1
        if step == 1 or step == updates or step % 500 == 0:
            history.append({'attempt': step, 'effective_updates': completed, 'loss': accumulated, 'skipped': skipped})
            print(f'{kind}/{parameterization} paso {step}: pérdida {accumulated:.6f}, '
                  f'AMP saltados {skipped}', flush=True)
    peak = torch.cuda.max_memory_allocated(device) if device.type == 'cuda' else None
    checkpoint = {'model': model.state_dict(), 'ema': ema.state_dict(), 'optimizer': optimizer.state_dict(),
                  'scaler': scaler.state_dict(), 'width': width, 'T': T, 'schedule': kind,
                  'parameterization': parameterization, 'zero_terminal': zero_terminal,
                  'attempts': updates, 'effective_updates': completed, 'skipped': skipped, 'history': history}
    torch.save(checkpoint, out / 'diffusion.pt')
    restored = torch.load(out / 'diffusion.pt', map_location=device, weights_only=True)
    assert all(torch.equal(restored['ema'][key], value) for key, value in ema.state_dict().items())
    del checkpoint, restored, optimizer, scaler, batches
    # Las dos ramas consumen las mismas semillas, puntos iniciales y ruidos por paso.
    raw = sampling(model, schedule, parameterization, n_eval, device, 1815, quick)
    averaged = sampling(ema, schedule, parameterization, n_eval, device, 1815, quick)
    raw_outside = float(((raw < -1) | (raw > 1)).float().mean())
    ema_outside = float(((averaged < -1) | (averaged > 1)).float().mean())
    save_image(((raw[:16] + 1)/2).clamp(0, 1), out / 'raw.png', nrow=4)
    save_image(((averaged[:16] + 1)/2).clamp(0, 1), out / 'ema.png', nrow=4)
    del model, ema, clean, noise, xt, prediction, loss
    if device.type == 'cuda':
        torch.cuda.empty_cache()
    inception = InceptionV3W(str(inception_path.parent), download=False, resize_inside=False).to(device).eval()
    raw_features = image_features((raw + 1) / 2, inception, device)
    ema_features = image_features((averaged + 1) / 2, inception, device)
    raw_fid, ema_fid = low_rank_fid(reference_features, raw_features), low_rank_fid(reference_features, ema_features)
    np.savez_compressed(out / 'features.npz', reference=reference_features, raw=raw_features, ema=ema_features)
    report = {'case': f'{kind}-{parameterization}', 'run_id': run_id, 'quick': quick, 'zero_terminal': zero_terminal,
              'T': T, 'params': 18_477_315 if not quick else sum(p.numel() for p in DiffusionUNet(width).parameters()),
              'attempts': updates, 'effective_updates': completed, 'skipped_amp_updates': skipped, 'microbatch': microbatch,
              'gradient_accumulation': accumulation, 'effective_batch': microbatch * accumulation,
              'train_count': len(train), 'reference_split': 'CIFAR-10 test', 'n_real': n_eval, 'n_generated': n_eval,
              'data_selection': data_metadata,
              'initialization_seed': 1812, 'data_shuffle_seed': 1813, 'training_noise_seed': 1814,
              'sample_seed': 1815, 'history': history, 'fid_raw': raw_fid, 'fid_ema': ema_fid,
              'raw_fraction_outside_before_clip': raw_outside, 'ema_fraction_outside_before_clip': ema_outside,
              'fid_protocol': 'InceptionV3W clean-fid 0.1.35, RGB uint8, PIL float bicúbico a 299',
              'inception_sha256': inception_hash,
              'gpu_peak_allocated_bytes_training': peak, 'torch_version': str(torch.__version__)}
    (out / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
    print(f'{kind}/{parameterization}: FID crudo={raw_fid:.4f}, EMA={ema_fid:.4f}; '
          f'fuera de rango crudo={raw_outside:.4f}, EMA={ema_outside:.4f}', flush=True)
    print('FID con pocas muestras es sesgado; EMA y entrenamiento breves no garantizan mejora.', flush=True)
    del inception, raw, averaged
    if device.type == 'cuda':
        torch.cuda.empty_cache()


def main():
    quick = os.environ.get('ORYON_QUICK') == '1'
    zero = os.environ.get('ORYON_ZERO_SNR') == '1'
    chosen = os.environ.get('ORYON_CASE', 'all')
    cases = [('linear', 'epsilon'), ('linear', 'v'), ('cosine', 'epsilon'), ('cosine', 'v')]
    if chosen != 'all':
        cases = [case for case in cases if '-'.join(case) == chosen]
        if not cases:
            raise ValueError('ORYON_CASE debe ser all, linear-epsilon, linear-v, cosine-epsilon o cosine-v')
    if zero and any(parameterization == 'epsilon' for _, parameterization in cases):
        raise ValueError('Para ORYON_ZERO_SNR=1 selecciona una variante v con ORYON_CASE')
    root = os.environ.get('ORYON_DATA_ROOT', './data')
    output = os.environ.get('ORYON_OUTPUT_DIR', './diffusion-ablation')
    parquet = os.environ.get('ORYON_CIFAR_PARQUET')
    if parquet and not quick:
        raise ValueError('ORYON_CIFAR_PARQUET solo se utiliza en quick')
    n_eval = 8 if quick else int(os.environ.get('ORYON_EVAL_COUNT', '1024'))
    if n_eval < 2 or n_eval > 10000:
        raise ValueError('ORYON_EVAL_COUNT debe estar entre 2 y 10000')
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print(f'dispositivo {device}; quick {quick}; casos {cases}', flush=True)
    check_all(device)
    train, test, data_metadata = get_data(root, quick, parquet, n_eval)
    reference = torch.stack([test[i][0] for i in range(n_eval)])
    path = inception_file()
    digest = hashlib.sha256()
    with path.open('rb') as file:
        for block in iter(lambda: file.read(1024 * 1024), b''):
            digest.update(block)
    inception_hash = digest.hexdigest()
    print(f'Inception SHA256 {inception_hash}; referencia CIFAR-10 test, n={n_eval}', flush=True)
    inception = InceptionV3W(str(path.parent), download=False, resize_inside=False).to(device).eval()
    reference_features = image_features(reference, inception, device)
    del inception
    if device.type == 'cuda':
        torch.cuda.empty_cache()
    for kind, parameterization in cases:
        train_case(kind, parameterization, train, data_metadata, reference_features, path, inception_hash, output,
                   quick, n_eval, device, zero)


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
Key idea

Schedule, parameterization, time distribution and weights form a single objective. Exact conversions help compare it, but endpoints and conventions matter; EMA, precision and architecture must be part of the experimental protocol.