Module contents
Lesson 9 of 28Advanced 115 min

GAN dynamics and stabilization: Wasserstein, penalties and spectral normalization

Study GAN training dynamics through the Dirac-GAN linearization, generalize objectives using f-divergences, derive WGAN from transport duality, and examine gradient penalties, spectral normalization, R1 and modern training recipes.

After this lesson you can

  • Linearize Dirac-GAN, calculate Jacobian eigenvalues and explain descent-ascent cycles.
  • Derive WGAN from Kantorovich-Rubinstein duality and derive the WGAN-GP gradient penalty.
  • Implement R1, WGAN-GP and spectral normalization and compare stability.
  • Formulate a GAN for an arbitrary f-divergence using its Fenchel dual.
  • Apply and justify standard recipes including TTUR, hinge loss and generator EMA.

Before you start

An optimization problem with two clocks

In a GAN, improving the discriminator changes the problem solved by the generator. Two apparently reasonable losses can therefore produce a trajectory that rotates around an equilibrium or moves away. Separate three questions: what the gradient field does near equilibrium, which distance is being optimized and what each regularizer actually constrains.

The continuous field descending generator loss and ascending discriminator value is

v(θ,ψ)=(ψσ(−ψθ)−θσ(ψθ)),J(0,0)=(01/2−1/20).v(\theta,\psi)=\begin{pmatrix}\psi\sigma(-\psi\theta)\\-\theta\sigma(\psi\theta)\end{pmatrix}, \qquad J(0,0)=\begin{pmatrix}0&1/2\\-1/2&0\end{pmatrix}.

Its eigenvalues are ±i/2\pm i/2: the continuous linearization rotates without damping. This does not prove nonlinear dynamics have exact circular orbits; Mescheder, Geiger and Nowozin specifically analyze the difference for the non-saturating objective. With simultaneous Euler step hh, linear-map eigenvalues are 1±ih/21\pm ih/2 and their modulus is 1+h2/4>1\sqrt{1+h^2/4}>1: near the origin this linear discretization amplifies the orbit.

Add a penalty R1=γψ2/2R_1=\gamma\psi^2/2 to the discriminator objective. Its field component gains −γψ-\gamma\psi. Eigenvalues of the new matrix are (−γ±γ2−1)/2(-\gamma\pm\sqrt{\gamma^2-1})/2, with a complex root when 0<γ<10<\gamma<1. For every γ>0\gamma>0 they have negative real parts; a sufficiently small discrete step is needed for map stability too. Extragradient first evaluates a provisional step and uses that field to update from the original point: in the linear model it can damp rotation, but stability depends on step size.

InteractiveDirac-GAN phase portrait
  • Continuous field direction
  • Discrete iterations
  • Drag the starting point
  • Selected iteration
Horizontal axis: θ. Vertical axis: ψ.

The real Dirac mass is at 0 and the generated mass at θ, with linear logit ψx and a non-saturating generator. In the first four modes the field is (ψσ(−θψ), −θσ(θψ) − γψ), with γ = 0 except in R1. Gray arrows show the normalized local direction. The blue line joins the actual iterates. Alternation updates ψ before θ, while extragradient evaluates the field at a provisional point.

The eigenvalues belong to the continuous field Jacobian at (0, 0). The spectral radius belongs to the discrete-step Jacobian there. A radius below one gives local linear stability and a radius above one gives local instability. A radius of one leaves the nonlinear behavior undecided. The trajectories use the full equations. The curve can leave the visible plane.

Model and analysis: Mescheder, Geiger, and Nowozin, Which Training Methods for GANs do actually Converge?, Sections 2 and 3 and Appendix C. The figure shows a finite trajectory under the stated convention.

0.30
100
Iteration100
Current θ, ψ(−0.255, −0.777)
Distance to the origin0.818
Field eigenvalue 10.000 + 0.500i
Field eigenvalue 20.000 − 0.500i
Update spectral radius1.0112
Compare the field, update methods and eigenvalues under the conventions shown in the figure.

Not every regularizer centers the same value. For a linear Wasserstein critic, GP is proportional to (∣ψ∣−1)2(|\psi|-1)^2, which is not differentiable at ψ=0\psi=0. The ordinary Jacobian does not exist there. In the Dirac counterexample, WGAN and WGAN-GP with a fixed number of critic updates do not always converge; Mescheder and colleagues do not claim GP fails in every application.

Changing divergence

