Module contents
Lesson 21 of 28Core 105 min

Conditional generation and guidance: classifier guidance, classifier-free guidance and editing

Derive conditional and classifier-free guidance, distinguish instantaneous tilted densities from guided-process output laws, and use learned diffusion priors for image editing and inverse problems.

After this lesson you can

  • Introduce class and text conditioning into a diffusion network.
  • Derive classifier and classifier-free guidance from conditional scores.
  • Distinguish an instantaneous tilted density from the final law of a guided sampler.
  • Compare guidance scales and intervals with controlled evaluations.
  • Apply diffusion priors to SDEdit, inpainting and inverse problems.

Before you start

Request a class, not just any sample

An unconditional diffusion model learns to turn noise into a plausible sample from its training distribution. When we want a specific class, plausibility is not enough: a realistic dog does not satisfy a request for a boat. The condition can enter the network itself, and we can also modify the field followed by the sampler to increase compatibility with it. Both choices affect output distribution and cost.

This lesson distinguishes the score of a density at one instant from the final distribution of a guided process. Even an exactly calculated score does not automatically make the tilted density the final law of an ODE or SDE. We then use the model as a prior to complete and edit images without retraining it.

Introduce the condition into the network

For a discrete label yy, a U-Net can add a class embedding to the time embedding received by its blocks. For text, a sequence of embeddings can enter through cross-attention, letting image positions query tokens. In both cases the model learns a conditional prediction, for example ϵθ(xt,t,y)\epsilon_\theta(x_t,t,y).

Classifier-free guidance also needs an unconditional prediction. One network can learn both branches by randomly replacing the condition with a null symbol during training. The lab uses independent 10% dropout: 10% is an experimental choice, not a theoretical requirement. A model always trained with a label therefore has no reliable null branch. The null symbol must be distinct from all real classes, and the same preprocessing must be used during training and generation.

Bayes applied to the score

Let pt(x,y)p_t(x,y) be a joint distribution at noise level tt. Where pt(x)p_t(x) and pt(y∣x)p_t(y\mid x) are positive and differentiable, Bayes’ rule gives

∇xlog⁡pt(x∣y)⏟sc(x,t)=∇xlog⁡pt(x)⏟su(x,t)+∇xlog⁡pt(y∣x)⏟g(x,t).\underbrace{\nabla_x\log p_t(x\mid y)}_{s_c(x,t)} =\underbrace{\nabla_x\log p_t(x)}_{s_u(x,t)}+ \underbrace{\nabla_x\log p_t(y\mid x)}_{g(x,t)}.

The conditional score adds to the unconditional score the direction of increasing condition probability. In classifier guidance, gg is estimated with a classifier differentiated with respect to its input. The classifier must know tt and be trained on images perturbed to those levels: a clean-image classifier does not generally estimate pt(y∣xt)p_t(y\mid x_t) when xtx_t is full of noise. The gradient propagates to xtx_t even if classifier weights are frozen. Dhariwal and Nichol studied this guidance in conditional diffusion.

Starting from the conditional score, introduce excess guidance w≥0w\ge0:

sw=sc+wg=(1+w)sc−wsu.s_w=s_c+w g=(1+w)s_c-w s_u.

At w=0w=0 we have the ordinary conditional score. The common convention writing su+s(sc−su)s_u+s(s_c-s_u) uses s=1+ws=1+w: s=1s=1 is the same point without extra guidance. Confusing the conventions shifts every value by one.

Classifier-free guidance and a double batch

In classifier-free guidance, or CFG, scs_c and sus_u are estimated by the same network and combined as above, without training a separate classifier. In VP noise-prediction diffusion, s≈−ϵθ/σts\approx-\epsilon_\theta/\sigma_t for σt>0\sigma_t>0; the same linear combination therefore applies to noise predictions:

ϵCFG=(1+w)ϵθ(xt,t,y)−wϵθ(xt,t,∅).\epsilon_{\rm CFG}=(1+w)\epsilon_\theta(x_t,t,y) -w\epsilon_\theta(x_t,t,\varnothing).

In practice concatenate two copies of xtx_t, one with the null label and one with the desired label, and split output in half. This is one call with batch 2B2B, but processes two evaluations per image; arithmetic and memory cost are not equivalent to one evaluation. If w=0w=0 or guidance is disabled outside an interval, the conditional branch alone suffices. Ho and Salimans formulated this combination and studied the fidelity–coverage tradeoff.

InteractiveGuidance shifts samples

Contours show the tilted density at t = 0. Points are outputs from integrating the guided ODE.

  • Guided ODE
  • Tilted-density contours

The explicit model has three equally likely Gaussian classes with means (−1.3, 0), (0, 0), (1.3, 0) and standard deviation 0.65. The final class is the target. The conditional score corresponds to w = 0, and the alternative guidance convention uses scale 1 + w. The 128 starting states are drawn from the tilted terminal distribution by CDF inversion, and RK45 uses the exact scores. The y coordinate is transported analytically because it is independent of the class.

Points come from export_guidance.py with seeds 2101 and 2102. Contours use the analytic model and are normalized by their peak. A finite sample cannot establish equality of distributions. Guidance gives the score of the tilted density at each time, but the dynamics need not preserve those marginals.

0
Mean x, sampler
1.280
Mean x, tilted density
1.300
KS on x, 128 points
0.053
Compare the guided process and tilted density under the figure’s explicit model.

An instantaneous identity does not determine the final law

At each time, if exact scores are used, sws_w is the log-density gradient of a density proportional to

pt(x∣y) pt(y∣x)w=pt(x∣y)1+wpt(x)−w p(y)w.p_t(x\mid y)\,p_t(y\mid x)^w =p_t(x\mid y)^{1+w}p_t(x)^{-w}\,p(y)^w.

Constant p(y)wp(y)^w does not depend on xx. This identity justifies calling the density tilted at each instant. It does not prove that this family of densities is the forward evolution of one initial distribution under the original SDE. Therefore solving the reverse ODE or SDE with this field does not guarantee ending at the t=0t=0 tilted density. The two samplers can even produce different laws. Bradley and Nakkiran provide explicit DDIM and DDPM counterexamples.

