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
Its eigenvalues are : 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 , linear-map eigenvalues are and their modulus is : near the origin this linear discretization amplifies the orbit.
Add a penalty to the discriminator objective. Its field component gains . Eigenvalues of the new matrix are , with a complex root when . For every 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.
Not every regularizer centers the same value. For a linear Wasserstein critic, GP is proportional to , which is not differentiable at . 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 gives the pointwise bound; integrating with respect to yields the expression. A neural-network family offers only a supremum over that family, and the domain of must be respected. A sufficiently expressive witness and suitable conditions attain the full representation. Nowozin, Cseke and Tomioka formulate this for different divergences: changing changes the objective and sensitivity to regions of different mass, without itself guaranteeing stable training.
From transport to a Wasserstein critic
For point masses and , : 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.
Gradients at different points
GP intuition comes from an optimal 1-Lipschitz potential saturating the transport inequality for pairs in an optimal coupling. If with , Lipschitz continuity preserves equality at each interior point of the segment. Where is differentiable, its derivative in the segment direction is one; because its norm cannot exceed one, . 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 and ; 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.
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.
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 ; with R1 it is . Spectral radius below one characterizes linear stability of the map, while continuous-field eigenvalues are interpreted through their real parts. These are different checks.
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 ; multiplying by 5 equals R1 with . 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.
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())npm run lab and open the connection link.Exercises
Step 1 of 3. What is the Jacobian without R1?
Step 1 of 3. What does Lipschitz continuity imply for the two subsegments?
import torch
def gradient_penalty(critic, real, fake):
pass
def r1_penalty(D, real):
passGame 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.