Fenchel inequality f(u)≥ut−f∗(t)f(u)\geq ut-f^*(t) gives the pointwise bound; integrating with respect to qq yields the expression. A neural-network family TT offers only a supremum over that family, and the domain of f∗f^* must be respected. A sufficiently expressive witness and suitable conditions attain the full representation. Nowozin, Cseke and Tomioka formulate this for different divergences: changing ff changes the objective and sensitivity to regions of different mass, without itself guaranteeing stable training.

From transport to a Wasserstein critic

For point masses δ0\delta_0 and δθ\delta_\theta, W1=∣θ∣W_1=|\theta|: distance distinguishes displacement even without support overlap. Transport duality explains why the critic provides this objective. The critic is not a probability and needs no sigmoid. An approximately trained critic’s gap is not automatically the true distance; network restrictions, imperfect regularization or incomplete optimization can separate it from the supremum.

The original WGAN by Arjovsky, Chintala and Bottou clips weights. This keeps parameters bounded but does not precisely impose a Lipschitz constant of one on the whole network. An interval that is too narrow can limit capacity; a wide one can constrain weakly. Gulrajani and colleagues study these problems and propose a different penalty.

InteractiveClassifier and critic

Two 2D normals have the same covariance 0.7² I and means (0, 0) and (d, 0). The blue background shows the real-class probability D*(x, y).

  • Real
  • Fake
  • Per-sample descent

The plot uses 24 pairs with the same Gaussian noise and seed 1909. Each arrow is 0.16 times the negative spatial gradient of the loss. For balanced classes D* = σ[d(d/2−x)/0.7²]. The gradient norm is D*d/0.7² for saturating loss and (1−D*)d/0.7² for non-saturating loss. For W₁, f = −x is an optimal 1-Lipschitz critic of these translated Gaussians and W₁ = d. The example is analytical, and backgrounds use different scales for D* and f. The arrows hold the discriminator or critic fixed and represent sample gradients.

2.4
Field and generator objective
D* at the fake mean
0.00279
Gradient norm at the fake mean
0.01368
Exact W₁
2.40
Compare fields of the explicit model in the figure. An illustrative ramp does not prove a trained network attained the optimal critic.

Gradients at different points

GP intuition comes from an optimal 1-Lipschitz potential saturating the transport inequality for pairs in an optimal coupling. If f(x)−f(y)=∥x−y∥f(x)-f(y)=\|x-y\| with x≠yx\ne y, Lipschitz continuity preserves equality at each interior point of the segment. Where ff is differentiable, its derivative in the segment direction is one; because its norm cannot exceed one, ∥∇f∥=1\|\nabla f\|=1. This concerns pairs from an optimal coupling, not arbitrary independent pairs. GP samples independent pairs and penalizes softly; it does not by itself certify a global Lipschitz constraint.

R1 seeks a different property: a discriminator gradient centered at zero on real data. The local guarantee of Mescheder and colleagues requires the regularity, equilibrium-structure and sufficiently small-step assumptions of their theorems; it does not promise global convergence for an arbitrary network. Do not use BatchNorm in a critic whose penalty is calculated per sample: one example’s output would depend on others, and the sum gradient would no longer represent an independent individual function. PyTorch requires create_graph=True so the gradient penalty can update critic parameters.

Spectral control and recipes

Power iteration alternates u←Wv/∥Wv∥u\leftarrow Wv/\|Wv\| and v←W⊤u/∥W⊤u∥v\leftarrow W^\top u/\|W^\top u\|; it estimates the largest singular value when initialization has a component in its subspace and spectral separation is appropriate. If the estimate understates the norm, dividing by it does not certify an exact bound of one. Miyato and colleagues reuse estimated vectors across updates to reduce cost. For convolution, the norm of the flattened-kernel matrix is not necessarily that of the full spatial operator; do not confuse them.

InteractivePower iteration and spectral norm
  • Circle and its image
  • v and its image
Iteration 0 / 25

Each step computes u = Wv/‖Wv‖ followed by v = Wᵀu/‖Wᵀu‖. The estimate is ‖Wv‖ for unit v. The output arrow points along u if Wv ≠ 0. Convergence to the major axis requires an initial component in its subspace and a spectral gap. An orthogonal direction may stay on the minor axis, and a tie at the largest singular value allows multiple major axes. Dividing by an underestimate can leave the norm above 1. Exact normalization of the zero matrix is undefined.