Stronger guidance often favors regions more compatible with the condition, but does not guarantee monotonic improvement in every diversity or quality metric. With an approximate network, strong guidance and few steps can also amplify error and cause saturation. A fidelity–diversity comparison requires fixed checkpoint, scale, seeds, reference samples, extractor and budget; FID without guidance scale does not describe the full experiment.

InteractiveGuidance scales in images

The images come from a very short run. All five panels share the same latents and class. Outputs still look like noise, so they cannot identify a better guidance scale.

w = 0Eight samples at w 0, full guidance

FID 565.87 · precision 0.00 · recall 0.00
Outside [−1, 1] before clipping: 36.3%

w = 1Eight samples at w 1, full guidance

FID 568.32 · precision 0.00 · recall 0.00
Outside [−1, 1] before clipping: 37.6%

w = 3Eight samples at w 3, full guidance

FID 566.31 · precision 0.00 · recall 0.00
Outside [−1, 1] before clipping: 41.5%

w = 7Eight samples at w 7, full guidance

FID 541.88 · precision 0.00 · recall 0.00
Outside [−1, 1] before clipping: 51.0%

w = 15Eight samples at w 15, full guidance

FID 532.35 · precision 0.00 · recall 0.00
Outside [−1, 1] before clipping: 65.1%

The convention is ε_cond + w(ε_cond − ε_uncond), so w = 0 already uses conditional predictions. The interval mode adds guidance only for 0.2 ≤ t/T ≤ 0.8 and uses conditional predictions at other steps. The network was trained for 20 updates on primeras 64 filas CIFAR-10 examples at width 8, with nominal 10% condition dropout. Of 80 labels seen, 7 had their conditions dropped. Each case uses 20 batch evaluations. The batch is doubled when guidance requires it. Sampling seed: 2115.

FID, precision and recall were measured against the first 8 cat images in the test set. The experiment used clean-fid 0.1.35 InceptionV3W, RGB clipped to 8 bits, and bicubic resizing to 299 pixels. Precision and recall use kNN balls with k = 3. With only eight images on either side, the 2,048-dimensional covariance estimate has rank at most 7 and all three scores are unstable. A zero estimate cannot establish no coverage, and the values do not support benchmark comparisons or rankings by small differences. See cfg_lab.py and cfg-grid.json for code, configuration and hashes.

Apply guidance
Target class
Cat, class 3
Samples per scale
8
Completed updates
20
DDIM steps
20
Compare the same network and seeds, with the sample sizes and limits stated in the figure.

Interval, rescaling and autoguidance

Guidance can be applied only for σ\sigma inside an interval, using the conditional branch outside it. If a Heun corrector evaluates twice per step, align limits with step boundaries and keep the decision constant within the step: a discontinuity between slopes changes the numerical problem. On 512×512512\times512 ImageNet, Kynkäänniemi and colleagues report FID 1.81 for EDM2-XXL with CFG throughout and 1.40 with an optimized interval. They used 32 Heun steps and, in the second case, guidance on six of them for σ∈(0,19,1,61]\sigma\in(0{,}19,1{,}61] and scale s=2s=2 in our notation. Those values depend on their network, search and protocol and do not guarantee improvement for every model.

Another option rescales guided prediction by its standard deviation and mixes the rescaled version with the original to reduce overexposure. This modifies the prediction; it is not a Bayes identity, and its effect depends on data and chosen weight. Lin and colleagues study it alongside terminal SNR.

Autoguidance replaces the reference branch with a worse version of the network itself, such as a smaller or less-trained network, and extrapolates from the difference. It does not require an unconditional reference. On ImageNet-512, Karras and colleagues report for EDM2-S FID 2.56 without guidance, 2.23 with CFG and 1.34 with autoguidance in table 1; these are optimized study configurations, not measurements from our lab. Arbitrary degradation does not guarantee the same improvement.

Edit using a learned prior

SDEdit starts from an image or sketch xinitx_{\rm init}, adds noise to a chosen level t0t_0 and runs the reverse process. If t0t_0 is small, more input information remains; if large, the prior has more scope to change it. This is a tradeoff, not a guarantee that every strength change improves realism. The technique does not require retraining the model for each image. See SDEdit.

InteractiveChange SDEdit strength

Edit the first image to guide the second. The buttons load preset sketches.

Editable sketch
Preparing

The sketch starts in [−1, 1]. The widget adds noise as xₜ₀ = a(t₀)x_guide + √(1 − a(t₀)²)ε and returns toward t = 0 in up to 20 reverse transitions. The fixed seed pairs the comparisons. Presets threshold examples 0 and 1 from m19-l19. Drawing replaces the template with the current sketch.

The prior is an equal-weight mixture of 32 Gaussians with standard deviation 0.35, centered on the first MNIST training images. Each reverse transition is sampled exactly from the conditional mixture. This uses an explicit prior with no trained network. MSE to the sketch measures change. MSE to the nearest center measures closeness to the small reference set, without assessing perceptual quality. Pixels are clipped for display. This example adapts SDEdit to an explicit VP prior.

Brush
50
Time t
...
Final MSE from the sketch
...
Final MSE from nearest center
...
Seed
2131
Draw and compare the influence of initial noise using the stated prior and seeds.

Alternatively, approximately invert an image with DDIM, change the condition and regenerate. Finite-step inversion is not exact, as seen in DDIM; guidance and network predictions can increase reconstruction error.

To complete an image, let M=1M=1 in the known region. At level tt, the known observation must be perturbed with the appropriate marginal, αˉtxobs+1−αˉtϵ\sqrt{\bar\alpha_t}x_{\rm obs}+\sqrt{1-\bar\alpha_t}\epsilon, before combining it with the unknown region. At t=0t=0 restore known pixels exactly. A single replacement per step does not guarantee boundary consistency. RePaint interleaves reverse transitions and forward jumps to reharmonize both regions; mask and schedule must use the same convention at every jump.

InteractiveInpainting step by step

Paint the missing region in blue. The buttons offer preset masks and digits.

Editable mask
Preparing

Both variants start at the same point from the exact terminal marginal of the 32-image MNIST mixture in m19-l19 and use 20 VP intervals. After each reverse transition t → s, the known pixels are replaced with a(s)x₀ + √(1 − a(s)²)ε using fresh noise. Missing pixels come from the mixture’s reverse transition. At s = 0, the known region matches the input image. Blue pixels mark the missing region.

