Module contents
Lesson 16 of 28Core 95 min

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 πN(μ1,I)+(1−π)N(μ2,I)\pi\Normal(\mu_1,I)+(1-\pi)\Normal(\mu_2,I) with 0<π<10<\pi<1. Write Δ=μ2−μ1\Delta=\mu_2-\mu_1, d=∥Δ∥d=\|\Delta\| and let r2(x)r_2(x) be the second component’s posterior responsibility. Differentiating the mixture gives exactly

sp(x)=−(x−μ1)+r2(x)Δ,r2(x)1−r2(x)=1−ππexp⁡(−d22+(x−μ1)⋅Δ).s_p(x)=-(x-\mu_1)+r_2(x)\Delta, \qquad \frac{r_2(x)}{1-r_2(x)} =\frac{1-\pi}{\pi}\exp\left(-\frac{d^2}{2}+(x-\mu_1)\cdot\Delta\right).

If ∥x−μ1∥≤r\|x-\mu_1\|\le r, Cauchy-Schwarz bounds (x−μ1)⋅Δ≤rd(x-\mu_1)\cdot\Delta\le rd. Since r2≤r2/(1−r2)r_2\le r_2/(1-r_2):

∥sp(x)+(x−μ1)∥≤d 1−ππexp⁡(−d22+rd).\left\|s_p(x)+(x-\mu_1)\right\| \le d\,\frac{1-\pi}{\pi}\exp\left(-\frac{d^2}{2}+rd\right).

With fixed rr and π\pi, the bound approaches zero as dd grows. Near μ1\mu_1 the field approaches the first Gaussian’s field, approximately independently of its weight. The argument is analogous near μ2\mu_2 with weights exchanged. If π\pi changes with dd or approaches zero very quickly, the weight ratio must also be controlled.

This does not mean the exact score loses all information about π\pi: 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.

InteractiveThe score cannot see weights near each mode

Initialization puts half the particles near each mean regardless of the target weights. Both methods receive the same Gaussian increments.

  • Closer to mean 1
  • Closer to mean 2
  • Means, draggable in the left plot

Two isotropic Gaussians have standard deviation 0.35 and weights π and 1 − π. Mixture responsibilities give the exact scores of the original and smoothed distributions. Updates follow x′ = x + α score(x) + √(2α)ξ. Each method uses 128 particles, 480 steps and seed 1610. Fixed noise uses α = 0.00735. Annealing uses 12 geometrically spaced levels from σ = 1.8 to 0.1, with 40 steps per level and α = 0.06σ². Annealing ends with residual noise and skips final denoising. Both methods use finite discretizations, so they cannot guarantee equilibrium or recovery of the mixture weights.

The fractions count particles by which mean is closer. They can differ from π when the components overlap, since the rule does not identify latent labels. The plot clips particles outside the axes, and the counts still include them. The difference shown depends on the positions, seeds and step budget.

0.90
480
Target weight of component 1
0.900
Fraction near mean 1, fixed noise
0.500
Fraction near mean 1, annealed
0.891
σ at the annealing level
0.100
Compare single-level and annealed chains in an explicit mixture. Finite frequencies depend on seeds, initialization and budget.

Smoothing at multiple scales and conditioning the network

For σ1>⋯>σL>0\sigma_1>\cdots>\sigma_L>0, define pσip_{\sigma_i} as the data distribution convolved with N(0,σi2I)\Normal(0,\sigma_i^2I). 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 yy and σi\sigma_i and approximates sθ(y,σi)≈∇ylog⁡pσi(y)s_\theta(y,\sigma_i)\approx\nabla_y\log p_{\sigma_i}(y). In Song and Ermon, 2019, the network trains on discrete noise levels with weighted denoising score matching. For example, if levels are uniformly selected:

L(θ)=12L∑i=1LEX,ϵ[∥σisθ(X+σiϵ,σi)+ϵ∥2].L(\theta)=\frac{1}{2L}\sum_{i=1}^L \mathbb E_{X,\epsilon}\left[\|\sigma_i s_\theta(X+\sigma_i\epsilon,\sigma_i)+\epsilon\|^2\right].