Matrix W
Initial vector v
Displayed matrix
Estimate ‖Wv‖
2.54951
Exact spectral norm
2.55834
Norm of the displayed matrix
2.55834
Modify the matrix and follow the estimate. Compare it with the exact singular norm of the 2×2 model.

Training recipes combine choices worth isolating in experiments: TTUR uses different update scales for the two players, but two different fixed rates alone do not satisfy the asymptotic assumptions of Heusel and colleagues; hinge loss changes the discriminator margin and objective; an exponential moving average of generator parameters smooths the model sequence without guaranteeing every average improves quality. Compare under equal budget, seeds and evaluation protocol.

As a later example, R3GAN combines relativistic loss, R1 and R2 penalties, and a modernized architecture. Its analysis and results belong to that design; they do not make hinge, WGAN-GP and R1 equivalent or prove global convergence. Quantitative image evaluation returns in FID, with its limits and seed variability.

Lab: the field and its discretization

Simulate exact non-saturating dynamics, not only their linearization. Compare simultaneous, alternating, extragradient and R1 from the same initial condition. Eigenvalues describe the local field at the origin; final distance belongs to a particular finite-step trajectory. Equality or inequality of these values does not prove a global guarantee.

[ ]Dirac-GAN and methodsBrowser
import numpy as np

def sigmoid(x):
    return np.exp(-np.logaddexp(0, -x))

def field(point, gamma=0.0):
    theta, psi = point
    product = theta * psi
    return np.array([psi * sigmoid(-product),
                     -theta * sigmoid(product) - gamma * psi])

def simulate(method, h=0.1, gamma=0.5, steps=200):
    point = np.array([0.4, 0.4])
    history = [point.copy()]
    for _ in range(steps):
        if method == 'r1':
            point = point + h * field(point, gamma)
        elif method == 'extra':
            predictor = point + h * field(point)
            point = point + h * field(predictor)
        elif method == 'alternado':
            theta, psi = point
            psi = psi + h * field(point)[1]
            theta = theta + h * field(np.array([theta, psi]))[0]
            point = np.array([theta, psi])
        elif method == 'simultaneo':
            point = point + h * field(point)
        else:
            raise ValueError('método desconocido')
        history.append(point.copy())
    return np.stack(history)

J = np.array([[0, 0.5], [-0.5, 0.]])
Jr = np.array([[0, 0.5], [-0.5, -0.5]])
print('Campo sin R1:', np.linalg.eigvals(J))
print('Campo con R1, γ=0.5:', np.linalg.eigvals(Jr))
for method in ('simultaneo', 'alternado', 'extra', 'r1'):
    path = simulate(method)
    print(method, '| distancia inicial:', round(float(np.linalg.norm(path[0])), 4),
          '| distancia final:', round(float(np.linalg.norm(path[-1])), 4))

The simultaneous Euler map near equilibrium is I+hJI+hJ; with R1 it is I+hJR1I+hJ_{R1}. Spectral radius below one characterizes linear stability of the map, while continuous-field eigenvalues are interpreted through their real parts. These are different checks.

[ ]Continuous field versus discrete stepsBrowser
h = 0.1
for name, matrix in [('sin R1', J), ('con R1', Jr)]:
    eigenvalues = np.linalg.eigvals(np.eye(2) + h * matrix)
    print(name, '| autovalores del paso:', np.round(eigenvalues, 6),
          '| radio:', round(float(np.max(np.abs(eigenvalues))), 6))

Local lab: three stabilizers on CIFAR-10

Adapt the previous DCGAN to 32×32 and remove BatchNorm from the critic so the derivative for one image does not depend on others in the batch. Compare WGAN-GP, non-saturating GAN with R1 and non-saturating GAN with custom spectral normalization. Each variant uses the same number of steps, initialization and data order; the gradient penalty requires more computation, so this is not an equal-time comparison. Losses of different objectives are not comparable, and the trained WGAN critic’s gap is not exact Wasserstein distance.

With PyTorch and torchvision installed, the cell downloads CIFAR-10 to ORYON_CIFAR_ROOT or ./data and runs 20 epochs per variant. For a short test use ORYON_QUICK=1, which reduces samples, width and epochs and does not demonstrate quality. ORYON_OUTPUT_DIR selects the results folder. Optionally ORYON_CIFAR_PARQUET points to local CIFAR-10 train-*.parquet files and requires pyarrow; the short test reads limited batches instead of the entire table. Fixed-noise grids, per-epoch metrics and models are saved. Mean pixel change between consecutive fixed-set images is only a pixel signal: it neither measures semantic diversity nor rules out collapse. Quantitative quality and coverage comparison is left to the lesson 11 harness.