The resampling variant repeats each transition three times except the last, with a forward jump s → t between repeats. It uses 58 posterior evaluations versus 20 for simple replacement. Each frame shows the result at the end of the interval. The initial sample is shared. Resampling consumes more noise, so later increments differ. The score and transitions are exact for this explicit prior. Extra jumps may or may not improve results. See RePaint, Sections 4.1 and 4.2. This example uses the marginal at destination s and a one-interval jump.

Mask brush
Time t
...
Masked pixels
160 / 784
Total reverse transitions
...
Seed
2121
Change the mask and observe replacement and resampling with the stated prior.

Inverse problems: the prior does not replace observation

If we observe yy through a known process p(y∣x0)p(y\mid x_0), the posterior combines prior and likelihood. To guide a noisy state exactly we would need ∇xtlog⁡pt(y∣xt)\nabla_{x_t}\log p_t(y\mid x_t), with

pt(y∣xt)=∫p(y∣x0) p(x0∣xt) dx0.p_t(y\mid x_t)=\int p(y\mid x_0)\,p(x_0\mid x_t)\,dx_0.

This integral is often difficult. Diffusion posterior sampling approximates likelihood using a denoised estimate x^0(xt)\hat x_0(x_t), related to Tweedie, and differentiates observation discrepancy through that estimate. The approximation omits posterior uncertainty and can fail if observation is ambiguous or the measurement model is wrong. It does not automatically make output an exact posterior sample. See Chung and colleagues.

Lab: exact guidance and final law

Three equally likely classes have means (−1,3,0)(-1{,}3,0), (0,0)(0,0), (1,3,0)(1{,}3,0) and covariance 0.65²I. The VP-SDE has β(t)=0.1+4.9t on [0,1]. By symmetry, the y coordinate is an independent Gaussian and comparison reduces to x. Classifier and conditional and unconditional scores are calculated analytically. We use s_guided = s_cond + w(s_cond − s_uncond): w=0 is the conditional score and the alternative scale is 1+w.

At every level the guided field matches the score of the tilted density proportional to pₜ(x|y)pₜ(y|x)^w. This does not prove those densities evolve under the same SDE. We therefore start from the terminal tilted density obtained by quadrature and i.i.d. sampling, and integrate the guided ODE. Compare the final distribution with the t=0 tilted density using KS and moments; repeat with stricter tolerances and check quadrature. The DKW band describes sample variability against the fixed CDF; it does not cover solver or grid error. Differences do not imply they occur in all models or define visual quality.

[ ]Analytical scores and classifierBrowser
"""Tres clases gaussianas con scores, clasificador y densidad exactos."""
import numpy as np
from scipy.special import logsumexp
from scipy.integrate import cumulative_trapezoid, solve_ivp
from scipy.stats import kstest

CENTERS = np.array([-1.3, 0., 1.3])
STD = .65
CLASS = 2
T = 1.


def beta(t):
    return .1 + 4.9*t


def mixture(t):
    a = np.exp(-.5*(.1*t + 2.45*t*t))
    var = a*a*STD*STD + 1-a*a
    return a*CENTERS, var


def fields(x, t):
    x = np.asarray(x)
    means, var = mixture(t)
    delta = means - x[..., None]
    logits = -.5 * delta**2/var
    weights = np.exp(logits-logsumexp(logits, axis=-1, keepdims=True))
    cond = delta[..., CLASS]/var
    uncond = np.sum(weights*delta, axis=-1)/var
    logpc = logits[..., CLASS] - .5*np.log(2*np.pi*var)
    logpost = logits[..., CLASS]-logsumexp(logits, axis=-1)
    return cond, uncond, logpc, logpost


def guided_score(x, t, w):
    cond, uncond, _, _ = fields(x, t)
    return cond + w*(cond-uncond)


def classifier_score(x, t, w):
    x = np.asarray(x)
    means, var = mixture(t)
    logits = -.5*(x[..., None]-means)**2/var
    posterior = np.exp(logits-logsumexp(logits, axis=-1, keepdims=True))
    grad_log_class = (means[CLASS]-np.sum(posterior*means, axis=-1))/var
    conditional = (means[CLASS]-x)/var
    return conditional + w*grad_log_class


def tilted_log_density(x, t, w):
    _, _, logpc, logpost = fields(x, t)
    return logpc + w*logpost


check_x = np.linspace(-3, 3, 9)
for time in (.2, .8):
    h = 1e-5
    fd = (tilted_log_density(check_x+h, time, 3) - tilted_log_density(check_x-h, time, 3))/(2*h)
    assert np.allclose(fd, guided_score(check_x, time, 3), atol=1e-8, rtol=0)
    assert np.allclose(guided_score(check_x, time, 3), classifier_score(check_x, time, 3))
print('Score inclinado y guía por clasificador coinciden; diferencias finitas verificadas.')
print('Convención: w=0 score condicional; escala alternativa s=1+w.')
[ ]Final law and tilted densityBrowser
"""Compara sampler guiado con la densidad inclinada y controla el solver."""


def tilted_cdf(t, w, n_grid=12001):
    grid = np.linspace(-10, 10, n_grid)
    log_density = tilted_log_density(grid, t, w)
    density = np.exp(log_density - np.max(log_density))
    cdf = cumulative_trapezoid(density, grid, initial=0)
    mass = cdf[-1]
    cdf /= mass
    mean = np.trapz(grid*density, grid)/mass if hasattr(np, 'trapz') else np.trapezoid(grid*density, grid)/mass
    variance = (np.trapz((grid-mean)**2*density, grid) if hasattr(np, 'trapz') else
                np.trapezoid((grid-mean)**2*density, grid))/mass
    return grid, cdf, float(mean), float(variance)


def draw_guided(t, w, uniforms):
    grid, cdf, _, _ = tilted_cdf(t, w)
    return np.interp(uniforms, cdf, grid)


def guided_ode(initial, w, rtol):
    def velocity(t, x):
        return -.5*beta(t)*(x+guided_score(x,t,w))
    result = solve_ivp(velocity, (1., 0.), initial, rtol=rtol, atol=rtol*.1, method='RK45')
    if not result.success:
        raise RuntimeError(result.message)
    return result.y[:,-1], result.nfev


