Module contents
Lesson 10 of 28Advanced 105 min

Conditional GANs, StyleGAN and the adversarial loss as a tool

Control generation and use the discriminator as a learned loss. Study conditional GANs and projection discriminators, pix2pix and CycleGAN image translation, style-based generation and truncation, and perceptual plus adversarial reconstruction losses.

After this lesson you can

  • Derive the projection discriminator from conditional density ratios.
  • Implement pix2pix with PatchGAN and compare L1, adversarial loss and their combination.
  • Implement StyleGAN2 modulated and demodulated convolution and verify its normalization.
  • Explain and measure truncation as a quality-diversity trade-off.
  • Train an autoencoder with perceptual and adversarial losses for reuse in latent diffusion.

Before you start

Generating under a condition

In an unconditional GAN we choose a noise sample and observe what appears. Translating an edge map to an image or generating a particular class requires a condition yy. It can be provided to both generator and discriminator: the former learns to produce an image compatible with yy and the latter compares real and generated pairs.

Label sampling matters: if yy frequencies differ between real and fake examples, the discriminator can exploit that difference without looking at the image. Mirza and Osindero introduce a conditional formulation; Miyato and Koyama study a projection discriminator.

A density ratio separating image and label

Assume discrete classes and positive densities at the point considered. With equal real and fake class priors and equally likely real/fake classes, the optimal discriminator logit is

log⁡pdata(x,y)pg(x,y)=log⁡pdata(x)pg(x)+log⁡pdata(y∣x)pg(y∣x).\log\frac{p_{\rm data}(x,y)}{p_g(x,y)} =\log\frac{p_{\rm data}(x)}{p_g(x)} +\log\frac{p_{\rm data}(y\mid x)}{p_g(y\mid x)}.

To understand projection, model both class probabilities with log-linear softmax over a representation h(x)h(x): p(y∣x)∝exp⁡(vy⊤h(x)+by)p(y\mid x)\propto\exp(v_y^\top h(x)+b_y) and pg(y∣x)∝exp⁡(uy⊤h(x)+cy)p_g(y\mid x)\propto\exp(u_y^\top h(x)+c_y). The difference of their logarithms contains (vy−uy)⊤h(x)+(by−cy)(v_y-u_y)^\top h(x)+(b_y-c_y) plus a difference of log-normalizers depending on xx, not the chosen class. If the marginal image ratio can also be expressed as a function of h(x)h(x), group terms independent of yy to obtain a(x,y)=ϕ(h(x))+ey⊤h(x)+by′a(x,y)=\phi(h(x))+e_y^\top h(x)+b_y'. Without that assumption, the class-independent term is generally a free function of xx.

This derivation motivates an architecture; it does not prove a finite network learns the exact ratio. If class priors differ, their ratio appears explicitly when factorizing via p(x∣y)p(y)p(x\mid y)p(y); in the decomposition above it is already included in conditionals p(y∣x)p(y\mid x). Projection lets compatibility and realism share features but does not guarantee classwise fidelity or coverage.

Translation with and without pairs

The L1 term encourages fidelity to the observed pair; the adversary penalizes learned discrepancies between real and generated patches. If several plausible outputs correspond to an ambiguous input, the deterministic solution minimizing coordinatewise L1 error is a coordinatewise conditional median. This can remove texture variations or produce smooth images, but L1 does not inevitably blur every problem. Adversarial loss can add plausible details that do not correspond to the particular image: compare fidelity too, and do not interpret sharpness as truth.

To calculate a receptive field, start with size r0=1r_0=1 and jump j0=1j_0=1. For a layer with kernel kk and stride ss, rℓ=rℓ−1+(k−1)jℓ−1r_{\ell}=r_{\ell-1}+(k-1)j_{\ell-1} and jℓ=s jℓ−1j_{\ell}=s\,j_{\ell-1}. Padding affects position and what part of the field falls outside the image, not the theoretical size of that recurrence. A PatchGAN map evaluates multiple overlapping fields; one output is not an independent judgment of the whole image.

InteractivePatchGAN receptive field

Each output cell can depend on a patch of the input. The control modifies a region of the synthetic image.

Input image and selected patch

Illustrative map: more orange means lower score