In this cell r1_penalty returns mean squared norm without factor 1/21/2; multiplying by 5 equals R1 with γ=10\gamma=10. The coding exercise uses another convention and already returns half that mean.

Normalization divides the flattened-kernel matrix by its largest singular value estimate from power iteration. The test compares this implementation with PyTorch and SVD of the same matrix; it does not prove the complete spatial convolution has norm one, since positions overlap. In the spectral variant power vectors update on every critic pass, including the generator pass, even though critic weights are frozen there.

[ ]Compare WGAN-GP, R1 and spectral normalizationLocal GPU
import csv
import io
import os
from pathlib import Path

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils import parametrize
from torch.utils.data import DataLoader, Dataset, Subset
from torchvision import datasets, transforms
from torchvision.utils import save_image

quick = os.environ.get('ORYON_QUICK') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(2)
width = 8 if quick else 64
latent = 100
batch_size = 16 if quick else 128
epochs = 1 if quick else 20
root = Path(os.environ.get('ORYON_CIFAR_ROOT', './data'))
output = Path(os.environ.get('ORYON_OUTPUT_DIR', './gan-stability-results'))
output.mkdir(parents=True, exist_ok=True)
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,) * 3, (0.5,) * 3)])

class ParquetCIFAR(Dataset):
    def __init__(self, folder):
        import pyarrow.parquet as pq
        from PIL import Image
        self.image_type = Image
        files = sorted(Path(folder).glob('train-*.parquet'))
        if not files:
            raise FileNotFoundError('No hay archivos train-*.parquet en ORYON_CIFAR_PARQUET')
        self.rows = []
        limit = 64 if quick else None
        for file in files:
            reader = pq.ParquetFile(file)
            for batch in reader.iter_batches(batch_size=64 if quick else 1024, columns=['img']):
                if limit is not None:
                    batch = batch.slice(0, limit - len(self.rows))
                self.rows.extend(batch.to_pylist())
                if limit is not None and len(self.rows) >= limit:
                    break
            if limit is not None and len(self.rows) >= limit:
                break
    def __len__(self):
        return len(self.rows)
    def __getitem__(self, index):
        with self.image_type.open(io.BytesIO(self.rows[index]['img']['bytes'])) as image:
            return transform(image.convert('RGB')), 0

folder = os.environ.get('ORYON_CIFAR_PARQUET')
data = ParquetCIFAR(folder) if folder else datasets.CIFAR10(root, train=True, download=True, transform=transform)
if quick:
    data = Subset(data, range(min(64, len(data))))
if len(data) < batch_size:
    raise ValueError('Se necesita al menos un lote completo')

class PowerSN(nn.Module):
    """Normaliza la matriz del peso aplanado, no el operador espacial completo."""
    def __init__(self, weight):
        super().__init__()
        matrix = weight.detach().reshape(weight.shape[0], -1)
        self.register_buffer('u', F.normalize(torch.randn(matrix.shape[0], device=matrix.device, dtype=matrix.dtype), dim=0))
        self.register_buffer('v', F.normalize(torch.randn(matrix.shape[1], device=matrix.device, dtype=matrix.dtype), dim=0))

    def forward(self, weight):
        matrix = weight.reshape(weight.shape[0], -1)
        if self.training:
            with torch.no_grad():
                self.v.copy_(F.normalize(matrix.T @ self.u, dim=0, eps=1e-12))
                self.u.copy_(F.normalize(matrix @ self.v, dim=0, eps=1e-12))
        # Cada forward conserva sus propios vectores para backpropagar varios forwards.
        u, v = self.u.clone(), self.v.clone()
        sigma = u @ matrix @ v
        return weight / sigma.clamp_min(1e-12)

def own_spectral_norm(module):
    return parametrize.register_parametrization(module, 'weight', PowerSN(module.weight))

def spectralize(model):
    for layer in list(model.modules()):
        if isinstance(layer, nn.Conv2d):
            own_spectral_norm(layer)

# Prueba con peso fijado: iteración propia, PyTorch y SVD del mismo peso.
matrix = torch.tensor([[3.0, 1.0, 0.0], [0.0, 1.0, 0.5], [0.0, 0.0, 0.25]])
own = nn.Linear(3, 3, bias=False)
ref = nn.Linear(3, 3, bias=False)
with torch.no_grad():
    own.weight.copy_(matrix)
    ref.weight.copy_(matrix)