n = 2048
uniforms = np.random.default_rng(2101).random(n)
dkw = np.sqrt(np.log(2/.01)/(2*n))
summary = []
for w in (0., 1., 3., 7.):
    initial = draw_guided(1., w, uniforms)
    generated, nfe = guided_ode(initial, w, 1e-7)
    refined, nfe_refined = guided_ode(initial, w, 1e-9)
    target_x, target_cdf, target_mean, target_var = tilted_cdf(0., w)
    cdf = lambda x: np.interp(x, target_x, target_cdf, left=0., right=1.)
    ks = float(kstest(refined, cdf).statistic)
    error = float(np.max(np.abs(generated-refined)))
    assert error < 1e-4
    summary.append((w, ks, float(refined.mean()), target_mean, float(refined.var()), target_var))
    print(f'w={w:g}: KS={ks:.5f}, media sampler/inclinada={refined.mean():.5f}/{target_mean:.5f}; '
          f'varianza={refined.var():.5f}/{target_var:.5f}; error solver={error:.2e}; NFE={nfe}/{nfe_refined}.')
print(f'DKW 99% para n={n}: banda {dkw:.5f}; no incluye error de cuadratura ni del solver.')
assert summary[0][1] < dkw
_, fine, _, _ = tilted_cdf(0., 7., 24001)
coarse_x, coarse, _, _ = tilted_cdf(0., 7., 12001)
assert np.max(np.abs(coarse - fine[::2])) < 1e-6
print('CDF en rejillas de 12001/24001 puntos coincide a menos de 1e-6 en los nodos.')

Local lab: CFG and editing on CIFAR-10

Start from lesson 18’s U-Net architecture and add a class embedding to the time representation. Labels 0 to 9 are CIFAR-10 classes and 10 is the null condition. During training each label is replaced by null with probability 0.1; the same network is trained in both cases. Full mode uses width 128, a 1000-step linear schedule and proposes 50,000 attempts with microbatches of 8 and accumulation of 4. ORYON_UPDATES selects a different budget. EMA weights update only if AMP actually performs the optimizer step.

The scale follows Ho and Salimans: ϵ^=(1+w)ϵcond−wϵnula\hat\epsilon=(1+w)\epsilon_{\rm cond}-w\epsilon_{\rm nula}, so w=0w=0 is already conditional generation. Each guided evaluation concatenates both branches into one batch; outside interval 0,2≤t/T≤0,80,2\le t/T\le0,8 or when w=0w=0, only the conditional branch is evaluated. The report distinguishes network calls from processed examples: a double batch does not cost the same as a single batch even though both are one call. The two-pass versus double-batch check compares values within numerical tolerance and reports maximum observed error. Sources are Ho and Salimans and the guidance interval study.

The experiment generates cats for w=0,1,3,7,15w=0,1,3,7,15, with the same seed and both full and interval guidance. Compare each group against the first cat images in test, not all CIFAR-10: calculate FID with InceptionV3W and precision and coverage using k=3k=3-neighbor balls in the same space. Save features, images, seeds, hashes and metrics in ORYON_OUTPUT_DIR, alongside fid-vs-precision.png. Finite-sample FID is biased and balls depend on kk, sample and extractor. Full mode defaults to 128 images per group: this is exploration, not a benchmark; ORYON_EVAL_COUNT accepts 4 to 1000. The range is clipped only for display and Inception preprocessing; the report retains the original out-of-range fraction.

For SDEdit, add noise to a test image up to t0t_0 and traverse backward with DDIM. For RePaint, the mask is one in the observed region: at each level replace that region with its forward marginal at the destination level, take an ancestral DDPM step for the unknown region and apply two local renoising and reverse cycles except at the final endpoint. This variant states its posterior variance and schedule; more cycles add cost and do not guarantee a better image. Compare against one cycle and verify known pixels are preserved at the end. Checks include full, empty and partial masks. Results go in editing.png alongside the original; test samples do not enter training.

Install PyTorch, torchvision, NumPy, SciPy, Pillow, Matplotlib and clean-fid==0.1.35. Set ORYON_INCEPTION_PT to the inception-2015-12-05.pt path; ORYON_DATA_ROOT and ORYON_OUTPUT_DIR choose data and result directories. Optionally, ORYON_PREVIOUS_CKPT points to the lesson 18 linear ϵ\epsilon-prediction EMA with matching width and TT: its shared weights are loaded and a new class embedding added. Without it, training starts from scratch. conditional.pt stores weights, EMA, optimizer and AMP for inspection; the script does not implement automatic resume.

With ORYON_QUICK=1, use a width-8 network, 64 train images, 20 diffusion steps, 20 attempts and eight cat-class test images. ORYON_CIFAR_PARQUET may point to local parquet only in this mode and requires pyarrow. In one run from scratch, 20 updates completed and 7 of 80 labels were dropped; all precision and coverage estimates were zero. FID ranged from about 532 to 569 with eight examples per group. Like the almost noisy images in the figure, this checks the pipeline: it does not demonstrate learning, quality or a scale or interval advantage. The double-batch versus two-pass test produced maximum error 4·10⁻⁵ on CUDA, within numerical tolerance. A second short run also checked initialization from a compatible lesson 18 EMA.

[ ]Conditional diffusion, guidance and inpainting on CIFAR-10Local GPU
"""Conditional CIFAR diffusion and classifier-free guidance."""
import copy, os, math, json, hashlib, io
from pathlib import Path
os.environ.setdefault('OPENBLAS_NUM_THREADS','1')
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.utils.data import Dataset,DataLoader,Subset
from torchvision import datasets,transforms
from torchvision.utils import save_image
from PIL import Image
from cleanfid.inception_torchscript import InceptionV3W
from cleanfid.resize import build_resizer
torch.set_num_threads(2)

def groups(channels):
    return math.gcd(32, channels)


class AdaResidual(nn.Module):
    def __init__(self, channels, embedding):
        super().__init__()
        self.norm1 = nn.GroupNorm(groups(channels), channels)
        self.conv1 = nn.Conv2d(channels, channels, 3, padding=1)
        self.norm2 = nn.GroupNorm(groups(channels), channels, affine=False)
        self.condition = nn.Linear(embedding, 2 * channels)
        self.conv2 = nn.Conv2d(channels, channels, 3, padding=1)

    def forward(self, x, embedding):
        h = self.conv1(F.silu(self.norm1(x)))
        scale, shift = self.condition(embedding).chunk(2, dim=1)
        h = self.norm2(h) * (1 + scale[:, :, None, None]) + shift[:, :, None, None]
        return x + self.conv2(F.silu(h))