All convolutions use kernel size 4 and padding 1. There are 3 stride-2 layers followed by two stride-1 layers, with sizes 128 → 64 → 32 → 16 → 15 → 14. The nominal receptive field is 70 and output positions are spaced by 8. Blue shows existing pixels only, clipping padding at each layer. Its indices are x = [33, 103) and y = [33, 103), measured from the top left. Training-time batch norm or instance norm can introduce global spatial dependencies beyond this convolutional graph.

The illustrative score uses mean absolute error e from the original synthetic image and displays σ(2 − 20e). It falls when the patch contains perturbations, dropping below 0.5 once e exceeds 0.1. This explicitly defined score illustrates locality. A trained PatchGAN can learn a different rule.

3
1.00
7
7
Nominal receptive field
70 × 70
Actual image area
70 × 70
Output map
14 × 14
Mean patch difference
0.1724
Illustrative model score
0.1903
Change the architecture and inspect which input region affects one output. The figure explains how the decision map arises.

When pairs do not exist, CycleGAN learns G:X→YG:X\to Y and F:Y→XF:Y\to X with adversarial losses per domain and consistency such as Ex∥F(G(x))−x∥1\E_x\|F(G(x))-x\|_1. Approximately returning to the starting point does not identify a unique semantic translation: many bijections and hidden encodings satisfy the cycle. Inspect correspondence, artifacts and robustness, not cycle loss alone.

Styles and scales

StyleGAN2 formulates weight modulation and demodulation. For kernel Wo,i,u,vW_{o,i,u,v} and style sis_i, first Wo,i,u,v′=siWo,i,u,vW'_{o,i,u,v}=s_iW_{o,i,u,v} and then

W~o,i,u,v=Wo,i,u,v′∑i,u,v(Wo,i,u,v′)2+ϵ.\widetilde W_{o,i,u,v}=\frac{W'_{o,i,u,v}}{\sqrt{\sum_{i,u,v}(W'_{o,i,u,v})^2+\epsilon}}.