own_spectral_norm(own)
ref = nn.utils.parametrizations.spectral_norm(ref, n_power_iterations=1)
for _ in range(40):
    _ = own.weight
    _ = ref.weight
own.eval()
ref.eval()
exact = torch.linalg.svdvals(matrix)[0]
assert torch.allclose(own.weight, matrix / exact, atol=2e-5, rtol=2e-5)
assert torch.allclose(own.weight, ref.weight, atol=2e-5, rtol=2e-5)
print('Normalización propia y PyTorch coinciden con SVD:', round(exact.item(), 6))

class Generator(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(
            nn.ConvTranspose2d(latent, width * 4, 4, 1, 0, bias=False),
            nn.BatchNorm2d(width * 4), nn.ReLU(True),
            nn.ConvTranspose2d(width * 4, width * 2, 4, 2, 1, bias=False),
            nn.BatchNorm2d(width * 2), nn.ReLU(True),
            nn.ConvTranspose2d(width * 2, width, 4, 2, 1, bias=False),
            nn.BatchNorm2d(width), nn.ReLU(True),
            nn.ConvTranspose2d(width, 3, 4, 2, 1, bias=False), nn.Tanh(),
        )
    def forward(self, z):
        return self.net(z)

class Critic(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(
            nn.Conv2d(3, width, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, True),
            nn.Conv2d(width, width * 2, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, True),
            nn.Conv2d(width * 2, width * 4, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, True),
            nn.Conv2d(width * 4, 1, 4, 1, 0, bias=False),
        )
    def forward(self, x):
        return self.net(x).flatten()

def initialize(module):
    if isinstance(module, (nn.Conv2d, nn.ConvTranspose2d)):
        nn.init.normal_(module.weight, 0.0, 0.02)
    elif isinstance(module, nn.BatchNorm2d):
        nn.init.normal_(module.weight, 1.0, 0.02)
        nn.init.zeros_(module.bias)

def gradient_penalty(critic, real, fake):
    alpha = torch.rand(real.shape[0], 1, 1, 1, device=real.device)
    mixed = (alpha * real.detach() + (1 - alpha) * fake.detach()).requires_grad_(True)
    scores = critic(mixed)
    grad = torch.autograd.grad(scores.sum(), mixed, create_graph=True)[0]
    return ((grad.flatten(1).norm(2, dim=1) - 1) ** 2).mean()

def r1_penalty(critic, real):
    real = real.detach().requires_grad_(True)
    scores = critic(real)
    grad = torch.autograd.grad(scores.sum(), real, create_graph=True)[0]
    return grad.flatten(1).square().sum(1).mean()

# Valores exactos para un crítico lineal de norma 5; también comprueban autograd.
class LinearCritic(nn.Module):
    def forward(self, x):
        return 3 * x[:, 0, 0, 0] + 4 * x[:, 1, 0, 0]
check_real = torch.zeros(2, 3, 1, 1)
check_fake = torch.ones_like(check_real)
assert torch.allclose(gradient_penalty(LinearCritic(), check_real, check_fake), torch.tensor(16.0))
assert torch.allclose(r1_penalty(LinearCritic(), check_real), torch.tensor(25.0))
print('Pruebas de gradiente: GP=16 y R1=25 para norma 5')

for mode in ('wgan-gp', 'r1', 'spectral'):
    torch.manual_seed(81)
    if device.type == 'cuda':
        torch.cuda.manual_seed_all(81)
    G, D = Generator().to(device), Critic().to(device)
    G.apply(initialize)
    D.apply(initialize)
    if mode == 'spectral':
        spectralize(D)
    opt_g = torch.optim.Adam(G.parameters(), lr=0.0002, betas=(0.0, 0.9))
    opt_d = torch.optim.Adam(D.parameters(), lr=0.0002, betas=(0.0, 0.9))
    torch.manual_seed(83)
    if device.type == 'cuda':
        torch.cuda.manual_seed_all(83)
    data_rng = torch.Generator().manual_seed(84)
    loader = DataLoader(data, batch_size=batch_size, shuffle=True, drop_last=True,
                        num_workers=0, generator=data_rng)
    fixed_rng = torch.Generator().manual_seed(85)
    fixed_z = torch.randn(64, latent, 1, 1, generator=fixed_rng).to(device)
    mode_path = output / mode
    mode_path.mkdir(parents=True, exist_ok=True)
    history = []
    for epoch in range(1, epochs + 1):
        G.train()
        D.train()
        totals = torch.zeros(4, device=device)
        count = 0
        for real, _ in loader:
            real = real.to(device)
            n = real.shape[0]
            fake = G(torch.randn(n, latent, 1, 1, device=device))
            opt_d.zero_grad(set_to_none=True)
            real_score, fake_score = D(real), D(fake.detach())
            if mode == 'wgan-gp':
                penalty = gradient_penalty(D, real, fake)
                d_loss = fake_score.mean() - real_score.mean() + 10 * penalty
            elif mode == 'r1':
                penalty = r1_penalty(D, real)
                d_loss = F.softplus(-real_score).mean() + F.softplus(fake_score).mean() + 5 * penalty
            else:
                penalty = torch.zeros((), device=device)
                d_loss = F.softplus(-real_score).mean() + F.softplus(fake_score).mean()
            d_loss.backward()
            opt_d.step()
            for p in D.parameters():
                p.requires_grad_(False)
            opt_g.zero_grad(set_to_none=True)
            score_for_g = D(fake)
            g_loss = -score_for_g.mean() if mode == 'wgan-gp' else F.softplus(-score_for_g).mean()
            g_loss.backward()
            opt_g.step()
            for p in D.parameters():
                p.requires_grad_(True)
            totals += n * torch.stack((d_loss.detach(), g_loss.detach(), penalty.detach(),
                                       (real_score.detach() - fake_score.detach()).mean()))
            count += n
        metrics = (totals / count).cpu().tolist()
        G.eval()
        with torch.no_grad():
            images = ((G(fixed_z) + 1) / 2).clamp(0, 1)
            difference = (images[1:] - images[:-1]).abs().mean().item()
            save_image(images, mode_path / f'fijo-{epoch:03d}.png', nrow=8)
        history.append([epoch, *metrics, difference])
        print(f'{mode} época {epoch:02d}: D={metrics[0]:.4f} G={metrics[1]:.4f} '
              f'penalización={metrics[2]:.4f} brecha={metrics[3]:.4f} '
              f'diferencia de píxel={difference:.4f}')
    with (mode_path / 'metricas.csv').open('w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerow(['epoca', 'objetivo_D', 'objetivo_G', 'penalizacion_sin_peso',
                         'real_menos_falsa', 'diferencia_pixel'])
        writer.writerows(history)
    torch.save({'G': G.state_dict(), 'D': D.state_dict(), 'width': width,
                'latent': latent, 'ruido_fijo': fixed_z.cpu()}, mode_path / 'modelos.pt')
    del real, fake, real_score, fake_score, score_for_g, d_loss, g_loss, penalty
    del images, totals, fixed_z, G, D, opt_g, opt_d, p
    if device.type == 'cuda':
        torch.cuda.empty_cache()

print('Resultados:', output.resolve())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofLinearizing the game
Prove: Linearize the Dirac-GAN non-saturating field at the origin and study R1 regularization.
0
Use θ for the fake sample, ψ for logit ψx and γ > 0 for penalty γψ²/2.

Step 1 of 3. What is the Jacobian without R1?

ProofSlope along an optimal segment
Prove: Let f be 1-Lipschitz and f(x)−f(y)=||x−y|| for x≠y. Prove that wherever f is differentiable inside the segment, its gradient has norm one.
0
Write z_t=(1−t)y+tx with 0<t<1.

Step 1 of 3. What does Lipschitz continuity imply for the two subsegments?

NumericLayerwise bound
A network with three matrices has spectral norms 2, 1.5 and 3, and 1-Lipschitz ReLU activations. What Lipschitz bound does the product of norms give?
CodePenalties with autograd
Implement gradient_penalty(critic, real, fake) and r1_penalty(D, real). Both models return a logit or scalar per example and process examples independently. GP returns the mean (norm−1)² over uniform interpolations; R1 returns half the mean squared norm on real data. Detach fake, use torch.autograd.grad with create_graph=True and do not multiply by regularization coefficients.
import torch

def gradient_penalty(critic, real, fake):
  pass

def r1_penalty(D, real):
  pass
Shift+Enter to run
QuizA data-centered penalty
You use non-saturating loss and a discriminator without BatchNorm. You want to penalize the logit gradient on real data toward zero. Which regularizer matches that objective?
Key idea

Game dynamics, distribution distance and critic constraints are different pieces. An improvement observed under one protocol does not turn a soft penalty into a global guarantee.