class SpatialAttention(nn.Module):
    """Atención de producto escalar solo en mapas de 16×16 y 8×8."""
    def __init__(self, channels, head_dim=32):
        super().__init__()
        self.heads = max(1, channels // min(head_dim, channels))
        if channels % self.heads:
            raise ValueError('Los canales deben dividirse entre las cabezas')
        self.norm = nn.GroupNorm(groups(channels), channels)
        self.qkv = nn.Conv2d(channels, 3 * channels, 1)
        self.output = nn.Conv2d(channels, channels, 1)

    def forward(self, x):
        batch, channels, height, width = x.shape
        q, k, v = self.qkv(self.norm(x)).chunk(3, dim=1)
        def arrange(z):
            return z.reshape(batch, self.heads, channels // self.heads, height * width).transpose(2, 3)
        h = F.scaled_dot_product_attention(arrange(q), arrange(k), arrange(v))
        h = h.transpose(2, 3).reshape(batch, channels, height, width)
        return x + self.output(h)


class DiffusionUNet(nn.Module):
    """CIFAR 32×32, niveles 32/16/8; ancho 128 en el modo completo."""
    def __init__(self, width=128):
        super().__init__()
        if width < 8 or width % 8:
            raise ValueError('El ancho debe ser un múltiplo de ocho')
        embedding = 4 * width
        self.width = width
        self.time = nn.Sequential(nn.Linear(width, embedding), nn.SiLU(), nn.Linear(embedding, embedding))
        self.label = nn.Embedding(11, 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, labels):
        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)) + self.label(labels)
        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 hash_file(path):
    digest = hashlib.sha256()
    with open(path,'rb') as f:
        for block in iter(lambda: f.read(1024*1024),b''): digest.update(block)
    return digest.hexdigest()


class TinyParquet(Dataset):
    def __init__(self, folder, split, count, class_id=None):
        import pyarrow.parquet as pq
        self.rows, self.used = [], []
        for path in sorted(Path(folder).glob(f'{split}-*.parquet')):
            self.used.append(str(path))
            for batch in pq.ParquetFile(path).iter_batches(batch_size=128, columns=['img','label']):
                for row in batch.to_pylist():
                    if class_id is None or row['label'] == class_id:
                        self.rows.append((row['img']['bytes'], int(row['label'])))
                        if len(self.rows) == count: break
                if len(self.rows) == count: break
            if len(self.rows) == count: break
        if len(self.rows) < count: raise ValueError('Faltan filas CIFAR en parquet')
    def __len__(self): return len(self.rows)
    def __getitem__(self, index):
        img,label = self.rows[index]
        with Image.open(io.BytesIO(img)) as image:
            return transforms.ToTensor()(image.convert('RGB')), label


def datasets_cifar(root, quick, parquet, n, target):
    if parquet:
        if not quick: raise ValueError('Parquet solo se usa en modo corto')
        train = TinyParquet(parquet, 'train', 64)
        test = TinyParquet(parquet, 'test', n, target)
        return train, test, {'source':'parquet CIFAR-10', 'train':'primeras 64 filas',
                             'test':f'primeras {n} filas de clase {target}',
                             'files':[{'name':Path(p).name,'sha256':hash_file(p)} for p in train.used+test.used]}
    train = datasets.CIFAR10(root, train=True, download=True, transform=transforms.ToTensor())
    test = datasets.CIFAR10(root, train=False, download=True, transform=transforms.ToTensor())
    indexes = [i for i,label in enumerate(test.targets) if label == target][:n]
    if len(indexes) < n: raise ValueError('No hay suficientes imágenes de test de la clase')
    if quick:
        ids = torch.randperm(len(train),generator=torch.Generator().manual_seed(2110))[:64].tolist()
        train = Subset(train,ids)
    return train, Subset(test,indexes), {'source':'torchvision CIFAR-10','train':'64 permutadas' if quick else 'todas',
                                        'test':f'primeras {n} de clase {target}','selection_seed':2110 if quick else None}


def guided(model, x, t, T, labels, w, use_interval):
    # Convención Ho-Salimans: w=0 equivale al condicional.
    active = not use_interval or .2 <= float(t[0])/T <= .8
    if w == 0 or not active:
        return model(x,t,T,labels), 1, len(x)
    null = torch.full_like(labels,10)
    both = model(torch.cat([x,x]),torch.cat([t,t]),T,torch.cat([labels,null]))
    cond, uncond = both.chunk(2)
    return (1+w)*cond-w*uncond, 1, 2*len(x)


def denoise_step(model,x,t,s,bars,labels,w,use_interval):
    times = torch.full((len(x),),t,device=x.device,dtype=torch.long)
    eps,calls,examples = guided(model,x,times,len(bars)-1,labels,w,use_interval)
    bt,bs = float(bars[t]),float(bars[s]); a,b = math.sqrt(bt),math.sqrt(1-bt)
    x0 = (x-b*eps)/a
    return math.sqrt(bs)*x0+math.sqrt(1-bs)*eps,calls,examples


@torch.no_grad()
def sample(model,bars,initial,labels,w,use_interval,steps):
    T=len(bars)-1
    ids=np.rint(np.linspace(T,0,steps+1)).astype(int)
    if np.any(np.diff(ids)>=0): raise ValueError('Demasiados pasos')
    x=initial.clone(); calls=examples=0
    for t,s in zip(ids[:-1],ids[1:]):
        x,c,e=denoise_step(model,x,int(t),int(s),bars,labels,w,use_interval)
        calls+=c;examples+=e
    if not torch.isfinite(x).all(): raise FloatingPointError('Muestra CFG no finita')
    return x,calls,examples


@torch.no_grad()
def sdedit(model,bars,original,labels,t0,steps,seed):
    gen=torch.Generator(device=original.device).manual_seed(seed)
    b=float(bars[t0]); noise=torch.randn(original.shape,device=original.device,generator=gen)
    x=math.sqrt(b)*original+math.sqrt(1-b)*noise
    for t,s in zip(np.rint(np.linspace(t0,0,steps+1)).astype(int)[:-1],
                   np.rint(np.linspace(t0,0,steps+1)).astype(int)[1:]):
        x,_,_=denoise_step(model,x,int(t),int(s),bars,labels,0.,False)
    return x


