Module contents
Stage 8 of 9Research 120 min

Latent diffusion with a DiT

Build a latent diffusion pipeline with a frozen VAE and a diffusion transformer trained by flow matching.

After this lesson you can

  • Explain latent scaling, reconstruction quality and data augmentation.
  • Implement a latent DiT with adaLN-Zero conditioning.
  • Train and evaluate decoded samples with a reproducible FID protocol.

Before you start

Compressing an image before learning the flow

A 256-by-256 RGB image contains 196,608 values. A first-stage autoencoder can turn it into a spatial tensor of 4×32×32=40964\times32\times32=4096 values, 48 times fewer, on which we train the velocity field from the flow matching lesson. The decoder then turns the generated latent into pixels. Compression changes the problem: the generative network no longer corrects each pixel directly, and final quality depends on both the autoencoder and the latent distribution it learns.

The underlying idea is due to Rombach and colleagues: most bits in a photograph describe barely perceptible detail, and modeling it with diffusion is expensive. They divide the work into two stages. First, perceptual compression trained once discards that detail while retaining structure. Then a generative model learns only the semantic part in the compressed space. This separation is latent diffusion, the basis of Stable Diffusion.

InteractiveA photograph in latent space
Original photographOriginal photograph of an astronaut
Reconstruction without noiseReconstruction with noise 0

Original latent channels (32 × 32), each rescaled from minimum to maximum:

Channel 1Latent channel 1
Channel 2Latent channel 2
Channel 3Latent channel 3
Channel 4Latent channel 4
Noise deviation in scaled latent
Mean absolute RGB error8.16
The real photograph, its four latent channels and the outputs of a fixed VAE. The same normal perturbation is multiplied by the selected level before decoding. Each channel uses its own grayscale; these are not RGB channels.

Start at level 0: this is pure reconstruction. At a glance it is almost identical to the original, with a mean absolute error of about 8 levels out of 255 concentrated in fine detail. Increase to 0.25: colors and composition remain, but the face and stars on the flag fill with spurious texture. At 0.5 the face disappears, while color regions and silhouette remain in place. At 1 only a mosaic of colored patches remains, with the layout barely discernible. Fine detail is lost first; global arrangement last. Each latent position corresponds to an 8-by-8 pixel block, so latent noise appears as texture at that scale rather than fine-grained pixel noise.

Do not overinterpret the latent channels either. A light channel does not mean “red” or an isolated semantic component: the visualization adjusts each channel’s minimum and maximum separately and discards absolute magnitude, and the decoder mixes channels and positions. Even so, the helmet and silhouette are recognizable in the first two: the latent is still an image, with spatial structure a model can exploit.

In this lesson you will build the full chain. You will encode Imagenette, a ten-class ImageNet subset, using an open-weight VAE; precompute latents; implement a diffusion transformer with adaLN-Zero conditioning; train it with flow matching; and evaluate it using the FID protocol from the evaluation lesson, always on decoded images.

Why latents: calculating the cost

A diffusion transformer treats an image as a sequence of patches, like a ViT. With 2-by-2 patches on a 32-by-32 latent there is a 16-by-16 grid, or 256 tokens. Patches of the same size on 256-by-256 pixels would yield 128 by 128 tokens, or 16,384. The attention matrix per head contains the square of that number, a difference by a factor of 4096.