This loss multiplies by σi2\sigma_i^2 the distance from target −ϵ/σi-\epsilon/\sigma_i. 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.

InteractiveWhere the score makes mistakes

Each cell shows ‖learned score − exact score‖ at its center. Color intensity is comparable across levels.

  • Error intensity from 0 to 20, capped
  • Data centers

The network has 24 tanh units, takes (x₁, x₂, log σ), and outputs σ·score. The recorded weighted DSM training used 500 updates, batch size 96, learning rate 0.003, and seeds 1610, 1612 and 1613. The weights and procedure are in ncsn-short.json and export_ncsn.py, derived from the lesson lab. The data are an equal-weight mixture of four Gaussians with standard deviation 0.18. The exact score uses variance 0.18² + σ².

The uniform grid has 32 × 32 cell centers in [−4, 4]². RMS is √mean(‖error‖²) with no density weighting, and the maximum also uses only the grid. Color opacity saturates at error 20. The numeric readouts show the full values. This short run may not have converged, and errors can remain or vary nonmonotonically with σ.

0.180
Evaluated σ
0.180
Grid RMS error
23.857
Maximum on the grid
54.293
The map compares a fitted field with the exact score of a known model. Inspect both errors and the regions containing data.

Low average error under pσip_{\sigma_i} does not automatically control maximum error throughout the plane. Map results depend on model, data and training: increasing σ\sigma 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 i=1,…,Li=1,\ldots,L, use step αi>0\alpha_i>0 and repeat:

x←x+αisθ(x,σi)+2αi z,z∼N(0,I).x\leftarrow x+\alpha_i s_\theta(x,\sigma_i) +\sqrt{2\alpha_i}\,z,\qquad z\sim\Normal(0,I).

The Song and Ermon, 2020 algorithm uses this convention with αi=εσi2/σL2\alpha_i=\varepsilon\sigma_i^2/\sigma_L^2 so ε\varepsilon is the final-level step. The 2019 work instead writes hi=2αih_i=2\alpha_i, with displacement his/2h_i s/2 and noise hiz\sqrt{h_i}z. For identical transitions, the 2019 parameter ε\varepsilon 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 pσip_{\sigma_i} also does not mean an arbitrary cloud follows pσip_{\sigma_i} after one transition.

InteractiveCoarse to fine with annealed Langevin

The target is a checkerboard of eight Gaussians. Each level displays the exact score of the smoothed mixture.

Level 0 / 8
  • Particles
  • Component centers
  • Exact score direction

Eight Gaussians have equal weight 1/8 and standard deviation 0.18. They are centered on alternating squares. The smoothed mixture has component variance 0.18² + σ² and uses its exact score. Initialization draws 96 2D Gaussian samples with standard deviation 2 and seed 1620. Each step is x′ = x + α score(x) + √(2α)ξ, where α = 0.05σ² and the endpoints are σ = 1.5 and 0.12. Arrow lengths are compressed to show directions.

At the final level, Tweedie denoising applies x + σ² score(x,σ) to each particle. This gives the posterior mean of the Gaussian target conditional on the noisy state. Finite steps and the chosen budget can leave bias. The plot clips particles outside its visible axes.

8
20
Final output
Completed level
0 / 8
σ for the displayed field
1.500
Langevin steps
0 / 160
Follow particles and field at each scale; change the number of levels and transitions.

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 L=232L=232, γ≈1,037559\gamma\approx1,037559. 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 σ1\sigma_1 on the order of the greatest Euclidean distance between training examples. In their CIFAR-10 experiment they study σ1=50\sigma_1=50 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 DD dimensions. An isotropic Gaussian norm concentrates near Dσ\sqrt D\sigma, and a normal approximation to its radius motivates measuring overlap with

C(γ,D)=Φ ⁣(2D(γ−1)+3γ)−Φ ⁣(2D(γ−1)−3γ).C(\gamma,D)=\Phi\!\left(\sqrt{2D}(\gamma-1)+3\gamma\right) -\Phi\!\left(\sqrt{2D}(\gamma-1)-3\gamma\right).