@torch.no_grad()
def inpaint(model,bars,original,known,labels,seed,repeats):
    # known=1: píxel observado; reverso DDPM y reemplazo en el nivel de destino.
    T=len(bars)-1; gen=torch.Generator(device=original.device).manual_seed(seed)
    x=torch.randn(original.shape,device=original.device,generator=gen)
    for t in range(T,0,-1):
        s=t-1
        for u in range(repeats if s>0 else 1):
            proposal=ancestral_step(model,x,t,bars,labels,gen)
            if torch.any(known):
                b=float(bars[s]); noise=torch.randn(x.shape,device=x.device,generator=gen) if s else torch.zeros_like(x)
                observed=math.sqrt(b)*original+math.sqrt(1-b)*noise
                x=known*observed+(1-known)*proposal
            else:
                x=proposal
            if u+1<repeats and s>0:
                ratio=float(bars[t]/bars[s]); noise=torch.randn(x.shape,device=x.device,generator=gen)
                x=math.sqrt(ratio)*x+math.sqrt(1-ratio)*noise
    return x


def ancestral_step(model,x,t,bars,labels,gen):
    s=t-1; bt=float(bars[t]); bs=float(bars[s]); ratio=bt/bs
    ts=torch.full((len(x),),t,device=x.device,dtype=torch.long)
    eps,_,_=guided(model,x,ts,len(bars)-1,labels,0.,False)
    x0=(x-math.sqrt(1-bt)*eps)/math.sqrt(bt)
    mean=math.sqrt(bs)*(1-ratio)/(1-bt)*x0+math.sqrt(ratio)*(1-bs)/(1-bt)*x
    variance=(1-bs)*(1-ratio)/(1-bt)
    noise=torch.randn(x.shape,device=x.device,generator=gen) if s else torch.zeros_like(x)
    return mean+math.sqrt(max(0.,variance))*noise


def low_rank_fid(real,fake):
    a,b=np.asarray(real,np.float64),np.asarray(fake,np.float64)
    x,y=a-a.mean(0),b-b.mean(0)
    cross=np.linalg.svd([email protected],compute_uv=False).sum()/math.sqrt((len(x)-1)*(len(y)-1))
    fid=np.square(a.mean(0)-b.mean(0)).sum()+(x*x).sum()/(len(x)-1)+(y*y).sum()/(len(y)-1)-2*cross
    if fid < -1e-7: raise ValueError('FID negativo fuera de tolerancia')
    return max(float(fid),0.)


def precision_recall(real,fake,k=3):
    from scipy.spatial.distance import cdist
    if min(len(real),len(fake))<=k: raise ValueError('Se necesitan más de k muestras')
    rr=cdist(real,real,'sqeuclidean'); ff=cdist(fake,fake,'sqeuclidean')
    # La diagonal propia se excluye, incluso cuando existen ejemplos duplicados.
    np.fill_diagonal(rr,np.inf);np.fill_diagonal(ff,np.inf)
    rad_r=np.partition(rr,k-1,axis=1)[:,k-1];rad_f=np.partition(ff,k-1,axis=1)[:,k-1]
    cross=cdist(real,fake,'sqeuclidean')
    return float(np.any(cross<=rad_r[:,None],axis=0).mean()),float(np.any(cross<=rad_f[None,:],axis=1).mean())


def image_features(images, inception, device):
    resize=build_resizer('clean'); chunks=[]
    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(a).transpose(2,0,1) for a in arrays])
            chunks.append(inception(torch.from_numpy(resized).to(device)).cpu().numpy())
    return np.concatenate(chunks)