[ ]Tokens and attention costBrowser
latent_tokens=(32//2)**2
pixel_tokens=(256//2)**2
print('tokens latentes',latent_tokens,'tokens de píxeles',pixel_tokens)
print('elementos por cabeza',latent_tokens**2,pixel_tokens**2,
      'razón',pixel_tokens**2//latent_tokens**2)
print('valores por imagen',3*256*256,'valores latentes',4*32*32,'compresión',3*256*256//(4*32*32))

That ratio does not predict total cost: projections, MLPs, activations, precision and kernels matter, and efficient implementations do not even materialize the attention matrix. You could also reduce pixel tokens using 16-by-16 patches, yielding 256 as well. The difference is what the network must model. Each pixel patch would contain 768 values with all their fine detail for the diffusion model to generate and correct; a latent patch has 16 values from which the autoencoder has already removed imperceptible detail. The gain from latent space therefore goes beyond token counts.

For an order-of-magnitude reference, the DiT you will train has 12 blocks of width 384 and 6 heads, the DiT-S/2 configuration of Peebles and Xie. It has 32.5 million parameters and one forward pass costs 10.9 GFLOP per image, counting a multiply and add as two operations with PyTorch’s counter.

The pretrained autoencoder

A variational encoder produces a distribution qϕ(z∣x)q_\phi(z\mid x), here a diagonal Gaussian with mean μϕ(x)\mu_\phi(x), and a decoder Dϕ(z)D_\phi(z) returns an image. The autoencoder is trained separately and frozen: its weights are not updated during field regression.

We use sd-vae-ft-mse, the Stable Diffusion KL autoencoder with a fine-tuned decoder. Its model card declares an MIT license and explains that only the decoder was fine-tuned, so the latents remain compatible with the original encoder. We pin revision 31f26fdeee1355a5c34592e401dd41e45d25a493 of the repository. It reduces each side by 8 and produces 4 channels: a 256-by-256 image gives a 4×32×324\times32\times32 latent. Sampling the posterior instead of taking its mode is another valid choice, but then the seed is part of the latent dataset and must be recorded.

The scaling factor

The raw latents of this autoencoder have a standard deviation of several units. Rombach and colleagues rescale them by the inverse standard deviation estimated over a data batch so the diffusion model receives inputs with variance near one; for the Stable Diffusion VAE this value was fixed at 0.18215. In Diffusers 0.34.0 it is the default scaling_factor in AutoencoderKL (documentation). This revision’s config.json does not declare that field: the number comes from the library default, so the lab reads it from the loaded object and saves it alongside the latents.

The factor is a single scalar estimated once. It guarantees neither zero mean nor unit variance per channel, especially on another dataset. In the viewer photograph the scaled latents have global standard deviation 0.90 and per-channel values between 0.70 and 1.03, with means between −0,30-0{,}30 and 0,300{,}30. The lab measures the same quantities on Imagenette and writes them to its report: check them before training. A global deviation far from one indicates that the scale is not what the rest of the pipeline assumes.

Reproduce the viewer

The next two cells form the basis of the lab. The first defines common utilities and the working directory; the second regenerates the viewer images. It downloads the photograph of Eileen Collins distributed by scikit-image as astronaut (a NASA image), resizes it to 256 by 256 using PIL bicubic interpolation, encodes it with the posterior mode and decodes the latent with the same normal perturbation seeded at 88, multiplied by 0, 0.25, 0.5 and 1. The mean absolute errors printed should match the viewer (8.16, 17.32, 32.51 and 58.19 on CPU); kernel differences can affect the last decimal places.

[ ]Lab utilitiesLocal GPU
import os, json, hashlib, importlib.metadata
from pathlib import Path
import numpy as np
import torch
from PIL import Image

VAE_REPO = 'stabilityai/sd-vae-ft-mse'
VAE_REVISION = '31f26fdeee1355a5c34592e401dd41e45d25a493'

def lab_dir():
    root = os.environ.get('P07_L08_WORK', '')
    if not root or not Path(root).is_absolute():
        raise ValueError('P07_L08_WORK debe ser una ruta absoluta elegida para este laboratorio')
    return Path(root)

def sha_file(path):
    with open(path, 'rb') as f:
        return hashlib.file_digest(f, 'sha256').hexdigest()

def save_atomic(path, writer):
    # Escribe en un temporal y lo renombra: un corte nunca deja un fichero a medias con el nombre final.
    tmp = path.with_name(path.name + '.tmp')
    with open(tmp, 'wb') as f:
        writer(f)
    os.replace(tmp, path)

def center_crop(image, size=256):
    # Recorte central de ADM y DiT: mitades con BOX mientras sobre, bicúbico al lado corto y recorte.
    image = image.convert('RGB')
    while min(image.size) >= 2*size:
        image = image.resize(tuple(s//2 for s in image.size), Image.Resampling.BOX)
    scale = size/min(image.size)
    image = image.resize(tuple(round(s*scale) for s in image.size), Image.Resampling.BICUBIC)
    arr = np.asarray(image)
    top, left = (arr.shape[0]-size)//2, (arr.shape[1]-size)//2
    return arr[top:top+size, left:left+size]

def to_unit(arrays, device):
    return torch.from_numpy(np.stack(arrays)).permute(0, 3, 1, 2).float().to(device)/127.5 - 1

def to_uint8(x):
    return ((x.float().clamp(-1, 1)+1)*127.5).round().to(torch.uint8).permute(0, 2, 3, 1).cpu().numpy()

def load_vae(device):
    from diffusers import AutoencoderKL
    vae = AutoencoderKL.from_pretrained(VAE_REPO, revision=VAE_REVISION, use_safetensors=True)
    return vae.to(device).eval().requires_grad_(False)

print('Utilidades listas; directorio del laboratorio:', os.environ.get('P07_L08_WORK', 'sin definir'))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Encode and decode a real photographLocal GPU
import urllib.request

ASTRONAUT_URL = 'https://raw.githubusercontent.com/scikit-image/scikit-image/v0.25.2/skimage/data/astronaut.png'

def latent_demo(work, device='cpu'):
    out = work/'demo'; out.mkdir(parents=True, exist_ok=True)
    source = out/'astronaut.png'
    if not source.exists():
        urllib.request.urlretrieve(ASTRONAUT_URL, source)
    print('sha256 de la fotografía', sha_file(source))
    original = Image.open(source).convert('RGB').resize((256, 256), Image.Resampling.BICUBIC)
    reference = np.asarray(original).astype(np.float64)
    vae = load_vae(device)
    with torch.inference_mode():
        z = vae.encode(to_unit([np.asarray(original)], device)).latent_dist.mode()*vae.config.scaling_factor
        print('escala', vae.config.scaling_factor, 'forma', tuple(z.shape), 'desviación global', round(float(z.std()), 4))
        print('desviación por canal', [round(float(s), 4) for s in z.std(dim=(0, 2, 3))])
        for i, channel in enumerate(z[0].cpu().numpy()):
            low, high = channel.min(), channel.max()
            Image.fromarray(np.rint((channel-low)/(high-low)*255).astype(np.uint8)).save(out/f'channel{i}.png')
        noise = torch.randn(z.shape, generator=torch.Generator().manual_seed(88)).to(device)
        for sigma, name in [(0., 'reconstruction'), (.25, 'noise025'), (.5, 'noise05'), (1., 'noise1')]:
            image = to_uint8(vae.decode((z + sigma*noise)/vae.config.scaling_factor).sample)[0]
            Image.fromarray(image).save(out/f'{name}.png')
            print('sigma', sigma, 'error absoluto medio RGB', round(float(np.abs(image-reference).mean()), 2))
    original.save(out/'original.png')
    del vae

if os.environ.get('P07_L08_DEMO') == '1':
    latent_demo(lab_dir())
else:
    print('Demostración omitida: define P07_L08_WORK y P07_L08_DEMO=1 para ejecutarla.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Scaling factor and signal-to-noise ratio

What happens if the factor is forgotten or applied twice? Intuitively, process noise has fixed variance but the data do not: larger data are more visible through the noise at each time tt. If a latent coordinate has variance vv and we add independent noise of variance σ2\sigma^2, its signal-to-noise ratio is v/σ2v/\sigma^2; multiplying the data by cc changes it to c2v/σ2c^2v/\sigma^2. In flow matching the calculation is exact and particularly neat: changing scale is equivalent to warping time.

Proof

Check both coefficients. For the data, s(t) τ(t)=cts(t)\,\tau(t)=ct. For the noise, s(t) (1−τ(t))=1+(c−1)t−ct=1−ts(t)\,(1-\tau(t))=1+(c-1)t-ct=1-t. Thus s(t)Zτ(t)=(1−t)ε+ct X=Zt(c)s(t)Z_{\tau(t)}=(1-t)\eps+ct\,X=Z^{(c)}_t. Since s(t)>0s(t)>0, τ(t)/(1−τ(t))=ct/(1−t)\tau(t)/(1-\tau(t))=ct/(1-t); taking logarithms gives the logit relationship. The original path’s signal-to-noise ratio at τ\tau is τ2v/(1−τ)2=c2t2v/(1−t)2\tau^2v/(1-\tau)^2=c^2t^2v/(1-t)^2, that of the scaled path at tt. Finally, τ\tau is continuous, strictly increasing and fixes 00 and 11, so it reparameterizes the interval.

∎

The theorem states exactly what breaks. If you train without the 0.18215 factor, the data are multiplied by c=1/0,18215≈5,49c=1/0{,}18215\approx5{,}49 relative to the intended values. Nominal time t=0,5t=0{,}5 behaves like τ≈0,846\tau\approx0{,}846, the signal-to-noise ratio is multiplied by c2≈30c^2\approx30 at all times, and the network also receives inputs multiplied by s(t)s(t), up to 5.49 times larger. With uniform tt during training, most of the budget is spent at times when data are already nearly visible, and very little in the noisy region where global composition is decided. Dividing before decoding at the end does not fix it: training has already seen a different family of inputs.

[ ]Effective time with and without scalingBrowser
import math
c=1/0.18215
for t in (0.25,0.5,0.75,0.9):
    tau=c*t/(1+(c-1)*t)
    print(f't={t:.2f}  tau={tau:.4f}  logit(tau)-logit(t)={math.log(tau/(1-tau))-math.log(t/(1-t)):.4f}')
print('log c',round(math.log(c),4),'c^2',round(c*c,2))

The same algebraic form appears in Esser and colleagues, who use it deliberately: when moving to higher resolutions they shift the time schedule with τ=αt/(1+(α−1)t)\tau=\alpha t/(1+(\alpha-1)t) to compensate for the fact that more pixels reveal the image with less noise. They use the opposite time direction (t=1t=1 is noise), so transferring a formula requires reversing time and the sign of velocity consistently. The lesson is the same: data scale and noise schedule belong together. This is the latent scaling you studied in the generative models module.

Reconstruction and generative quality

Before training anything, measure how well the autoencoder works on your data. Decode the evaluation set’s latents, apply the same preprocessing and extractor to originals and reconstructions, and calculate FID: this is reconstruction FID or rFID. Record size, split, VAE, libraries, extractor version and posterior convention. FID compares feature moments of two sets; it does not measure paired error or identify failed images. The lab therefore adds mean per-image PSNR and saves reconstructions for inspection.

The VAE model card reports rFID 4.70 and PSNR 24,5±3,724{,}5\pm3{,}7 dB for ft-MSE on 5,000 COCO 2017 validation images at 256 by 256. This is its authors’ protocol, not a universal threshold or a prediction for Imagenette. The viewer photograph’s reconstruction has PSNR 24.4 dB, within that range.

Why is rFID a reference for achievable quality? The generative model is trained to reproduce the distribution of latents c μϕ(x)c\,\mu_\phi(x) from the training set. A perfect generator for that objective would produce exactly those latents and, upon decoding, the distribution of reconstructions Dϕ(μϕ(x))D_\phi(\mu_\phi(x)). Its FID would be the rFID measured on training data, approximated by evaluation-set rFID. That is the quality targeted by training, not a mathematical bound for every generator. The triangle inequality states what can be claimed.

Proof

For two Gaussians, the FID formula,

F=∥μ1−μ2∥2+tr⁡(Σ1+Σ2)−2tr⁡((Σ11/2Σ2Σ11/2)1/2),\begin{aligned} F={}&\lVert\vb\mu_1-\vb\mu_2\rVert^2+\tr(\mat\Sigma_1+\mat\Sigma_2)\\ &-2\tr\bigl((\mat\Sigma_1^{1/2}\mat\Sigma_2\mat\Sigma_1^{1/2})^{1/2}\bigr), \end{aligned}

is the square of their Wasserstein distance W2W_2 (Dowson and Landau, 1982). W2W_2 is a metric on distributions with finite second moment, and all three Gaussians have one. Applying the triangle inequality to W2(G,R)≤W2(G,Rec)+W2(Rec,R)W_2(G,R)\le W_2(G,\mathrm{Rec})+W_2(\mathrm{Rec},R) and W2(Rec,R)≤W2(Rec,G)+W2(G,R)W_2(\mathrm{Rec},R)\le W_2(\mathrm{Rec},G)+W_2(G,R) gives both sides of the absolute-value bound.

∎

If generated samples resemble reconstructions, in the sense that FID⁡(G,Rec)\operatorname{FID}(G,\mathrm{Rec}) is small, generated FID cannot lie far below rFID. To go below it, the generator would have to move away from the reconstruction distribution, the opposite of what training asks. A high rFID therefore suggests improving the autoencoder or evaluation before spending GPU time on the DiT.

It is not an absolute bound, as a one-dimensional counterexample shows. Take X∼N(0,1)X\sim\Normal(0,1), an encoder E(X)=0E(X)=0 and D(z)=z+1D(z)=z+1: all reconstructions equal 1. A generator producing Z∼N(−1,1)Z\sim\Normal(-1,1) decodes exactly the distribution of XX. The Gaussian Fréchet distance is 2 for reconstructions and 0 for that generated distribution. This counterexample uses one-dimensional features, not a measured Inception FID; it illustrates that the theorem does not prevent going below rFID, but requires moving away from reconstructions.

[ ]Counterexample to a reconstruction boundBrowser
def frechet_1d(mean_a,sd_a,mean_b,sd_b):
    return (mean_a-mean_b)**2+(sd_a-sd_b)**2
rec,gen,gen_rec=frechet_1d(0,1,1,0),frechet_1d(0,1,0,1),frechet_1d(0,1,1,0)
print('reconstrucción',rec,'generación',gen,'generación frente a reconstrucción',gen_rec)
print('desigualdad triangular:',abs(gen**.5-rec**.5),'<=',gen_rec**.5)

Precompute latents and augment without breaking the autoencoder

The VAE encoder is much more expensive than the small DiT: with the same PyTorch counter, encoding a 256-by-256 image costs 271 GFLOP, about 25 times one DiT forward pass and about 8 times a full training step per image (forward and backward, about 33 GFLOP). The decoder costs 620 GFLOP, as much as 57 DiT Euler steps: in evaluation it costs as much as sampling. Encoding each image every epoch pays that price hundreds of times per image. Because the encoder is frozen and we use the mode, its output for a fixed image is always the same: encode once and save it. With Imagenette at 256 by 256, two-view training latents occupy about 310 MB in float32 and fit entirely on the GPU.

The problem arises with data augmentation. For random horizontal flips each epoch, one might flip the latent instead of the image. That would work if the encoder commuted with flipping, μϕ(flip⁡x)=flip⁡μϕ(x)\mu_\phi(\operatorname{flip}x)=\operatorname{flip}\mu_\phi(x). It does not: its convolutions do not have symmetric kernels. In the viewer photograph, the relative difference between flip⁡μϕ(x)\operatorname{flip}\mu_\phi(x) and μϕ(flip⁡x)\mu_\phi(\operatorname{flip}x) is 82%. Decoding the flipped latent and comparing it with the flipped image drops PSNR to 16.5 dB, versus 24.6 dB for encoding the flipped image. Flipping in latent space produces latents the encoder never generates: you would train on out-of-distribution data.

The solution is to precompute several identified views: the lab saves μϕ(x)\mu_\phi(x) and μϕ(flip⁡x)\mu_\phi(\operatorname{flip}x) for each training image and samples from both. It also measures the mean relative difference over all Imagenette and saves it in the report, so you can check the phenomenon is not peculiar to one photograph. Richer augmentations, such as random crops, require more precomputed views or accepting repeated encoding and measuring its cost; they are not equivalent, so state which was used.

For your own dataset, first freeze the image list and splits, apply the same preprocessing and save the scale, posterior convention and versions with the latents. Check that training and evaluation share no images: file hashes detect exact copies, not near-duplicates. Imagenette already provides official splits: according to its repository, 9,469 training and 3,925 validation images in ten classes. The lab uses the 320-pixel version, center-crops to 256 with ADM and DiT preprocessing, and writes a report with counts, per-channel means and deviations, and each file’s fingerprint.

The diffusion transformer

DiT is a standard transformer with two changes: its input is patches of a latent, and each block receives a global condition (time and class) that modulates its normalizations.

With p=2p=2, C=4C=4 and H=W=32H=W=32 we get T=256T=256 tokens of 1616 values each. The output has the latent’s shape because it is the field velocity at that point.

The block is a transformer block with multi-head attention and an MLP, but normalization has no affine parameters of its own: it receives them from the condition. A projection of c\vb c produces six vectors in Rd\R^d: shift β1\vb\beta_1, scale γ1\vb\gamma_1 and gate α1\vb\alpha_1 for attention, and β2,γ2,α2\vb\beta_2,\vb\gamma_2,\vb\alpha_2 for the MLP. With parameter-free LN⁡\operatorname{LN} and elementwise products applied to each token,

Y1=LN⁡(X)⊙(1+γ1)+β1,X′=X+α1⊙Attn⁡(Y1),Y2=LN⁡(X′)⊙(1+γ2)+β2,B(X,c)=X′+α2⊙MLP⁡(Y2).\begin{aligned} \mat Y_1 &= \operatorname{LN}(\mat X)\odot(1+\vb\gamma_1)+\vb\beta_1,\\ \mat X' &= \mat X+\vb\alpha_1\odot\operatorname{Attn}(\mat Y_1),\\ \mat Y_2 &= \operatorname{LN}(\mat X')\odot(1+\vb\gamma_2)+\vb\beta_2,\\ B(\mat X,\vb c) &= \mat X'+\vb\alpha_2\odot\operatorname{MLP}(\mat Y_2). \end{aligned}

This is the official DiT implementation, with the same order of six vectors. The “Zero” in adaLN-Zero refers to initialization: the final linear layer of the projection producing the six vectors starts at zero, as do the final layer’s modulation and output projection.

Proof

With a zero layer, all six vectors are zero for any c\vb c. Then α1=0\vb\alpha_1=\vb 0 gives X′=X\mat X'=\mat X and α2=0\vb\alpha_2=\vb 0 gives B(X,c)=X′=XB(\mat X,\vb c)=\mat X'=\mat X. The model output is Wh+b\mat W\vb h+\vb b per token, with h\vb h the final normalization output; with W=0\mat W=\mat 0 and b=0\vb b=\vb 0 it is zero.

For the gradient, let δ=∂L/∂(output)\vb\delta=\partial L/\partial(\text{output}). The derivatives with respect to W\mat W and b\vb b are δh⊤\vb\delta\vb h^\top and δ\vb\delta, generally nonzero. Any other parameter θ\theta affects the output only through h\vb h, so by the chain rule ∂L/∂θ=(∂h/∂θ)⊤W⊤δ=0\partial L/\partial\theta=(\partial\vb h/\partial\theta)^\top\mat W^\top\vb\delta=0.

∎

The theorem has an often overlooked consequence: the network wakes up layer by layer. With AdamW without weight decay, an exactly zero gradient leaves moments and the update at zero, so the first step moves only the output projection. On the second, W≠0\mat W\neq\mat 0 and the gradient reaches the final modulation, the α\vb\alpha gates of each block and, through residual connections, the patch projection. Block shifts, scales, attention and MLPs still have zero gradient because they are multiplied by gates that remain zero. Each block starts as identity and activates only as its gate grows. Peebles and Xie compare this initialization with other conditioning methods, and adaLN-Zero achieves the best FID among those tested.

The next cell implements the model and checks all this on CPU: block identity, inverse patch reassembly, zero output and the order in which parameters receive gradients in the first three steps.

[ ]Latent DiT with adaLN-ZeroLocal GPU
import math
import torch
from torch import nn
import torch.nn.functional as F

def timestep_embedding(t, dim=256, max_period=10000):
    # t en [0,1] se lleva a [0,1000], la escala de los pasos discretos de DiT.
    half = dim//2
    freqs = torch.exp(-math.log(max_period)*torch.arange(half, device=t.device)/half)
    args = 1000*t.float()[:, None]*freqs[None]
    return torch.cat([torch.cos(args), torch.sin(args)], dim=-1)

def sincos_2d(width, grid):
    # Posiciones fijas de DiT: la mitad de los canales codifica la fila y la otra mitad la columna.
    def axis(pos, dim):
        omega = 1/10000**(torch.arange(dim//2, dtype=torch.float64)/(dim/2))
        angle = pos.reshape(-1).double()[:, None]*omega[None]
        return torch.cat([torch.sin(angle), torch.cos(angle)], dim=1)
    rows, cols = torch.meshgrid(torch.arange(grid), torch.arange(grid), indexing='ij')
    return torch.cat([axis(rows, width//2), axis(cols, width//2)], dim=1).float()

class Attention(nn.Module):
    def __init__(self, width, heads):
        super().__init__()
        self.heads = heads
        self.qkv = nn.Linear(width, 3*width)
        self.proj = nn.Linear(width, width)
    def forward(self, x):
        B, T, D = x.shape
        q, k, v = self.qkv(x).reshape(B, T, 3, self.heads, D//self.heads).permute(2, 0, 3, 1, 4)
        y = F.scaled_dot_product_attention(q, k, v)
        return self.proj(y.transpose(1, 2).reshape(B, T, D))

class AdaBlock(nn.Module):
    def __init__(self, width, heads):
        super().__init__()
        self.norm1 = nn.LayerNorm(width, elementwise_affine=False, eps=1e-6)
        self.norm2 = nn.LayerNorm(width, elementwise_affine=False, eps=1e-6)
        self.attn = Attention(width, heads)
        self.mlp = nn.Sequential(nn.Linear(width, 4*width), nn.GELU(approximate='tanh'), nn.Linear(4*width, width))
        self.mod = nn.Sequential(nn.SiLU(), nn.Linear(width, 6*width))
    def forward(self, x, c):
        shift1, scale1, gate1, shift2, scale2, gate2 = self.mod(c)[:, None].chunk(6, dim=-1)
        x = x + gate1*self.attn(self.norm1(x)*(1+scale1) + shift1)
        return x + gate2*self.mlp(self.norm2(x)*(1+scale2) + shift2)

class LatentDiT(nn.Module):
    def __init__(self, width=384, depth=12, heads=6, patch=2, channels=4, size=32, classes=10):
        super().__init__()
        self.patch, self.channels, self.grid, self.classes = patch, channels, size//patch, classes
        self.embed = nn.Conv2d(channels, width, patch, stride=patch)
        self.register_buffer('pos', sincos_2d(width, self.grid)[None], persistent=False)
        self.time = nn.Sequential(nn.Linear(256, width), nn.SiLU(), nn.Linear(width, width))
        self.label = nn.Embedding(classes+1, width)   # el índice `classes` es la etiqueta nula de la guía
        self.blocks = nn.ModuleList([AdaBlock(width, heads) for _ in range(depth)])
        self.final_norm = nn.LayerNorm(width, elementwise_affine=False, eps=1e-6)
        self.final_mod = nn.Sequential(nn.SiLU(), nn.Linear(width, 2*width))
        self.out = nn.Linear(width, patch*patch*channels)
        self.reset_parameters()
    def reset_parameters(self):
        for m in self.modules():
            if isinstance(m, nn.Linear):
                nn.init.xavier_uniform_(m.weight); nn.init.zeros_(m.bias)
        nn.init.xavier_uniform_(self.embed.weight.view(self.embed.weight.shape[0], -1))
        nn.init.zeros_(self.embed.bias)
        nn.init.normal_(self.label.weight, std=0.02)
        nn.init.normal_(self.time[0].weight, std=0.02); nn.init.normal_(self.time[2].weight, std=0.02)
        for layer in [b.mod[-1] for b in self.blocks] + [self.final_mod[-1], self.out]:
            nn.init.zeros_(layer.weight); nn.init.zeros_(layer.bias)   # adaLN-Zero
    def patchify(self, z):
        B, C, p, g = z.shape[0], self.channels, self.patch, self.grid
        return z.reshape(B, C, g, p, g, p).permute(0, 2, 4, 3, 5, 1).reshape(B, g*g, p*p*C)
    def unpatchify(self, tokens):
        B, C, p, g = tokens.shape[0], self.channels, self.patch, self.grid
        return tokens.reshape(B, g, g, p, p, C).permute(0, 5, 1, 3, 2, 4).reshape(B, C, g*p, g*p)
    def forward(self, z, t, y):
        x = self.embed(z).flatten(2).transpose(1, 2) + self.pos
        c = self.time(timestep_embedding(t)) + self.label(y)
        for block in self.blocks:
            x = block(x, c)
        shift, scale = self.final_mod(c)[:, None].chunk(2, dim=-1)
        return self.unpatchify(self.out(self.final_norm(x)*(1+scale) + shift))

def group(name):
    if name.startswith('blocks.'):
        part = name.split('.')[2]
        return 'modulación de bloques' if part == 'mod' else 'atención y MLP'
    return name.split('.')[0]

torch.manual_seed(21)
model = LatentDiT()
z, t, y = torch.randn(4, 4, 32, 32), torch.rand(4), torch.tensor([3, 10, 0, 7])
x, c = torch.randn(2, 256, 384), torch.randn(2, 384)
print('parámetros', sum(p.numel() for p in model.parameters()))
print('bloque idéntico al inicio:', torch.equal(model.blocks[0](x, c), x))
print('unpatchify∘patchify = id:', torch.equal(model.unpatchify(model.patchify(z)), z))
print('primer token = parche superior izquierdo:',
      torch.equal(model.patchify(z)[:, 0], z[:, :, :2, :2].permute(0, 2, 3, 1).reshape(4, -1)))
with torch.no_grad():
    print('salida inicial nula:', float(model(z, t, y).abs().max()))
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0)
target = torch.randn_like(z)
for step in (1, 2, 3):
    opt.zero_grad(set_to_none=True)
    (model(z, t, y)-target).square().mean().backward()
    moving = sorted({group(n) for n, p in model.named_parameters() if p.grad is not None and p.grad.abs().max() > 0})
    print('paso', step, 'gradiente no nulo en:', moving)
    opt.step()
del model, opt, z, t, y, x, c, target
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Within each block the cell distinguishes modulation (which receives gradient only in the gate rows on step two) from the rest. Notice that time and class do not receive gradients until the third step: the condition enters only through modulations whose weights start at zero.

The 8 GB budget

Counting parameters is not enough to determine whether training fits on the GPU (review the memory budget). The 32.5 million parameters occupy 130 MB in float32; with gradients and both AdamW moments, about 520 MB, plus another 130 MB for the EMA copy. The dominant cost is activations saved for the backward pass, which grow linearly with batch size: 12 blocks, 256 tokens, width 384 and an MLP of width 1536 per image. Measured on an 8 GB RTX 4060 Laptop with bf16 autocast and PyTorch attention, peak allocated memory in a training step with EMA is 1.60 GiB at batch 16, 2.46 GiB at batch 32 and 4.19 GiB at batch 64: about 55 MiB per image above a fixed base. At batch 128 it reaches 7.78 GiB, too tight for an 8 GB card that also hosts the CUDA context and desktop. The lab therefore uses batch 64, plus the 310 MB of latents uploaded to the GPU. Measure on your machine with torch.cuda.max_memory_allocated(), printed by the training log; the CUDA context and other applications consume memory outside that counter.

Training with flow matching

The objective is from p07-l07: a clean latent Z1Z_1 with class yy, independent noise Z0∼N(0,I)Z_0\sim\Normal(0,I), time t∼U[0,1]t\sim\mathcal U[0,1], point Zt=(1−t)Z0+tZ1Z_t=(1-t)Z_0+tZ_1 and regression of velocity Z1−Z0Z_1-Z_0:

L(θ)=14096 E∥vθ−(Z1−Z0)∥2,\mathcal L(\theta)=\tfrac{1}{4096}\,\E\lVert v_\theta-(Z_1-Z_0)\rVert^2,

where vθ=vθ(Zt,t,y~)v_\theta=v_\theta(Z_t,t,\tilde y). The loss is a mean per coordinate, not a sum; keep that convention when comparing experiments. To use classifier-free guidance in sampling, label y~\tilde y is replaced by the null label with probability 0.1, as in DiT; the same network thus learns conditional and unconditional fields.

The remaining choices follow DiT: AdamW with constant rate 10−410^{-4} and no weight decay, and an exponential moving average (EMA) of weights with decay 0.9999, which is evaluated. Initially decay is min⁡(0,9999,(1+k)/(10+k))\min(0{,}9999,(1+k)/(10+k)) at step kk, so the EMA does not carry the initialization for thousands of steps. Esser and colleagues find that sampling tt from a logit-normal distribution, concentrating training on intermediate times, improves over uniform; here we use p07-l07’s uniform distribution and leave the alternative as an experiment.

The lab is designed for your GPU, in independent phases that read and write in P07_L08_WORK (an absolute path you choose, with at least 5 GB free). Each phase is activated with its environment variable in the environment running the local cells: P07_L08_PREPARE=1, P07_L08_RFID=1, P07_L08_TRAIN=1 and P07_L08_EVAL=1. It needs Diffusers 0.34.0, a torchvision version including datasets.Imagenette and clean-fid, as in p07-l02. The first phase downloads 320-pixel Imagenette through torchvision, which verifies its MD5, and VAE weights from the Hub at the pinned revision; the rFID phase downloads clean-fid’s Inception extractor.

[ ]Phase 1: precompute Imagenette latentsLocal GPU
def prepare_latents(work, device='cuda', batch=16):
    from torchvision.datasets import Imagenette
    out = work/'latents'
    if (out/'report.json').exists():
        print('Los latentes ya están precalculados en', out)
        return json.loads((out/'report.json').read_text(encoding='utf-8'))
    (out/'val_images').mkdir(parents=True, exist_ok=True)
    vae = load_vae(device)
    scale = float(vae.config.scaling_factor)
    report = {'vae': VAE_REPO, 'revision': VAE_REVISION, 'scaling_factor': scale, 'posterior': 'mode',
              'preprocess': 'center crop 256 (ADM)',
              'versions': {n: importlib.metadata.version(n) for n in ('torch', 'torchvision', 'diffusers', 'numpy', 'Pillow')}}
    try:
        for split in ('train', 'val'):
            data = Imagenette(work/'data', split=split, size='320px', download=True)
            views, labels, flip_err = {'latents': [], 'flipped': []}, [], []
            for start in range(0, len(data), batch):
                items = [data[i] for i in range(start, min(start+batch, len(data)))]
                arrays = [center_crop(im) for im, _ in items]
                labels += [label for _, label in items]
                if split == 'val':
                    for i, arr in enumerate(arrays):
                        Image.fromarray(arr).save(out/'val_images'/f'{start+i:05d}.png')
                with torch.inference_mode():
                    x = to_unit(arrays, device)
                    z = vae.encode(x).latent_dist.mode()*scale
                    views['latents'].append(z.cpu())
                    if split == 'train':   # segunda vista: se codifica la imagen volteada
                        zf = vae.encode(x.flip(-1)).latent_dist.mode()*scale
                        views['flipped'].append(zf.cpu())
                        flip_err += ((z.flip(-1)-zf).flatten(1).norm(dim=1)/zf.flatten(1).norm(dim=1)).tolist()
                if start % (100*batch) == 0:
                    print(split, 'codificadas', start+len(items), 'de', len(data), flush=True)
            arrays = {k: torch.cat(v).numpy() for k, v in views.items() if v}
            arrays['labels'] = np.array(labels, dtype=np.int64)
            target = out/f'{split}.npz'
            save_atomic(target, lambda f: np.savez(f, **arrays))
            lat = arrays['latents']
            report[split] = {'images': len(data), 'classes': len(data.classes), 'shape': list(lat.shape),
                             'channel_mean': [round(float(v), 4) for v in lat.mean(axis=(0, 2, 3))],
                             'channel_std': [round(float(v), 4) for v in lat.std(axis=(0, 2, 3))],
                             'global_std': round(float(lat.std()), 4), 'sha256': sha_file(target)}
            if flip_err:
                report[split]['flip_relative_error'] = {'mean': round(float(np.mean(flip_err)), 4),
                                                        'max': round(float(np.max(flip_err)), 4)}
            print(split, json.dumps(report[split], ensure_ascii=False))
    finally:
        del vae
        if str(device).startswith('cuda'): torch.cuda.empty_cache()
    (out/'report.json').write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding='utf-8')
    return report

if os.environ.get('P07_L08_PREPARE') == '1':
    prepare_latents(lab_dir())
else:
    print('Precálculo omitido: define P07_L08_WORK y P07_L08_PREPARE=1 para ejecutarlo.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The latents/report.json report should show 9,469 training and 3,925 validation images in 10 classes, latents of shape 4×32×324\times32\times32, the global standard deviation of scaled latents, and the mean relative difference between latent flipping and encoding flipped images.

[ ]Phase 2: reconstruction FIDLocal GPU
class InceptionFeatures:
    # El extractor y el redimensionado «clean» de p07-l02.
    def __init__(self, work, device='cuda'):
        from cleanfid.inception_torchscript import InceptionV3W
        from cleanfid.resize import build_resizer
        self.device = device
        self.model = InceptionV3W(str(work), download=True).eval().to(device)
        self.resize = build_resizer('clean')
        self.weights_sha256 = sha_file(work/'inception-2015-12-05.pt')
    @torch.inference_mode()
    def __call__(self, arrays):
        x = np.stack([self.resize(a) for a in arrays]).transpose(0, 3, 1, 2)
        return self.model(torch.from_numpy(x).to(self.device)).cpu().numpy().astype(np.float64)

def gaussian_stats(features):
    f = np.concatenate(features)
    return f.mean(axis=0), np.cov(f, rowvar=False), len(f)

def fid_from_stats(a, b):
    from cleanfid.fid import frechet_distance
    return float(frechet_distance(a[0], a[1], b[0], b[1]))

def real_val_stats(work, extractor, batch=50):
    cache = work/'fid_val_stats.npz'
    if cache.exists():
        with np.load(cache) as d: return d['mu'], d['sigma'], int(d['n'])
    paths = sorted((work/'latents'/'val_images').glob('*.png'))
    feats = [extractor([np.asarray(Image.open(p)) for p in paths[i:i+batch]]) for i in range(0, len(paths), batch)]
    mu, sigma, n = gaussian_stats(feats)
    save_atomic(cache, lambda f: np.savez(f, mu=mu, sigma=sigma, n=n))
    return mu, sigma, n

def reconstruction_fid(work, device='cuda', batch=8):
    out = work/'reconstructions'
    out.mkdir(exist_ok=True)
    with np.load(work/'latents'/'val.npz') as d: latents = torch.from_numpy(d['latents'])
    paths = sorted((work/'latents'/'val_images').glob('*.png'))
    assert len(paths) == len(latents)
    vae = load_vae(device); extractor = InceptionFeatures(work, device)
    feats, psnr = [], []
    try:
        for start in range(0, len(latents), batch):
            with torch.inference_mode():
                rec = to_uint8(vae.decode(latents[start:start+batch].to(device)/vae.config.scaling_factor).sample)
            real = np.stack([np.asarray(Image.open(p)) for p in paths[start:start+batch]])
            mse = ((rec.astype(np.float64)-real)**2).mean(axis=(1, 2, 3))
            psnr += (10*np.log10(255**2/np.maximum(mse, 1e-10))).tolist()
            feats.append(extractor(list(rec)))
            for i, im in enumerate(rec):
                Image.fromarray(im).save(out/f'{start+i:05d}.png')
        result = {'rfid': fid_from_stats(gaussian_stats(feats), real_val_stats(work, extractor)),
                  'n': len(latents), 'psnr_mean': float(np.mean(psnr)), 'psnr_std': float(np.std(psnr)),
                  'extractor_sha256': extractor.weights_sha256}
    finally:
        del vae, extractor
        if str(device).startswith('cuda'): torch.cuda.empty_cache()
    (work/'rfid.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
    print(json.dumps(result, ensure_ascii=False))
    return result

if os.environ.get('P07_L08_RFID') == '1':
    reconstruction_fid(lab_dir())
else:
    print('rFID omitido: define P07_L08_WORK y P07_L08_RFID=1 tras el precálculo.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

rFID is calculated with the 3,925 validation images against their reconstructions, and FID for generated samples uses exactly that count and the same real statistics. With a few thousand images the FID estimator has an appreciable positive bias depending on sample size (Chong and Forsyth): therefore compare only figures with the same nn, and none are comparable with a published FID-50K.

[ ]Phase 3: train DiT on latentsLocal GPU
import time, copy

CONFIG = dict(width=384, depth=12, heads=6, batch=64, lr=1e-4, steps=100_000, checkpoint_every=10_000,
              log_every=1000, ema=0.9999, label_drop=0.1, seed=88)

def train_dit(work, device='cuda', **overrides):
    cfg = {**CONFIG, **overrides}
    with np.load(work/'latents'/'train.npz') as d:
        latents = torch.from_numpy(np.concatenate([d['latents'], d['flipped']])).to(device)
        labels = torch.from_numpy(np.concatenate([d['labels'], d['labels']])).to(device)
    classes = int(labels.max())+1
    model = LatentDiT(cfg['width'], cfg['depth'], cfg['heads'], classes=classes).to(device)
    ema = copy.deepcopy(model).requires_grad_(False)
    opt = torch.optim.AdamW(model.parameters(), lr=cfg['lr'], weight_decay=0)
    gen = torch.Generator(device).manual_seed(cfg['seed'])
    folder = work/'checkpoints'; folder.mkdir(exist_ok=True)
    latest, step, history = folder/'latest.pt', 0, []
    if latest.exists():   # reanudación: modelo, EMA, optimizador, generador y paso
        state = torch.load(latest, map_location=device, weights_only=True)
        fixed = ('width', 'depth', 'heads', 'batch', 'lr', 'ema', 'label_drop', 'seed')
        if any(state['config'][k] != cfg[k] for k in fixed): raise ValueError('latest.pt se creó con otra configuración')
        model.load_state_dict(state['model']); ema.load_state_dict(state['ema'])
        opt.load_state_dict(state['opt']); gen.set_state(state['gen'].cpu())
        step, history = state['step'], state['history']
        del state
        print('reanudado en el paso', step)
    window, tick = [], time.perf_counter()
    if str(device).startswith('cuda'): torch.cuda.reset_peak_memory_stats()
    model.train()
    try:
        while step < cfg['steps']:
            idx = torch.randint(len(latents), (cfg['batch'],), device=device, generator=gen)
            z1, y = latents[idx], labels[idx]
            drop = torch.rand(len(y), device=device, generator=gen) < cfg['label_drop']
            y = torch.where(drop, torch.full_like(y, classes), y)      # etiqueta nula para la guía
            z0 = torch.randn(z1.shape, device=device, generator=gen)
            t = torch.rand(len(y), device=device, generator=gen)
            zt = (1-t[:, None, None, None])*z0 + t[:, None, None, None]*z1
            with torch.autocast('cuda', dtype=torch.bfloat16, enabled=str(device).startswith('cuda')):
                v = model(zt, t, y)
            loss = F.mse_loss(v.float(), z1-z0)
            opt.zero_grad(set_to_none=True); loss.backward(); opt.step()
            step += 1
            decay = min(cfg['ema'], (1+step)/(10+step))
            with torch.no_grad():
                torch._foreach_lerp_(list(ema.parameters()), list(model.parameters()), 1-decay)
            window.append(loss.detach())
            if step % cfg['log_every'] == 0 or step == cfg['steps']:
                mean = float(torch.stack(window).mean()); elapsed = time.perf_counter()-tick
                history.append([step, mean])
                peak = torch.cuda.max_memory_allocated()/2**30 if str(device).startswith('cuda') else 0.0
                print(f'paso {step}  pérdida {mean:.4f}  {elapsed/len(window):.3f} s/paso  pico {peak:.2f} GiB', flush=True)
                window, tick = [], time.perf_counter()
            if step % cfg['checkpoint_every'] == 0 or step == cfg['steps']:
                save_atomic(folder/f'ema_{step:07d}.pt',
                            lambda f: torch.save({'ema': ema.state_dict(), 'config': cfg, 'step': step}, f))
                state = {'model': model.state_dict(), 'ema': ema.state_dict(), 'opt': opt.state_dict(),
                         'gen': gen.get_state(), 'step': step, 'config': cfg, 'history': history}
                save_atomic(latest, lambda f: torch.save(state, f))
                del state
    finally:
        del model, ema, opt, latents, labels
        if str(device).startswith('cuda'): torch.cuda.empty_cache()
    (work/'train_history.json').write_text(json.dumps(history), encoding='utf-8')

if os.environ.get('P07_L08_TRAIN') == '1':
    train_dit(lab_dir(), **json.loads(os.environ.get('P07_L08_OVERRIDES', '{}')))
else:
    print('Entrenamiento omitido: define P07_L08_WORK y P07_L08_TRAIN=1 tras el precálculo.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Full training is 100,000 steps at batch 64, about 6.4 million examples, or around 340 passes over the 18,938 views. It saves the EMA every 10,000 steps (ema_0010000.pt, …) and a complete latest.pt for automatic resumption: if interrupted, rerun the cell and it continues from the last save with the same random generator state. Saves are atomic, so interruption during writing does not leave a corrupted file under the final name. P07_L08_OVERRIDES accepts JSON to change configuration, for example {"steps": 2000, "checkpoint_every": 1000} for a first test; resumption refuses changes to parameters defining the experiment. Every 1,000 steps the log prints mean loss, time per step and peak memory; your machine’s time per step lets you estimate total duration.

Flow-matching loss does not fall to zero even for a perfect model: the optimal field is a conditional expectation and variance of Z1−Z0Z_1-Z_0 around it remains as a floor. A loss that keeps falling does not certify better samples; FID serves that purpose.

Evaluate decoded images

After training, for each saved checkpoint generate 3,925 latents with the validation classes and fixed seeds, integrate with 50 Euler steps from t=0t=0 to t=1t=1, undo scaling, decode and calculate FID against the phase-2 validation statistics. With guidance scale ww, velocity is v∅+w (vy−v∅)v_\varnothing+w\,(v_y-v_\varnothing), as in p07-l06; w=1w=1 is the conditional model without guidance.

[ ]Phase 4: samples, FID curve and figuresLocal GPU
@torch.no_grad()
def sample_latents(model, labels, euler_steps, guidance, seed, device):
    gen = torch.Generator(device).manual_seed(seed)
    z = torch.randn((len(labels), 4, 32, 32), device=device, generator=gen)
    null = torch.full_like(labels, model.classes)
    for j in range(euler_steps):
        t = torch.full((len(labels),), j/euler_steps, device=device)
        with torch.autocast('cuda', dtype=torch.bfloat16, enabled=str(device).startswith('cuda')):
            if guidance == 1:
                v = model(z, t, labels)
            else:   # guía sin clasificador de p07-l06: v_nula + w (v_y - v_nula)
                vc, vu = model(torch.cat([z, z]), torch.cat([t, t]), torch.cat([labels, null])).chunk(2)
                v = vu + guidance*(vc-vu)
        z = z + v.float()/euler_steps
    return z

def evaluate_checkpoints(work, steps=None, euler_steps=50, guidance=1.0, count=None, seed=2024,
                         batch=32, device='cuda'):
    with np.load(work/'latents'/'val.npz') as d: val_labels = torch.from_numpy(d['labels'])
    count = count or len(val_labels)          # mismas clases y mismo número que la referencia
    files = sorted((work/'checkpoints').glob('ema_*.pt'))
    if steps: files = [f for f in files if int(f.stem[4:]) in steps]
    vae = load_vae(device); extractor = InceptionFeatures(work, device)
    reference = real_val_stats(work, extractor)
    results_path = work/'fid_curve.json'
    results = json.loads(results_path.read_text(encoding='utf-8')) if results_path.exists() else []
    model = None
    try:
        for file in files:
            state = torch.load(file, map_location=device, weights_only=True)
            cfg = state['config']
            model = LatentDiT(cfg['width'], cfg['depth'], cfg['heads'], classes=int(val_labels.max())+1).to(device)
            model.load_state_dict(state['ema']); model.eval()
            out = work/'samples'/f'{file.stem}_g{guidance}'; out.mkdir(parents=True, exist_ok=True)
            feats, stride = [], max(1, count//64)   # 64 muestras repartidas por todas las clases
            for start in range(0, count, batch):
                labels = val_labels[start:start+batch].to(device)
                z = sample_latents(model, labels, euler_steps, guidance, seed+start, device)
                images = []
                for k in range(0, len(z), 8):
                    with torch.inference_mode():
                        images.append(to_uint8(vae.decode(z[k:k+8]/vae.config.scaling_factor).sample))
                images = np.concatenate(images)
                feats.append(extractor(list(images)))
                for i, im in enumerate(images):
                    if (start+i) % stride == 0: Image.fromarray(im).save(out/f'{start+i:05d}.png')
            entry = {'step': state['step'], 'fid': fid_from_stats(gaussian_stats(feats), reference),
                     'n': count, 'euler_steps': euler_steps, 'guidance': guidance, 'seed': seed,
                     'extractor_sha256': extractor.weights_sha256}
            print(json.dumps(entry), flush=True)
            results.append(entry)
            results_path.write_text(json.dumps(results, indent=2), encoding='utf-8')
            del model, state; model = None
    finally:
        del vae, extractor, model
        if str(device).startswith('cuda'): torch.cuda.empty_cache()
    return results

def plot_results(work):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    results = json.loads((work/'fid_curve.json').read_text(encoding='utf-8'))
    rfid = json.loads((work/'rfid.json').read_text(encoding='utf-8'))['rfid']
    history = json.loads((work/'train_history.json').read_text(encoding='utf-8'))
    fig, (a, b) = plt.subplots(1, 2, figsize=(11, 4))
    a.plot(*zip(*history)); a.set_xlabel('paso'); a.set_ylabel('pérdida media'); a.set_yscale('log')
    for g in sorted({r['guidance'] for r in results}):
        pts = sorted((r['step'], r['fid']) for r in results if r['guidance'] == g)
        b.plot(*zip(*pts), marker='o', label=f'guía {g}')
    b.axhline(rfid, ls='--', c='gray', label='rFID del VAE'); b.set_xlabel('paso'); b.set_ylabel('FID'); b.legend()
    fig.tight_layout(); fig.savefig(work/'curvas.png', dpi=120); plt.close(fig)
    last = max(results, key=lambda r: r['step'])
    folder = work/'samples'/f"ema_{last['step']:07d}_g{last['guidance']}"
    tiles = [np.asarray(Image.open(p)) for p in sorted(folder.glob('*.png'))[:64]]
    if tiles:
        cols = 8; rows = (len(tiles)+cols-1)//cols
        grid = np.zeros((rows*256, cols*256, 3), np.uint8)
        for i, im in enumerate(tiles): grid[(i//cols)*256:(i//cols+1)*256, (i % cols)*256:(i % cols+1)*256] = im
        Image.fromarray(grid).save(work/'muestras.png')
    print('Guardados', work/'curvas.png', 'y', work/'muestras.png')

if os.environ.get('P07_L08_EVAL') == '1':
    evaluate_checkpoints(lab_dir(), **json.loads(os.environ.get('P07_L08_EVAL_OPTIONS', '{}')))
    plot_results(lab_dir())
else:
    print('Evaluación omitida: define P07_L08_WORK y P07_L08_EVAL=1 cuando haya checkpoints.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Without options, phase 4 evaluates all checkpoints without guidance and plots curvas.png (loss and FID versus step, with rFID as a reference line) and muestras.png (64 samples from the last evaluated checkpoint). To add the guided curve, rerun with P07_L08_EVAL_OPTIONS set to {"guidance": 1.5}; results accumulate in fid_curve.json. The steps key selects specific checkpoints, for example {"steps": [50000, 100000], "guidance": 1.5}. Choose in advance which checkpoints and guidance to evaluate: selecting the minimum of many evaluations introduces selection optimism.

What to expect

This lab was verified end to end with a short run: a set of 128 training and 32 validation images from two classes with the same folder structure as Imagenette, full DiT-S/2 for 30 steps at batch 8 (interrupted and resumed at step 20), and evaluation of two checkpoints with 32 samples, 4 Euler steps and guidance 1 and 1.5. That run checks that all four phases chain files, resumption and saves work, and the demonstration cell exactly reproduces the viewer errors; its FIDs mean nothing because the set was tiny and the model untrained. The previous section’s memory figures were measured separately with the real configuration. References for full training come from the sources:

  • rFID and PSNR. The VAE card reports rFID 4.70 and PSNR 24,5±3,724{,}5\pm3{,}7 dB on COCO with 5,000 images. Imagenette with 3,925 images will have a different rFID due to dataset and sample bias, but mean PSNR should be in that range. If rFID is high or PSNR very low, check preprocessing and scale before training.
  • Scale. Global standard deviation of scaled latents should be near 1, like the viewer photograph’s 0.90.
  • FID curve. It should fall with training and remain above rFID. As an order-of-magnitude reference, Peebles and Xie report FID-50K of 68.4 without guidance for DiT-S/2 on ImageNet at batch 256 and 400,000 steps; your experiment has different classes, dataset size, objective and nn, so figures are not directly comparable.
  • Guidance. With guidance 1.5 FID should fall relative to the unguided curve; in DiT-XL/2 guidance 1.5 changes FID-50K from 9.62 to 2.27. Guided samples resemble their class more closely and are less varied.
  • Samples. The 64 in muestras.png are spread across validation, which is ordered by class, so they cover all ten. Inspect them alongside the curve: a falling FID without visually better samples, or vice versa, calls for evaluation checks.

With so few images per class and hundreds of passes, the model may begin to memorize. The next lesson gives you a way to check: find the nearest training-set neighbor for each sample.

Exercises

NumericDiT patches
The latent has shape 4 × 32 × 32. If each token covers a 2 × 2 spatial patch, how many tokens are there?
NumericTime seen by the network without scaling
You train flow matching with Z_t = (1 − t)ε + tX, but forget to multiply latents by 0.18215, making the data c = 1/0.18215 times larger than intended. What time τ on the intended path corresponds to nominal time t = 0.5? Give τ to four decimal places.
CodeThe conditioned residual block
Implement ada_block(x, params, attn, mlp), where x has shape B×T×D and params contains six B×D arrays: attention shift, scale and gate, followed by those for the MLP. norm normalizes each token without affine parameters. Apply both residual branches using the supplied functions and corresponding gates. The first test checks identity with zero modulation.
import numpy as np

def norm(x):
  return (x-x.mean(axis=-1,keepdims=True))/np.sqrt(x.var(axis=-1,keepdims=True)+1e-5)

def ada_block(x, params, attn, mlp):
  # Sustituye esta identidad por las dos ramas moduladas.
  return x
Shift+Enter to run
Quiz
Clean latents are doubled while additive noise stays the same. What happens to the ratio of signal and noise variances?
Quiz
You want horizontal-flip augmentation without re-encoding every epoch. What do you do?
Quiz
Reconstruction of a separate dataset has high FID under a fixed protocol. What conclusion is justified?
ProofWhat moves in the second step
Prove: In a DiT with adaLN-Zero (all block and final-layer modulations zero, output projection W = 0) trained with AdamW without weight decay, only the output projection has changed after the first step. On the second step, block shifts, scales, attention and MLP have zero gradients, while block gates receive gradients.
0
After the first step, W ≠ 0 and all modulations remain zero, so each block is still the identity and gates are zero.

Step 1 of 3. Does the output of the final block receive a gradient?

Key idea
Latent diffusion divides the work: a frozen autoencoder removes imperceptible detail and DiT learns the distribution of its scaled latents. Latent scale is part of the noise schedule, augmentation must be precomputed by encoding each view, adaLN-Zero makes each block start as identity and wake through its gate, and all evaluation uses decoded images, with rFID as the quality reference targeted by training.