The authors recommend approximately C=0,5C=0,5 as a trade-off in that model; Φ\Phi is the standard normal cumulative distribution. This guidance depends on DD and is not the exact mixing probability of an arbitrary NCSN. The original fit with pixels in [0,1][0,1] 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 N(0,σi2I)\Normal(0,\sigma_i^2I), a chain coordinate satisfies

xt+1=(1−αiσi2)xt+2αi zt,vt+1=(1−αiσi2)2vt+2αi.x_{t+1}=\left(1-\frac{\alpha_i}{\sigma_i^2}\right)x_t+\sqrt{2\alpha_i}\,z_t, \qquad v_{t+1}=\left(1-\frac{\alpha_i}{\sigma_i^2}\right)^2v_t+2\alpha_i.

The second equation calculates how variance vtv_t approaches that of the level in TT steps. If 0<αi<2σi20<\alpha_i<2\sigma_i^2, stationary variance of this discretization is σi2/(1−αi/(2σi2))\sigma_i^2/(1-\alpha_i/(2\sigma_i^2)), not exactly σi2\sigma_i^2. With step proportional to σi2\sigma_i^2, ratio αi/σi2=ε/σL2\alpha_i/\sigma_i^2=\varepsilon/\sigma_L^2 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 ε=2⋅10−5\varepsilon=2\cdot10^{-5} and T=100T=100; check the specific code convention, scale and cost before transferring those numbers.

Exponential parameter averaging maintains an independent copy θˉ\bar\theta. After each optimization step update θˉ←βθˉ+(1−β)θ\bar\theta\leftarrow\beta\bar\theta+(1-\beta)\theta and use that copy for generation. The paper typically uses β=0,999\beta=0,999 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:

x^=x+σL2sθ(x,σL).\hat x=x+\sigma_L^2s_\theta(x,\sigma_L).

If the score is exact and xx 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 LL: 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.

[ ]Gradients and analytical scoreBrowser
"""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.')
[ ]Separate training and testBrowser
"""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}')
[ ]Annealed Langevin and comparisonBrowser
"""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

ProofHow much the other mode matters
Prove: For a mixture of two isotropic Gaussians with identity covariance, prove that near μ₁ the score approaches that of the first component as separation increases.
0
Fix 0 < π < 1 and r > 0; write Δ = μ₂ − μ₁ and d = ‖Δ‖. Work with ‖x − μ₁‖ ≤ r.

Step 1 of 3. How is the mixture score written?

NumericSeparating geometric scales
A decreasing ladder has σ₁ = 50, σL = 0.01 and L = 232. What is the constant ratio γ = σᵢ/σᵢ₊₁? Give at least five decimal places.
QuizInitial scale and units
In a heuristic based on the largest observed distance, data are scaled so that distance is 80. What initial candidate and conclusion are reasonable?
CodeA ladder of chains
Implement annealed_langevin(score_fn, sigmas, n_steps_each, eps, shape, x0=None, generator=None). score_fn(x, sigma) returns a same-sized tensor. Use αᵢ = eps σᵢ²/σL², transition x ← x + αᵢ score_fn(x,σᵢ) + √(2αᵢ) ξ per step, and finally return x + σL² score_fn(x,σL). If x0 is supplied, clone it; otherwise initialize with a standard normal on CPU. Use the supplied generator for both random draws, avoid accumulating gradients and validate that positive scales are strictly decreasing.
import torch

def annealed_langevin(score_fn, sigmas, n_steps_each, eps, shape, x0=None, generator=None):
  pass
Shift+Enter to run

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 1/σ1/\sigma. Each update selects a geometric level per image and minimizes 12E∥σsθ(x+σϵ,σ)+ϵ∥2\frac12\mathbb E\|\sigma s_\theta(x+\sigma\epsilon,\sigma)+\epsilon\|^2, 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 [0,1][0,1]. 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 ε\varepsilon on a grid. This heuristic does not guarantee equilibrium with a learned network. Chains start uniformly in [0,1][0,1], use αi=εσi2/σL2\alpha_i=\varepsilon\sigma_i^2/\sigma_L^2 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 [0,1][0,1], 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 [0,1][0,1] 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 σ\sigma, 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 with annealed Langevin and Inception FIDLocal GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
Key idea

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.