@torch.no_grad()
def verify(device):
    torch.manual_seed(2101)
    model=DiffusionUNet(8).to(device).eval()
    x=torch.randn((2,3,8,8),device=device)
    labels=torch.tensor([3,8],device=device)
    t=torch.tensor([10,10],device=device)
    cond=model(x,t,20,labels); uncond=model(x,t,20,torch.full_like(labels,10))
    combined,calls,examples=guided(model,x,t,20,labels,2.,False)
    error=float((combined-(3*cond-2*uncond)).abs().max())
    assert calls==1 and examples==4 and torch.allclose(combined,3*cond-2*uncond,atol=8e-5,rtol=2e-5)
    assert torch.allclose(guided(model,x,t,20,labels,0.,False)[0],cond,atol=2e-6,rtol=1e-5)
    assert torch.allclose(guided(model,x,torch.tensor([19,19],device=device),20,labels,5.,True)[0],
                          model(x,torch.tensor([19,19],device=device),20,labels),atol=2e-6,rtol=1e-5)
    assert torch.allclose(guided(model,x,t,20,torch.full_like(labels,10),5.,False)[0],uncond,atol=8e-5,rtol=2e-5)
    bars=make_schedule('linear',4,'cpu')['bar'].numpy()
    known=torch.ones_like(x); null=torch.full_like(labels,10)
    painted=inpaint(model,bars,x,known,null,2111,2)
    assert torch.equal(painted,x)
    none=torch.zeros_like(x)
    painted=inpaint(model,bars,x,none,null,2111,1)
    gen=torch.Generator(device=device).manual_seed(2111)
    initial=torch.randn(x.shape,device=device,generator=gen)
    baseline=initial
    for time in range(4,0,-1): baseline=ancestral_step(model,baseline,time,bars,null,gen)
    assert torch.allclose(painted,baseline,atol=1e-6)
    half=known.clone();half[:,:,:,half.shape[-1]//2:]=0
    painted=inpaint(model,bars,x,half,null,2111,2)
    assert torch.equal(painted*half,x*half) and torch.isfinite(painted).all()
    r=np.array([[0.,0.],[1.,0.],[0.,1.],[1.,1.],[.5,.5]])
    p,q=precision_recall(r,r,k=3)
    assert p==1 and q==1 and low_rank_fid(r,r)<1e-10
    print(f'Controles: lote doble frente a dos pases (error máximo {error:.2g}), intervalo, w=0, máscaras y métricas.',flush=True)
    del model


def main():
    quick=os.environ.get('ORYON_QUICK')=='1'
    device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print(f'dispositivo {device}; quick {quick}',flush=True)
    inception_path=Path(os.environ.get('ORYON_INCEPTION_PT',''))
    if inception_path.name!='inception-2015-12-05.pt' or not inception_path.is_file():
        raise ValueError('ORYON_INCEPTION_PT debe nombrar el archivo inception-2015-12-05.pt existente')
    verify(device)
    n=8 if quick else int(os.environ.get('ORYON_EVAL_COUNT','128'))
    if not 4 <= n <= 1000: raise ValueError('ORYON_EVAL_COUNT debe estar entre 4 y 1000')
    target=3 # gato en CIFAR-10
    parquet=os.environ.get('ORYON_CIFAR_PARQUET')
    train,test,source=datasets_cifar(os.environ.get('ORYON_DATA_ROOT','./data'),quick,parquet,n,target)
    output=Path(os.environ.get('ORYON_OUTPUT_DIR','./cfg-cifar'));output.mkdir(parents=True,exist_ok=True)
    T,width,micro,accum,attempts=(20,8,4,1,20) if quick else (1000,128,8,4,int(os.environ.get('ORYON_UPDATES','50000')))
    if attempts<1: raise ValueError('ORYON_UPDATES debe ser positivo')
    bars=make_schedule('linear',T,'cpu')['bar'].numpy()
    checkpoint_path=os.environ.get('ORYON_PREVIOUS_CKPT')
    torch.manual_seed(2112)
    model=DiffusionUNet(width).to(device)
    if checkpoint_path:
        previous=torch.load(checkpoint_path,map_location='cpu',weights_only=True)
        if previous['width']!=width or previous['parameterization']!='epsilon' or previous['schedule']!='linear' or previous['T']!=T or previous.get('zero_terminal',False):
            raise ValueError('El checkpoint previo debe ser EMA epsilon/lineal con T, anchura y calendario compatibles')
        loaded=model.load_state_dict(previous['ema'],strict=False)
        assert set(loaded.missing_keys)=={'label.weight'} and not loaded.unexpected_keys
        del previous
    initial_label_weights=model.label.weight.detach().clone()
    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=micro,shuffle=True,drop_last=True,num_workers=0,
                      generator=torch.Generator().manual_seed(2113))
    batches=iter(loader); rng=torch.Generator(device=device).manual_seed(2114)
    completed=skipped=dropped=seen=0; history=[]
    for attempt in range(1,attempts+1):
        optimizer.zero_grad(set_to_none=True); running=0.
        for _ in range(accum):
            try: images,labels=next(batches)
            except StopIteration: batches=iter(loader);images,labels=next(batches)
            images=images.to(device)*2-1;labels=labels.to(device)
            missing=torch.rand((len(labels),),device=device,generator=rng)<.1
            dropped+=int(missing.sum()); seen+=len(labels)
            labels=torch.where(missing,10,labels)
            t=torch.randint(1,T+1,(len(images),),device=device,generator=rng)
            noise=torch.randn(images.shape,device=device,generator=rng)
            bar=torch.as_tensor(bars,device=device,dtype=images.dtype)[t,None,None,None]
            xt=bar.sqrt()*images+(1-bar).sqrt()*noise
            with torch.autocast(device_type=device.type,dtype=torch.float16,enabled=device.type=='cuda'):
                prediction=model(xt,t,T,labels)
                loss=F.mse_loss(prediction.float(),noise.float())
            if not torch.isfinite(loss):raise FloatingPointError('Pérdida no finita')
            scaler.scale(loss/accum).backward();running+=loss.item()/accum
        scaler.unscale_(optimizer);torch.nn.utils.clip_grad_norm_(model.parameters(),1.)
        old_scale=scaler.get_scale();scaler.step(optimizer);scaler.update()
        if scaler.get_scale()<old_scale:skipped+=1
        else:
            completed+=1; decay=min(.9999,(1+completed)/(10+completed))
            with torch.no_grad():
                for average,current in zip(ema.parameters(),model.parameters(),strict=True):
                    average.mul_(decay).add_(current,alpha=1-decay)
        if attempt in (1,attempts) or attempt%500==0:
            history.append({'attempt':attempt,'loss':running,'effective_updates':completed,'skipped_amp':skipped})
            print(f'intento {attempt}: pérdida {running:.6f}, efectivos {completed}, saltados {skipped}',flush=True)
    checkpoint={'model':model.state_dict(),'ema':ema.state_dict(),'optimizer':optimizer.state_dict(),
                'scaler':scaler.state_dict(),'width':width,'T':T,'schedule':'linear',
                'parameterization':'epsilon','drop_probability':.1,'attempts':attempts,
                'effective_updates':completed,'skipped_amp':skipped,'history':history}
    if completed==0 or torch.equal(initial_label_weights,model.label.weight.detach()):
        raise RuntimeError('No hubo actualización efectiva del embedding de clase')
    ckpt=output/'conditional.pt';torch.save(checkpoint,ckpt)
    loaded=torch.load(ckpt,map_location='cpu',weights_only=True)
    assert torch.equal(loaded['ema']['label.weight'],ema.label.weight.cpu())
    del model,optimizer,scaler,checkpoint,loaded,batches,loss,images,noise,xt,prediction,initial_label_weights
    del average,current,labels,missing,t,bar
    if device.type=='cuda':torch.cuda.empty_cache()
    inception=InceptionV3W(str(inception_path.parent),download=False,resize_inside=False).to(device).eval()
    real=torch.stack([test[i][0] for i in range(n)])
    reference=image_features(real,inception,device)
    steps=20 if quick else 30
    records=[];all_features={'reference':reference}
    for w in (0,1,3,7,15):
        for limited in (False,True):
            gen=torch.Generator(device=device).manual_seed(2115)
            pieces=[];nfe=None; processed=0
            for offset in range(0,n,4):
                size=min(4,n-offset)
                initial=torch.randn((size,3,32,32),device=device,generator=gen)
                labels=torch.full((size,),target,device=device,dtype=torch.long)
                out,calls,examples=sample(ema,bars,initial,labels,w,limited,steps)
                nfe=calls if nfe is None else nfe
                processed+=examples;pieces.append(out.cpu())
            fake=torch.cat(pieces);outside=float(((fake < -1)|(fake > 1)).float().mean())
            feats=image_features((fake+1)/2,inception,device);fid=low_rank_fid(reference,feats)
            precision,recall=precision_recall(reference,feats,k=3)
            name=f'w{w}-{("interval" if limited else "full")}'
            all_features[name]=feats
            save_image(((fake[:8]+1)/2).clamp(0,1),output/f'{name}.png',nrow=4)
            records.append({'w':w,'interval':limited,'fid':fid,'precision':precision,'recall':recall,
                            'outside_fraction':outside,'calls_per_batch':nfe,
                            'network_examples_total':processed,'image':f'{name}.png'})
            print(f'{name}: FID={fid:.4f}, precisión={precision:.3f}, cobertura={recall:.3f}, fuera={outside:.3f}',flush=True)
    np.savez_compressed(output/'features.npz',**all_features)
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    fig,ax=plt.subplots()
    for limited in (False,True):
        rows=[row for row in records if row['interval']==limited]
        ax.plot([row['precision'] for row in rows],[row['fid'] for row in rows],'o-',
                label='intervalo' if limited else 'guía completa')
        for row in rows: ax.annotate(f"w={row['w']}",(row['precision'],row['fid']))
    ax.set(xlabel='Precisión kNN en Inception',ylabel='FID estimado',title=f'Clase gato, {n} imágenes')
    ax.legend();fig.tight_layout();fig.savefig(output/'fid-vs-precision.png',dpi=150);plt.close(fig)
    original=real[:1].to(device)*2-1;null=torch.full((1,),10,device=device,dtype=torch.long)
    strength=max(2,T//2)
    edited=sdedit(ema,bars,original,null,strength,min(strength,steps),2116)
    mask=torch.ones_like(original);mask[:,:,:,16:]=0
    basic=inpaint(ema,bars,original,mask,null,2117,1)
    repaint=inpaint(ema,bars,original,mask,null,2117,2)
    assert torch.equal(basic*mask,original*mask) and torch.equal(repaint*mask,original*mask)
    save_image(torch.cat([(original+1)/2,(edited+1)/2,(basic+1)/2,(repaint+1)/2]).clamp(0,1),output/'editing.png',nrow=4)
    report={'quick':quick,'dataset':source,'target_class':target,'target_name':'gato',
            'reference_count':n,'generated_per_case':n,'width':width,'T':T,'ddim_steps':steps,
            'attempts':attempts,'effective_updates':completed,'skipped_amp':skipped,
            'drop_probability':.1,'dropped':dropped,'labels_seen':seen,'history':history,
            'checkpoint_sha256':hash_file(ckpt),'inception_sha256':hash_file(inception_path),
            'previous_checkpoint_sha256':hash_file(checkpoint_path) if checkpoint_path else None,
            'sampler_seed':2115,'training_seed':2112,'batch_seed':2113,'noise_seed':2114,
            'sdedit_seed':2116,'inpainting_seed':2117,'sdedit_t0':strength,
            'interval_t_over_T':[.2,.8],'guidance_convention':'condicional + w*(condicional - incondicional)',
            'feature_protocol':'InceptionV3W clean-fid 0.1.35, RGB uint8, PIL bicubico 299',
            'precision_recall':'k=3, bolas k-vecinos en características Inception de clase 3',
            'repaint':'máscara 1 conocida; reemplazo a nivel destino y 2 ciclos locales de salto',
            'cases':records,'warning':'Ensayo pequeño: FID sesgado, kNN inestable y no demuestra calidad.'}
    (output/'report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
    print('Sin evaluar calidad con este presupuesto corto; métricas de muestra finita sesgadas.',flush=True)
    del ema,inception,train,test,loader,initial,out,labels,original,null,edited,mask,basic,repaint
    if device.type=='cuda':torch.cuda.empty_cache()


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.

Exercises

For the Gaussian exercise, take σ>0\sigma>0, w≥0w\ge0 and vectors μ,a\mu,a of the same dimension.

ProofThe CFG combination
Prove: Derive the CFG score combination from Bayes’ rule.
0
Consider positive differentiable densities and nonnegative weight w.

Step 1 of 2. What is ∇ log pₜ(y|x) in terms of scores?

ProofMode of a tilted density
Prove: Analyze the shape and mode of a tilted Gaussian density with a logistic factor.
0
Let π(x)=sigmoid(a·x+b), with w≥0 and σ>0.

Step 1 of 3. If p(x|y) is N(μ,σ²I) and p(y|x)=sigmoid(a·x+b), what is the log-gradient of the tilted density?

After solving the proof, check a one-dimensional case with μ=0\mu=0, σ=1\sigma=1, a=1a=1, b=0b=0 and w=3w=3. Mode and mean are different objects. The following quadrature truncates the integral to [−12,12][-12,12].

[ ]Check the tilted density modeBrowser
import numpy as np
from scipy.optimize import brentq
from scipy.special import expit, log_expit
from scipy.integrate import quad

w = 3.
mode = brentq(lambda z: z-w*expit(-z), 0., w)
weight = lambda x: np.exp(-.5*x*x+w*log_expit(x))
Z = quad(weight,-12,12,epsabs=1e-12)[0]
mean = quad(lambda x: x*weight(x),-12,12,epsabs=1e-12)[0]/Z
variance = quad(lambda x: (x-mean)**2*weight(x),-12,12,epsabs=1e-12)[0]/Z
curvature = -1-w*expit(mode)*expit(-mode)
print(f'modo={mode:.8f}; curvatura={curvature:.8f}; media={mean:.8f}; varianza={variance:.8f}')
NumericCost without a double batch
A DDIM sampler uses 30 steps, separately evaluating conditional and unconditional branches at each. How many network evaluations per image does it perform?
QuizWhat must the classifier learn?
Why does classifier guidance train the classifier with different noise levels?
CodeCFG with a double batch
Implement cfg_denoise(model,x,sigma,y,w,interval). x has B rows, y has B integer labels between 0 and 9, and −1 represents the null condition. model(x,sigma,labels) returns an array shaped like x. Within the closed interval [a,b] and with w≠0, evaluate one double batch, null first and conditional second, and return (1+w)cond−w uncond. Outside the interval or with w=0 evaluate only the conditional branch. Do not modify x or y.
import numpy as np

def cfg_denoise(model, x, sigma, y, w, interval):
  pass
Shift+Enter to run
Key idea

Guidance combines scores to increase compatibility with a condition. Its instantaneous interpretation, the numerical process using it and the final law are three different objects; editing and inverse problems also add an observation that must be explicitly respected.