If inputs to a receptive field have zero mean, unit variance and are uncorrelated, linear output variance for a channel is S/(S+ϵ)S/(S+\epsilon), where S=∑(W′)2S=\sum(W')^2. It approaches one if S≫ϵS\gg\epsilon. Correlations, padding, nonlinearities and added noise can change that conclusion; demodulation does not exactly normalize every activation in a real network.

InteractiveMixing styles by layer

These prerecorded StyleGAN2-ADA outputs are for the CIFAR-10 cat class. They are enlarged from 32×32 pixels.

Source A: seed 17
Source A: seed 17
Mixture: cut 4
Mixture: cut 4
Source B: seed 29
Source B: seed 29

W inputs in synthesis order, indices 0 to 7

0
A
1
A
2
A
3
A
4
B
5
B
6
B
7
B

The mixture takes the first 4 W inputs from A and the rest from B. Cut 0 reproduces B, and cut 8 reproduces A. Three seeds and five cuts were precomputed with truncation ψ = 1 and fixed internal noise. This implementation shares some W inputs across operations in neighboring blocks, so a cut can fall across a resolution boundary. The relationship between the index and an attribute depends on the model and inputs.

Model and code: NVIDIA StyleGAN2-ADA, CIFAR-10 checkpoint. Research and noncommercial evaluation use under the NVIDIA license. A copy is included with the widget.

Source A
Source B
4
Inputs from A
4 / 8
Inputs from B
4 / 8
Compare images from the model and protocol specified in the figure; distribution across scales is an observation, not a universal rule.

Contraction reduces variation in the modified style space, but does not guarantee improved quality for every image or a monotonic decline in every metric for every model. Report truncated layers and the value of ψ\psi. It resembles other fidelity-diversity controls, such as some diffusion guidance, but operations and distributions differ: contraction in WW is not classifier-free guidance.

InteractiveThe cost of truncation

StyleGAN2-ADA pretrained on CIFAR-10: cat class, ψ = 0.50

Image generated with seed 17 and psi 0.50Seed 17
Image generated with seed 29 and psi 0.50Seed 29
Image generated with seed 41 and psi 0.50Seed 41

Images come from the official checkpoint NVIDIA cifar10.pkl. These are 32×32 outputs shown enlarged, with fixed synthesis noise and the same seeds as ψ changes. Its code license limits use to research and noncommercial evaluation. The 2D mixture and metrics come from a separate experiment.

  • Reference
  • Truncated samples
  • Component centers

The horizontal axis is ψ and the vertical axis is the fraction of samples, from 0 to 1.

  • Proximity precision
  • Proximity coverage

The explicit model mixes three isotropic 2D normals with standard deviation 0.35 and weights 0.55, 0.30, 0.15. The 384 reference samples and 384 initial samples use separate seeds 191001 and 191002. Each transformed sample satisfies w′ = c + ψ(w − c), with c equal to the theoretical global mean (−0.43, −0.58) or the center of its known component.

Precision is the fraction of transformed samples within distance ≤ 0.16 of some reference. Coverage is the fraction of references that close to some transformed sample. These fixed-radius proximity metrics apply in this plane. Changing seed, radius, or center can change both curves.

The global mean reproduces the affine truncation used by StyleGAN in W space on this 2D mixture. Per-component mode knows the label of each sample and shrinks samples toward different centers. Precision and coverage can respond differently for other models or metrics.

Truncation center
0.50
Proximity precision99.7 %
Proximity coverage75.8 %
Comparison radius0.16
Samples per set384
Explore the model and metrics defined in the figure; do not treat a trend as a universal guarantee.

A loss that learns to look

Perceptual and adversarial loss combines terms answering different questions. L2 measures pixelwise differences; LPIPS compares features of a network with calibration learned from perceptual judgments, under the protocol of Zhang and colleagues. A PatchGAN learns to distinguish patches of reconstructions and data. Neither alone guarantees generated content is faithful to the input.

VQGAN combines perceptual and adversarial reconstruction with a quantized autoencoder. Convincing texture can be wrong for the original image, especially with excessive adversarial weight. For an autoencoder intended for latent diffusion, save its checkpoint and document architecture, input scaling, latent dimensions and selection criterion; the later stage must use that same contract. GANs also appear in super-resolution and systems reducing generation steps, but costs and guarantees depend on the method.

Lab: modulation and demodulation

Implement a valid convolution without bias or padding, with a different modulated kernel per example. Styles and weights are fixed, and each input patch is an independent standard normal sample. Compare empirical variance with prediction S/(S+ϵ)S/(S+\epsilon) for each output channel. In real images, overlapping inputs and learned features may be correlated: this checks assumptions of a controlled case, not variance throughout StyleGAN.

[ ]Modulated convolution from scratchBrowser
import numpy as np

def modulated_conv_numpy(x, weight, style, demodulate=True, eps=1e-8):
    batch, channels, height, width = x.shape
    outputs, inputs, kh, kw = weight.shape
    assert inputs == channels and style.shape == (batch, channels)
    scaled = weight[None] * style[:, None, :, None, None]
    if demodulate:
        norm = np.sqrt(np.sum(scaled**2, axis=(2, 3, 4), keepdims=True) + eps)
        scaled = scaled / norm
    result = np.empty((batch, outputs, height-kh+1, width-kw+1))
    for row in range(height-kh+1):
        for col in range(width-kw+1):
            patch = x[:, :, row:row+kh, col:col+kw]
            result[:, :, row, col] = np.einsum('bijk,boijk->bo', patch, scaled)
    return result

rng = np.random.default_rng(1010)
weight = rng.normal(size=(4, 3, 3, 3))
fixed_style = np.array([0.3, 1.4, 0.7])
batch = 4096
styles = np.broadcast_to(fixed_style, (batch, 3))
x = rng.normal(size=(batch, 3, 3, 3))
raw = modulated_conv_numpy(x, weight, styles, demodulate=False)[:, :, 0, 0]
normalized = modulated_conv_numpy(x, weight, styles, demodulate=True)[:, :, 0, 0]
energy = np.sum((weight * fixed_style[None, :, None, None])**2, axis=(1, 2, 3))
print('Varianza teórica sin demodulación:', np.round(energy, 3))
print('Varianza empírica sin demodulación:', np.round(raw.var(axis=0), 3))
print('Varianza teórica demodulada:', np.round(energy / (energy + 1e-8), 3))
print('Varianza empírica demodulada:', np.round(normalized.var(axis=0), 3))

The difference between the last two rows is Monte Carlo error. It may increase with fewer patches; changing input correlation also changes theoretical variance.

Local lab: pix2pix for edges and images

Fashion-MNIST offers continuous-intensity images; classes are not used in training. Construct input by applying a Sobel filter and fixed threshold 0.75 to each image; the target is the original image. U-Net has skip connections and the discriminator receives the pair (bordes, imagen), edges and image, with a 7×7 logit map. The interior receptive field of each logit is 26×26 pixels, with padding at the edges.

Compare three variants: L1 alone, non-saturating adversarial loss alone, and their sum with L1 weight 10 and adversarial weight 1. All begin with the same initialization, data order and number of generator and discriminator updates. The discriminator is trained even in the L1-only variant, although its loss does not influence G updates; this maintains equal step counts for both networks. One seed cannot separate randomness sensitivity from objective differences. Training losses alone do not measure perceptual quality.

Evaluation uses only images from the official test split, separate from training. Per-pixel L1 is reported and the same four inputs and targets are shown for all three models; a pixel metric alone does not establish visual quality or semantic fidelity. Adversarial output can invent details and a short test proves no method superior.

Install PyTorch, torchvision and matplotlib. By default all training images, 2048 test images and 15 epochs per variant are used. ORYON_QUICK=1 uses 128 training images, 64 test images, one epoch and fewer channels to check the workflow. ORYON_FASHION_ROOT points to the directory containing FashionMNIST; if unset, ORYON_DATA_ROOT or ./data is used.

[ ]Pix2pix: edges to Fashion-MNISTLocal GPU
import os
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms
import matplotlib.pyplot as plt

quick = os.environ.get('ORYON_QUICK') == '1'
root = Path(os.environ.get('ORYON_FASHION_ROOT', os.environ.get('ORYON_DATA_ROOT', './data')))
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(1)
width = 12 if quick else 32
epochs = 1 if quick else 15
batch_size = 16 if quick else 64
seed = 1010
data_train = datasets.FashionMNIST(root, train=True, download=True, transform=transforms.ToTensor())
data_test = datasets.FashionMNIST(root, train=False, download=True, transform=transforms.ToTensor())
train = Subset(data_train, range(128)) if quick else data_train
test = Subset(data_test, range(64 if quick else 2048))
test_loader = DataLoader(test, batch_size=batch_size, shuffle=False, num_workers=0)

def edges(x):
    # Sobel fijo sobre cada imagen, seguido de un umbral explícito.
    kernel = x.new_tensor([[-1., 0., 1.], [-2., 0., 2.], [-1., 0., 1.]])
    gx = F.conv2d(x, kernel[None, None], padding=1)
    gy = F.conv2d(x, kernel.T[None, None], padding=1)
    return (torch.sqrt(gx.square() + gy.square()) > 0.75).to(x.dtype)

assert torch.count_nonzero(edges(torch.zeros(2, 1, 28, 28))) == 0

class UNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.down1 = nn.Conv2d(1, width, 4, 2, 1)
        self.down2 = nn.Conv2d(width, 2 * width, 4, 2, 1)
        self.middle = nn.Conv2d(2 * width, 2 * width, 3, padding=1)
        self.up1 = nn.ConvTranspose2d(2 * width, width, 4, 2, 1)
        self.up2 = nn.ConvTranspose2d(2 * width, width, 4, 2, 1)
        self.output = nn.Conv2d(width, 1, 3, padding=1)

    def forward(self, x):
        first = F.leaky_relu(self.down1(x), 0.2)
        second = F.leaky_relu(self.down2(first), 0.2)
        hidden = F.relu(self.middle(second))
        up = F.relu(self.up1(hidden))
        up = F.relu(self.up2(torch.cat((up, first), dim=1)))
        return torch.sigmoid(self.output(up))

class PatchDiscriminator(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(
            nn.Conv2d(2, width, 4, 2, 1), nn.LeakyReLU(0.2),
            nn.Conv2d(width, 2 * width, 4, 2, 1), nn.LeakyReLU(0.2),
            nn.Conv2d(2 * width, 2 * width, 3, padding=1), nn.LeakyReLU(0.2),
            nn.Conv2d(2 * width, 1, 3, padding=1))

    def forward(self, condition, image):
        return self.net(torch.cat((condition, image), dim=1))

@torch.no_grad()
def evaluate(model):
    model.eval()
    total_abs = count = 0
    for x, _ in test_loader:
        x = x.to(device)
        prediction = model(edges(x))
        total_abs += (prediction - x).abs().sum().item()
        count += x.numel()
    return total_abs / count

def run(mode):
    torch.manual_seed(seed)
    if device.type == 'cuda':
        torch.cuda.manual_seed_all(seed)
    generator = UNet().to(device)
    discriminator = PatchDiscriminator().to(device)
    g_optimizer = torch.optim.Adam(generator.parameters(), lr=0.0002, betas=(0.5, 0.999))
    d_optimizer = torch.optim.Adam(discriminator.parameters(), lr=0.0002, betas=(0.5, 0.999))
    order = torch.Generator().manual_seed(seed + 1)
    loader = DataLoader(train, batch_size=batch_size, shuffle=True, num_workers=0, generator=order)
    recon_weight, adversarial_weight = {'l1': (10.0, 0.0), 'adversaria': (0.0, 1.0), 'combinada': (10.0, 1.0)}[mode]
    for epoch in range(epochs):
        generator.train(); discriminator.train()
        seen = 0
        total_l1 = total_adv = total_d = 0.0
        for target, _ in loader:
            target = target.to(device)
            condition = edges(target)
            fake = generator(condition)
            assert fake.shape == target.shape
            d_optimizer.zero_grad(set_to_none=True)
            real_logits = discriminator(condition, target)
            fake_logits = discriminator(condition, fake.detach())
            d_loss = F.softplus(-real_logits).mean() + F.softplus(fake_logits).mean()
            d_loss.backward()
            d_optimizer.step()
            for parameter in discriminator.parameters():
                parameter.requires_grad_(False)
            g_optimizer.zero_grad(set_to_none=True)
            generated_logits = discriminator(condition, fake)
            l1 = F.l1_loss(fake, target)
            adversarial = F.softplus(-generated_logits).mean()
            loss = recon_weight * l1 + adversarial_weight * adversarial
            loss.backward()
            g_optimizer.step()
            for parameter in discriminator.parameters():
                parameter.requires_grad_(True)
            n = len(target)
            total_l1 += l1.item() * n
            total_adv += adversarial.item() * n
            total_d += d_loss.item() * n
            seen += n
        heldout_l1 = evaluate(generator)
        print(mode, 'época', epoch + 1, 'L1 train:', round(total_l1 / seen, 4),
              'adversaria train:', round(total_adv / seen, 4),
              'D train:', round(total_d / seen, 4), 'L1 test:', round(heldout_l1, 4), flush=True)
    generator.eval()
    with torch.no_grad():
        reference = next(iter(test_loader))[0][:4].to(device)
        condition = edges(reference)
        examples = generator(condition).cpu()
        reference, condition = reference.cpu(), condition.cpu()
    del generator, discriminator, g_optimizer, d_optimizer
    del target, fake, loss, d_loss, l1, adversarial, real_logits, fake_logits, generated_logits, parameter
    if device.type == 'cuda':
        torch.cuda.empty_cache()
    return reference, condition, examples, heldout_l1

print('Dispositivo:', device, '| prueba corta:', quick, '| train/test:', len(train), len(test), flush=True)
results = {mode: run(mode) for mode in ('l1', 'adversaria', 'combinada')}
fig, axes = plt.subplots(5, 4, figsize=(8, 10))
names = ['Bordes', 'Objetivo', 'Solo L1', 'Solo adversaria', 'L1 + adversaria']
rows = [results['l1'][1], results['l1'][0], results['l1'][2], results['adversaria'][2], results['combinada'][2]]
for row, images in enumerate(rows):
    for col, image in enumerate(images):
        axes[row, col].imshow(image[0], cmap='gray', vmin=0, vmax=1)
        axes[row, col].axis('off')
    axes[row, 0].set_title(names[row])
fig.tight_layout()
plt.show()
plt.close(fig)
print('L1 reservada por píxel:', {mode: round(results[mode][3], 4) for mode in results}, flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local lab: perceptual and adversarial reconstruction

Install torch, torchvision and lpips==0.1.4. The first run downloads ImageNet SqueezeNet weights and uses calibrated weights included in LPIPS. This is real LPIPS distance with the squeeze network, not a random network. Use aligned CelebA images and its official list_eval_partition.txt: set ORYON_CELEBA_DIR to the flat img_align_celeba folder and ORYON_CELEBA_SPLITS to that file. The training split is respected and the first 1024 validation images are reserved for checkpoint selection. CelebA terms restrict use and redistribution; consult them when downloading.

Train three autoencoders with identical architecture and initialization: MSE, MSE + 0.1 LPIPS and MSE + 0.1 LPIPS + 0.01 adversarial loss. The PatchGAN discriminator is not conditioned on the original image. To prevent early dominance it activates after five epochs; the short trial activates it immediately to test that branch. Selection uses the same validation MSE + 0.1 LPIPS criterion for all variants and epochs; best_autoencoder.pt contains winning weights, architecture, normalization, variant and epoch. It is a deterministic autoencoder with continuous 8×8×8 latent, not a VQGAN or pretrained VAE. Diffusion must load and freeze it, measure latent scale on training, and apply that same scale when encoding and decoding; no universal scale is assumed.

By default train 20 epochs per variant. ORYON_QUICK=1 uses little data and a smaller network only to check functionality. If ORYON_DEBUG_CIFAR_PARQUET also points to a folder with CIFAR-10 train-*.parquet and test-*.parquet, the test uses 32 training and 16 test images resized to 64×64 instead of CelebA; this option works only with ORYON_QUICK=1 and produces no diffusion checkpoint. MSE, LPIPS and Laplacian variance are recorded alongside identical validation grids. Higher edge variance does not prove greater fidelity: it can indicate artifacts or invented texture. The selection score does not replace independent perceptual evaluation.

[ ]Compare three perceptual autoencodersLocal GPU
import csv
import io
import os
from pathlib import Path

import lpips
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from torchvision.utils import save_image

quick = os.environ.get('ORYON_QUICK') == '1'
debug_dir = os.environ.get('ORYON_DEBUG_CIFAR_PARQUET')
if debug_dir and not quick:
    raise ValueError('ORYON_DEBUG_CIFAR_PARQUET solo se usa con ORYON_QUICK=1')
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(2)
width = 8 if quick else 48
epochs = 1 if quick else 20
batch_size = 4 if quick else 32
warmup = 0 if quick else 5
latent_channels = 8
output = Path(os.environ.get('ORYON_OUTPUT_DIR', './perceptual-autoencoder'))
output.mkdir(parents=True, exist_ok=True)
transform = transforms.Compose([
    transforms.Resize((64, 64)), transforms.ToTensor(),
    transforms.Normalize((0.5,) * 3, (0.5,) * 3),
])

class CelebAImages(Dataset):
    def __init__(self, directory, partition_file, split, limit=None):
        folder = Path(directory)
        rows = Path(partition_file).read_text(encoding='utf-8').splitlines()
        files = [folder / name for name, part in (row.split() for row in rows) if part == str(split)]
        self.files = files[:limit] if limit else files
        if not self.files or not all(path.is_file() for path in self.files):
            raise FileNotFoundError('Faltan imágenes de la partición oficial de CelebA')
        self.crop = transforms.CenterCrop(178)
    def __len__(self):
        return len(self.files)
    def __getitem__(self, index):
        with Image.open(self.files[index]) as image:
            return transform(self.crop(image.convert('RGB')))

class DebugCIFAR(Dataset):
    def __init__(self, folder, split, limit):
        import pyarrow.parquet as pq
        files = sorted(Path(folder).glob(f'{split}-*.parquet'))
        if not files:
            raise FileNotFoundError(f'No se encontró el parquet {split}')
        self.rows = []
        for file in files:
            for batch in pq.ParquetFile(file).iter_batches(batch_size=limit, columns=['img']):
                self.rows.extend(batch.slice(0, limit - len(self.rows)).to_pylist())
                if len(self.rows) >= limit:
                    break
            if len(self.rows) >= limit:
                break
    def __len__(self):
        return len(self.rows)
    def __getitem__(self, index):
        with Image.open(io.BytesIO(self.rows[index]['img']['bytes'])) as image:
            return transform(image.convert('RGB'))

if debug_dir:
    train_data = DebugCIFAR(debug_dir, 'train', 32)
    val_data = DebugCIFAR(debug_dir, 'test', 16)
else:
    folder = os.environ.get('ORYON_CELEBA_DIR')
    splits = os.environ.get('ORYON_CELEBA_SPLITS')
    if not folder or not splits:
        raise ValueError('Define ORYON_CELEBA_DIR y ORYON_CELEBA_SPLITS')
    train_data = CelebAImages(folder, splits, 0, 32 if quick else None)
    val_data = CelebAImages(folder, splits, 1, 16 if quick else 1024)
if len(train_data) < batch_size or not len(val_data):
    raise ValueError('No hay suficientes imágenes para entrenar y validar')
val_loader = DataLoader(val_data, batch_size=batch_size, shuffle=False, num_workers=0)

class Autoencoder(nn.Module):
    def __init__(self, base=width, z_channels=latent_channels):
        super().__init__()
        self.encoder = nn.Sequential(
            nn.Conv2d(3, base, 4, 2, 1), nn.GroupNorm(8, base), nn.SiLU(),
            nn.Conv2d(base, base * 2, 4, 2, 1), nn.GroupNorm(8, base * 2), nn.SiLU(),
            nn.Conv2d(base * 2, base * 4, 4, 2, 1), nn.GroupNorm(8, base * 4), nn.SiLU(),
            nn.Conv2d(base * 4, z_channels, 3, 1, 1),
        )
        self.decoder = nn.Sequential(
            nn.Conv2d(z_channels, base * 4, 3, 1, 1), nn.GroupNorm(8, base * 4), nn.SiLU(),
            nn.ConvTranspose2d(base * 4, base * 2, 4, 2, 1), nn.GroupNorm(8, base * 2), nn.SiLU(),
            nn.ConvTranspose2d(base * 2, base, 4, 2, 1), nn.GroupNorm(8, base), nn.SiLU(),
            nn.ConvTranspose2d(base, 3, 4, 2, 1), nn.Tanh(),
        )
    def forward(self, x):
        return self.decoder(self.encoder(x))

class PatchDiscriminator(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(
            nn.Conv2d(3, width, 4, 2, 1), nn.LeakyReLU(0.2),
            nn.Conv2d(width, width * 2, 4, 2, 1), nn.LeakyReLU(0.2),
            nn.Conv2d(width * 2, width * 4, 4, 2, 1), nn.LeakyReLU(0.2),
            nn.Conv2d(width * 4, 1, 4, 1, 1),
        )
    def forward(self, x):
        return self.net(x)

def sharpness(x):
    # Varianza espacial de la respuesta al laplaciano, media de canales e imágenes.
    kernel = x.new_tensor([[0, 1, 0], [1, -4, 1], [0, 1, 0]]).reshape(1, 1, 3, 3)
    kernel = kernel.expand(x.shape[1], 1, 3, 3)
    edges = F.conv2d(x, kernel, padding=1, groups=x.shape[1])
    return edges.flatten(2).var(dim=2, unbiased=False).mean()

perceptual = lpips.LPIPS(net='squeeze', verbose=False).to(device).eval()
for parameter in perceptual.parameters():
    parameter.requires_grad_(False)
del parameter
best = float('inf')
history = []
for mode in ('mse', 'mse_lpips', 'mse_lpips_patch'):
    torch.manual_seed(91)
    if device.type == 'cuda':
        torch.cuda.manual_seed_all(91)
    model, disc = Autoencoder().to(device), PatchDiscriminator().to(device)
    opt_model = torch.optim.Adam(model.parameters(), lr=0.0002, betas=(0.5, 0.999))
    opt_disc = torch.optim.Adam(disc.parameters(), lr=0.0002, betas=(0.5, 0.999))
    loader = DataLoader(train_data, batch_size=batch_size, shuffle=True, drop_last=True,
                        num_workers=0, generator=torch.Generator().manual_seed(92))
    mode_dir = output / mode
    mode_dir.mkdir(parents=True, exist_ok=True)
    for epoch in range(1, epochs + 1):
        model.train()
        disc.train()
        adversarial = mode == 'mse_lpips_patch' and epoch > warmup
        for real in loader:
            real = real.to(device)
            reconstruction = model(real)
            if adversarial:
                opt_disc.zero_grad(set_to_none=True)
                d_loss = (F.softplus(-disc(real)).mean() +
                          F.softplus(disc(reconstruction.detach())).mean())
                d_loss.backward()
                opt_disc.step()
            opt_model.zero_grad(set_to_none=True)
            loss = F.mse_loss(reconstruction, real)
            if mode != 'mse':
                loss = loss + 0.1 * perceptual(reconstruction, real).mean()
            if adversarial:
                for parameter in disc.parameters():
                    parameter.requires_grad_(False)
                loss = loss + 0.01 * F.softplus(-disc(reconstruction)).mean()
            loss.backward()
            opt_model.step()
            if adversarial:
                for parameter in disc.parameters():
                    parameter.requires_grad_(True)
        model.eval()
        totals = torch.zeros(4, device=device)
        count = 0
        with torch.no_grad():
            for batch_index, real in enumerate(val_loader):
                real = real.to(device)
                reconstruction = model(real)
                n = real.shape[0]
                totals += n * torch.stack((F.mse_loss(reconstruction, real),
                    perceptual(reconstruction, real).mean(), sharpness(real), sharpness(reconstruction)))
                count += n
                if batch_index == 0:
                    pairs = torch.cat((real, reconstruction), dim=0)
                    save_image(((pairs + 1) / 2).clamp(0, 1),
                               mode_dir / f'validacion-{epoch:03d}.png', nrow=n)
        mse, distance, sharp_real, sharp_rec = (totals / count).cpu().tolist()
        score = mse + 0.1 * distance
        history.append([mode, epoch, mse, distance, sharp_real, sharp_rec, score])
        print(f'{mode} época {epoch:02d}: MSE={mse:.5f} LPIPS={distance:.5f} '
              f'laplaciano real={sharp_real:.5f} reconstrucción={sharp_rec:.5f} score={score:.5f}')
        if score < best:
            best = score
            torch.save({'state_dict': model.state_dict(), 'base': width,
                        'latent_channels': latent_channels, 'image_size': 64,
                        'input_range': [-1, 1], 'mode': mode, 'epoch': epoch,
                        'selection_score': score, 'debug': quick,
                        'selection': 'validation MSE + 0.1 LPIPS squeeze'},
                       output / ('debug_autoencoder.pt' if quick else 'best_autoencoder.pt'))
    del real, reconstruction, totals, pairs, loss, model, disc, opt_model, opt_disc
    if mode == 'mse_lpips_patch' and adversarial:
        del d_loss, parameter
    if device.type == 'cuda':
        torch.cuda.empty_cache()

with (output / 'metricas.csv').open('w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(['variante', 'epoca', 'mse_val', 'lpips_val', 'lap_real', 'lap_reconstruccion', 'score'])
    writer.writerows(history)
print('Resultados:', output.resolve())
del perceptual
if device.type == 'cuda':
    torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofSeparating the condition
Prove: Starting from the joint-distribution ratio, derive the projection form under log-linear softmax class classifiers.
0
Assume positive densities and a shared representation h(x).

Step 1 of 3. How does the joint ratio separate?

NumericPatch size
Five layers have kernel 4; the first three use stride 2 and the last two stride 1. What is one output’s theoretical receptive field in pixels per side?
CodeGrouped convolutions
Implement modulated_conv2d(x, weight, style, demodulate=True, eps=1e-8) using torch.nn.functional.conv2d and groups=B. x has shape (B, Cin, H, W), weight (Cout, Cin, K, K) and style (B, Cin). Each example uses its own kernel; add no bias or padding. Preserve gradients to x, weight and style.
import torch
import torch.nn.functional as F

def modulated_conv2d(x, weight, style, demodulate=True, eps=1e-8):
  pass
Shift+Enter to run
QuizAre pairs available?
You have aligned edge maps and corresponding photos for one task, and two unpaired collections for another. Which starting point fits best?
QuizAmbiguous reconstruction
Several plausible textures correspond to one outline and a deterministic predictor is trained with per-pixel L1. Which conclusion is defensible?
Key idea

Conditioning a GAN changes the distributions being compared. Styles control a specific architecture, truncation changes its input distribution, and perceptual or adversarial loss must be evaluated alongside fidelity to data.