GANs: the game between generator and discriminator
GANs generate without evaluable likelihood: an implicit generator learns against a classifier distinguishing real and generated data. Derive the optimal discriminator and game value in terms of Jensen-Shannon divergence, interpret density-ratio estimation, and study gradient saturation, mode collapse, oscillation and DCGAN.
After this lesson you can
- Derive D* = p_data/(p_data + p_g) and the ideal generator criterion 2 JSD(p_data ‖ p_g) - log 4.
- Explain generator-gradient saturation and derive the non-saturating loss.
- Implement a GAN from scratch in NumPy and investigate mode collapse in 2D data.
- Train a DCGAN on the local GPU and interpret both players’ loss curves.
- Relate the discriminator to density-ratio estimation by classification.
Before you start
- 19Taxonomy of generative modelsDivergence choice as a design decisionLow-dimensional supports and divergence degeneracy
- 07Jensen-Shannon divergence
- 06Min-max problems and saddle pointsGradient descent-ascent
- 12Noise-contrastive estimationOptimal critic as density ratio
- 11Logistic regressionLogistic loss as Bernoulli likelihood
- 16Multichannel convolutional layerTransposed convolution
Learning to generate with an adversary
Imagine having many real images without knowing a function that assigns probability to every possible image. Train a network to transform simple noise into samples . Another network, , observes images and tries to distinguish real from generated ones. The generator’s signal depends on an adversary that is also changing.
This is an implicit model: generation only requires sampling and evaluating , but generally no evaluable density for is available. Evaluation is still necessary. Visual quality, distribution coverage and memorization require different protocols; a selection of the best images does not represent typical behavior.
In alternating implementation, freeze while updating with a real batch and a generated batch. Then freeze parameters of , while retaining its derivative with respect to its input, to update . Freezing parameters does not interrupt the derivative traveling from to . Several discriminator steps may be taken per generator step: changing this ratio changes game dynamics.
The best discriminator for a fixed generator
Suppose both distributions have densities and with respect to a common measure, and is fixed. An unconstrained discriminator can be chosen independently at each point.
Proof
At a point with , differentiate with respect to : condition gives . The second derivative is negative. If one density is zero, the maximum occurs at the corresponding endpoint; interpret terms by continuity. Substitute and : the two factors contribute and the remaining integrals are the two KL terms. Each KL vanishes only when its distributions coincide almost everywhere.
∎This result assumes an optimal discriminator in a sufficiently broad class; it does not automatically describe the value or gradient of a network trained for a few steps. For disjoint supports JSD reaches and the optimal value is zero. The measure does not indicate the distance between supports: moving them farther leaves JSD unchanged. Arjovsky and Bottou analyze support and saturation problems in adversarial training.
With equally likely classes and , . Thus an optimal classifier estimates a density ratio even when normalizations are unknown. If the real-class prior probability is , the ratio requires prior correction: . An approximate or poorly calibrated classifier does not make this identity an exact estimate; near division also amplifies errors. The same connection appears in density-ratio estimation by classification.
When winning too early removes the signal
Write the discriminator logit as and . If the generator minimizes the original loss , then
When the discriminator assigns a fake sample probability near zero, this factor approaches zero. By the chain rule, : saturation of the scalar factor does not remove the need to inspect the other derivatives too.
Do not confuse derivatives with respect to with derivatives with respect to the logit: does not tend to zero when . The sigmoid factor changes the conclusion. Non-saturating loss provides a larger scalar factor in that regime, but does not guarantee useful gradients if is zero, the discriminator generalizes poorly or the generator derivative is degenerate. Both losses share the ideal equilibrium, but their training dynamics differ.
A further interpretation of the non-saturating field requires stronger assumptions. If and are positive smooth densities, and differentiation can be exchanged with integration, the expected gradient when updating with frozen coincides with the gradient of . The second exercise proves this identity via functional derivatives. Do not substitute in the loss and differentiate through that dependence: that total calculation gives a different result. With disjoint supports, reverse KL can be infinite and this formulation no longer applies without further assumptions.
Dynamics, coverage and architectures
Both players’ losses depend on their rivals and can oscillate without quality changing monotonically. A discriminator unable to distinguish samples may indicate equilibrium, insufficient capacity or faulty training. Save a grid obtained with fixed noise to track changes, and also evaluate independent samples: one fixed grid does not measure diversity. Low generator loss does not guarantee good coverage.
As a simple example of rotation in a game, consider . The simultaneous descent field in and ascent field in is : it points perpendicular to vector rather than directly at equilibrium. A discrete step can amplify oscillations. Real GAN networks and optimizers add other dynamics, so this example illustrates a mechanism rather than quantitatively predicting every run.
The generator usually ends with tanh and receives images scaled to the same interval; the discriminator should output logits when using a stable binary loss on logits. Applying sigmoid first and directly taking logarithms can overflow or lose precision. Batch normalization uses shared statistics: mixing real and fake examples in one batch changes the problem because one example’s output depends on others. State the protocol and evaluate in inference mode too. Interpolating lets us observe output continuity, but a pleasing path does not prove coverage or absence of memorization.
The discriminator update uses real labels of one and fake labels of zero, summing the two mean cross-entropies. The non-saturating generator update uses labels of one for fake samples, even though they are not real data: that label defines gradient direction. During the generator step the parameters of remain fixed while differentiating through its input. The lab leaves in training mode, so its BatchNorm statistics also update on that batch; freezing parameters does not automatically freeze those buffers. This choice affects dynamics and must be preserved when comparing runs.
Lab: a small GAN from scratch
Both networks are MLPs with one tanh hidden layer. The discriminator receives points from an equally weighted eight-Gaussian mixture with radius 2 and standard deviation 0.12; the generator receives 2D normal noise. Each variant starts with the same seed and architecture. In this deliberately unbalanced experiment, receives five steps for every step and uses a higher learning rate. Compare minimax with non-saturating loss while keeping everything else fixed.
A region counts as covered if at least 1% of 2000 evaluation samples fall within 0.4 of its center. Also report the total fraction near any center: covering more regions with a diffuse cloud does not imply better samples. The 2000 samples use fixed evaluation noise distinct from training. Change seeds and thresholds before generalizing.
import numpy as np
centers = 2 * np.column_stack((np.cos(np.arange(8) * np.pi / 4),
np.sin(np.arange(8) * np.pi / 4)))
def init_mlp(rng, n_in, n_out, hidden=24):
return [rng.normal(0, 1 / np.sqrt(n_in), (n_in, hidden)),
np.zeros(hidden), rng.normal(0, 1 / np.sqrt(hidden), (hidden, n_out)),
np.zeros(n_out)]
def forward(params, x):
hidden = np.tanh(x @ params[0] + params[1])
return hidden @ params[2] + params[3], (x, hidden)
def backward(params, cache, dy):
x, h = cache
dh = (dy @ params[2].T) * (1 - h * h)
return [x.T @ dh, dh.sum(axis=0), h.T @ dy, dy.sum(axis=0)], dh @ params[0].T
def step_adam(params, grads, state, lr):
m, v, t = state
t += 1
for i, grad in enumerate(grads):
m[i] = 0.9 * m[i] + 0.1 * grad
v[i] = 0.999 * v[i] + 0.001 * grad * grad
params[i] -= lr * (m[i] / (1 - 0.9 ** t)) / (np.sqrt(v[i] / (1 - 0.999 ** t)) + 1e-8)
return m, v, t
def new_state(params):
return [np.zeros_like(p) for p in params], [np.zeros_like(p) for p in params], 0
def sigmoid(x):
return np.exp(-np.logaddexp(0, -x))
class Experiment:
def __init__(self, kind):
self.kind = kind
self.rng = np.random.default_rng(47)
self.g = init_mlp(self.rng, 2, 2)
self.d = init_mlp(self.rng, 2, 1)
self.gs, self.ds = new_state(self.g), new_state(self.d)
self.t = 0
self.history = []
self.capture()
def capture(self):
noise = np.random.default_rng(1046).normal(size=(2000, 2))
samples, _ = forward(self.g, noise)
dist = np.linalg.norm(samples[:, None, :] - centers[None, :, :], axis=2)
nearest, close = dist.argmin(axis=1), dist.min(axis=1) < 0.4
counts = np.bincount(nearest[close], minlength=8)
self.history.append((self.t, samples[:256].copy(), counts, float(close.mean())))
print(self.kind, 'paso', self.t, '| centros con ≥1%:', int((counts >= 20).sum()),
'| fracción cerca:', round(float(close.mean()), 3))
def advance(self, steps):
batch = 64
for _ in range(steps):
for _ in range(5):
real = centers[self.rng.integers(8, size=batch)] + self.rng.normal(0, 0.12, (batch, 2))
fake, _ = forward(self.g, self.rng.normal(size=(batch, 2)))
real_logits, rc = forward(self.d, real)
fake_logits, fc = forward(self.d, fake)
dr, _ = backward(self.d, rc, (sigmoid(real_logits) - 1) / batch)
df, _ = backward(self.d, fc, sigmoid(fake_logits) / batch)
self.ds = step_adam(self.d, [a+b for a,b in zip(dr, df)], self.ds, 0.01)
fake, gc = forward(self.g, self.rng.normal(size=(batch, 2)))
logits, fc = forward(self.d, fake)
slope = -sigmoid(logits) if self.kind == 'minimax' else sigmoid(logits)-1
_, dx = backward(self.d, fc, slope / batch)
gg, _ = backward(self.g, gc, dx)
self.gs = step_adam(self.g, gg, self.gs, 0.0002)
self.t += 1
if self.t % 100 == 0:
self.capture()
experiments = [Experiment('minimax'), Experiment('no saturante')]
def advance_both(steps):
for experiment in experiments:
experiment.advance(steps)
advance_both(200)advance_both(200)advance_both(200)advance_both(200)advance_both(200)In the reference run with this seed, at step 1000 the declared rule counts two centers for minimax and seven for non-saturating loss. The fractions near any center were approximately 0.259 and 0.143 respectively: coverage improves under that threshold while this precision measure worsens. This compares one seed and budget and does not guarantee non-saturating loss prevents collapse.
Each panel shows the first 256 points from the same fixed noise. The preceding figures use all 2000 samples. Observe states every 100 steps and compare covered regions with sample precision.
import matplotlib.pyplot as plt
for experiment in experiments:
fig, axes = plt.subplots(2, 6, figsize=(12, 4))
for ax, (step, points, counts, fraction) in zip(axes.flat, experiment.history):
ax.scatter(points[:, 0], points[:, 1], s=2, alpha=0.4)
ax.scatter(centers[:, 0], centers[:, 1], s=10, marker='x')
ax.set(xlim=(-3, 3), ylim=(-3, 3), title=str(step))
ax.set_xticks([]); ax.set_yticks([])
axes.flat[-1].axis('off')
fig.suptitle(experiment.kind)
fig.tight_layout()
plt.show()
plt.close(fig)Local lab: DCGAN on Fashion-MNIST and CelebA
The cell trains DCGAN with non-saturating loss and BCE on logits. By default it uses Fashion-MNIST, the full network and 25 epochs. For a short trial set ORYON_QUICK=1: it uses 128 images, one epoch and fewer channels; its images do not demonstrate quality. ORYON_FASHION_ROOT may point to the directory containing FashionMNIST; otherwise data download to ./data. ORYON_OUTPUT_DIR changes the output folder.
For CelebA, download img_align_celeba.zip from the official page, accept its terms and extract it. Set ORYON_DATASET=celeba and ORYON_CELEBA_DIR to the flat img_align_celeba folder. The lab uses a centered 178-pixel crop resized to 64×64. CelebA is distributed for noncommercial research and its terms restrict redistribution: consult the official page before use. To return to Fashion set ORYON_DATASET=fashion.
Mean probabilities and losses describe the game during training; they do not by themselves measure quality or coverage. The fixed-noise grid permits epoch comparison without hand-picking images; linear interpolation follows two latents fixed at the start and can pass through low-probability regions. The implementation follows the architecture and initialization of the official PyTorch example, with stable BCE on logits.
import csv
import os
from pathlib import Path
import torch
import torch.nn as nn
from PIL import Image
from torch.utils.data import DataLoader, Dataset, Subset
from torchvision import datasets, transforms
from torchvision.utils import save_image
import matplotlib.pyplot as plt
quick = os.environ.get('ORYON_QUICK') == '1'
kind = os.environ.get('ORYON_DATASET', 'fashion').lower()
if kind not in ('fashion', 'celeba'):
raise ValueError('ORYON_DATASET debe ser fashion o celeba')
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.manual_seed(81)
if device.type == 'cuda':
torch.cuda.manual_seed_all(81)
torch.set_num_threads(2)
output = Path(os.environ.get('ORYON_OUTPUT_DIR', './dcgan-results')) / kind
output.mkdir(parents=True, exist_ok=True)
epochs = 1 if quick else 25
batch_size = 16 if quick else 128
width = 8 if quick else 64
latent = 100
channels = 1 if kind == 'fashion' else 3
normalize = transforms.Normalize((0.5,) * channels, (0.5,) * channels)
if kind == 'fashion':
transform = transforms.Compose([transforms.Resize((64, 64)), transforms.ToTensor(), normalize])
root = Path(os.environ.get('ORYON_FASHION_ROOT', './data'))
dataset = datasets.FashionMNIST(root, train=True, transform=transform, download=True)
else:
directory = os.environ.get('ORYON_CELEBA_DIR')
if not directory:
raise ValueError('Define ORYON_CELEBA_DIR con la carpeta img_align_celeba')
class CelebAFiles(Dataset):
def __init__(self, folder):
self.files = sorted(Path(folder).glob('*.jpg'))
if not self.files:
raise ValueError('No se encontraron archivos JPG en ORYON_CELEBA_DIR')
self.transform = transforms.Compose([
transforms.CenterCrop(178), transforms.Resize((64, 64)),
transforms.ToTensor(), normalize,
])
def __len__(self):
return len(self.files)
def __getitem__(self, index):
with Image.open(self.files[index]) as image:
return self.transform(image.convert('RGB')), 0
dataset = CelebAFiles(directory)
if quick:
dataset = Subset(dataset, range(min(128, len(dataset))))
if len(dataset) < batch_size:
raise ValueError('Se necesita al menos un lote completo')
loader = DataLoader(dataset, batch_size=batch_size, shuffle=True,
num_workers=0, drop_last=True)
class Generator(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.ConvTranspose2d(latent, width * 8, 4, 1, 0, bias=False),
nn.BatchNorm2d(width * 8), nn.ReLU(True),
nn.ConvTranspose2d(width * 8, width * 4, 4, 2, 1, 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, channels, 4, 2, 1, bias=False), nn.Tanh(),
)
def forward(self, z):
return self.net(z)
class Discriminator(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(channels, width, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, True),
nn.Conv2d(width, width * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(width * 2), nn.LeakyReLU(0.2, True),
nn.Conv2d(width * 2, width * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(width * 4), nn.LeakyReLU(0.2, True),
nn.Conv2d(width * 4, width * 8, 4, 2, 1, bias=False),
nn.BatchNorm2d(width * 8), nn.LeakyReLU(0.2, True),
nn.Conv2d(width * 8, 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)
G = Generator().to(device)
D = Discriminator().to(device)
G.apply(initialize)
D.apply(initialize)
opt_g = torch.optim.Adam(G.parameters(), lr=0.0002, betas=(0.5, 0.999))
opt_d = torch.optim.Adam(D.parameters(), lr=0.0002, betas=(0.5, 0.999))
bce = nn.BCEWithLogitsLoss()
fixed_rng = torch.Generator().manual_seed(123)
fixed_z = torch.randn(64, latent, 1, 1, generator=fixed_rng).to(device)
endpoints = torch.randn(2, latent, 1, 1, generator=fixed_rng).to(device)
mix = torch.linspace(0, 1, 9, device=device).reshape(-1, 1, 1, 1)
interpolated_z = (1 - mix) * endpoints[0] + mix * endpoints[1]
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.size(0)
z = torch.randn(n, latent, 1, 1, device=device)
fake = G(z)
opt_d.zero_grad(set_to_none=True)
# Lotes reales y falsos por separado: BatchNorm nunca los mezcla.
real_logits = D(real)
fake_logits = D(fake.detach())
d_loss = (bce(real_logits, torch.ones_like(real_logits)) +
bce(fake_logits, torch.zeros_like(fake_logits)))
d_loss.backward()
opt_d.step()
# Congelar D no impide propagar su gradiente hasta las imágenes falsas.
for parameter in D.parameters():
parameter.requires_grad_(False)
opt_g.zero_grad(set_to_none=True)
generated_logits = D(fake)
g_loss = bce(generated_logits, torch.ones_like(generated_logits))
g_loss.backward()
opt_g.step()
for parameter in D.parameters():
parameter.requires_grad_(True)
totals += n * torch.stack((d_loss.detach(), g_loss.detach(),
real_logits.detach().sigmoid().mean(),
fake_logits.detach().sigmoid().mean()))
count += n
metrics = (totals / count).cpu().tolist()
history.append([epoch, *metrics])
print(f'época {epoch:02d}: D={metrics[0]:.4f} G={metrics[1]:.4f} '
f'D(real)={metrics[2]:.4f} D(falsa)={metrics[3]:.4f}')
G.eval()
with torch.no_grad():
grid = ((G(fixed_z) + 1) / 2).clamp(0, 1)
save_image(grid, output / f'fijo-{epoch:03d}.png', nrow=8)
interpolation = ((G(interpolated_z) + 1) / 2).clamp(0, 1)
save_image(interpolation, output / f'interpolacion-{epoch:03d}.png', nrow=9)
with (output / 'metricas.csv').open('w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['epoca', 'perdida_D', 'perdida_G', 'D_real', 'D_falsa_antes_paso_D'])
writer.writerows(history)
torch.save({'generador': G.state_dict(), 'discriminador': D.state_dict(),
'latent': latent, 'width': width, 'channels': channels,
'fixed_z': fixed_z.cpu(), 'endpoints': endpoints.cpu()}, output / 'dcgan.pt')
fig, ax = plt.subplots()
ax.plot([row[0] for row in history], [row[1] for row in history], label='D')
ax.plot([row[0] for row in history], [row[2] for row in history], label='G no saturante')
ax.set(xlabel='Época', ylabel='Pérdida media por imagen')
ax.legend()
fig.tight_layout()
fig.savefig(output / 'perdidas.png')
plt.close(fig)
print('Archivos generados:', output.resolve())
# Se liberan también los tensores de la última iteración antes de vaciar CUDA.
del real, z, fake, real_logits, fake_logits, generated_logits, d_loss, g_loss
del grid, interpolation, totals, fixed_z, endpoints, interpolated_z, mix
del G, D, opt_g, opt_d, parameter
if device.type == 'cuda':
torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
Step 1 of 3. What equation follows from differentiating with respect to D?
Step 1 of 3. What is the functional derivative of KL(q||p) with respect to q?
import numpy as np
def gan_losses(real, fake, kind):
passA GAN learns through a game rather than directly maximizing an evaluable likelihood. JSD describes the discriminator’s ideal optimum; practical losses, their gradients and observed coverage require separate analysis.