Module contents
Lesson 8 of 28Core 110 min

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

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 GθG_\theta to transform simple noise z∼pzz\sim p_z into samples Gθ(z)G_\theta(z). Another network, DϕD_\phi, 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 zz and evaluating GG, but generally no evaluable density for pgp_g 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 GG while updating DD with a real batch and a generated batch. Then freeze parameters of DD, while retaining its derivative with respect to its input, to update GG. Freezing parameters does not interrupt the derivative traveling from D(G(z))D(G(z)) to GG. Several discriminator steps may be taken per generator step: changing this ratio changes game dynamics.

InteractiveThe eight-Gaussian arena
  • Real samples
  • G samples
  • G descent direction
  • Selected point
D ≈ 0
D ≈ 1

The data are an equal mixture of eight isotropic Gaussians, with centers on a circle of radius 2 and standard deviation 0.12. The generator and discriminator MLPs train in the browser from seed 1908 with Adam, batch size 64, and moments 0.5 and 0.999. Each G step follows the chosen number of D steps. Points and displayed losses use fixed samples separate from each update's samples.

A mode counts as nearby when at least two of the 192 G samples lie within 0.35 of its center. This discrete criterion measures one aspect of quality. Arrows show −∇ₓL_G on twelve samples, rescaled together to show direction. The mean norm uses the original magnitude. An output gradient can differ from the actual sample movement after updating all G parameters.

Generator loss
0.0020
0.0020
2
G steps0
Nearby modes0 / 8
D loss1.411
G loss0.688
Mean arrow norm0.3014
D at selected point0.500
Train both players and inspect samples, discriminator and gradients. Behavior depends on the controls and stated seed.

The best discriminator for a fixed generator

Suppose both distributions have densities pp and qq with respect to a common measure, and GG is fixed. An unconstrained discriminator can be chosen independently at each point.

Proof

At a point with p,q>0p,q>0, differentiate plog⁡D+qlog⁡(1−D)p\log D+q\log(1-D) with respect to DD: condition p/D−q/(1−D)=0p/D-q/(1-D)=0 gives D=p/(p+q)D=p/(p+q). The second derivative is negative. If one density is zero, the maximum occurs at the corresponding endpoint; interpret 0log⁡00\log0 terms by continuity. Substitute p/(p+q)=p/(2m)p/(p+q)=p/(2m) and q/(p+q)=q/(2m)q/(p+q)=q/(2m): the two 1/21/2 factors contribute −2log⁡2-2\log2 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 log⁡2\log2 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.

InteractiveThe optimal discriminator in 1D

Two Gaussian densities with standard deviation 0.85. Move their means independently.

JSD uses natural logs and midpoint quadrature on [−12, 12] with step 0.02. The displayed value 2 JSD − log 4 assumes an optimized discriminator of unlimited capacity and equal weights for both classes. These Gaussian densities are positive everywhere, so JSD approaches log 2 only as separation grows without bound. Outside the union of the supports, the objective would leave D* undetermined.

-1.0
1.0
Approximate JSD
0.4126 nats
Game value
−0.5610 nats
JSD limit
0.6931 nats
Move the two distributions and compare their densities, optimal classifier and divergence calculated for the indicated model.

With equally likely classes and pg(x)>0p_g(x)>0, D∗(x)/(1−D∗(x))=p(x)/q(x)D^*(x)/(1-D^*(x))=p(x)/q(x). Thus an optimal classifier estimates a density ratio even when normalizations are unknown. If the real-class prior probability is α\alpha, the ratio requires prior correction: p/q=((1−α)/α)D∗/(1−D∗)p/q=((1-\alpha)/\alpha)D^*/(1-D^*). An approximate or poorly calibrated classifier does not make this identity an exact estimate; near D=1D=1 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 a(x)a(x) and D(x)=σ(a(x))D(x)=\sigma(a(x)). If the generator minimizes the original loss ℓsat(a)=log⁡(1−σ(a))\ell_{\rm sat}(a)=\log(1-\sigma(a)), then

dℓsatda=−σ(a).\frac{d\ell_{\rm sat}}{da}=-\sigma(a).

When the discriminator assigns a fake sample probability near zero, this factor approaches zero. By the chain rule, ∇θℓ=(dℓ/da)∇xa(Gθ(z))∇θGθ(z)\nabla_\theta\ell=(d\ell/da)\nabla_x a(G_\theta(z))\nabla_\theta G_\theta(z): saturation of the scalar factor does not remove the need to inspect the other derivatives too.

Do not confuse derivatives with respect to DD with derivatives with respect to the logit: dlog⁡(1−D)/dD=−1/(1−D)d\log(1-D)/dD=-1/(1-D) does not tend to zero when D→0D\to0. The sigmoid factor D(1−D)D(1-D) changes the conclusion. Non-saturating loss provides a larger scalar factor in that regime, but does not guarantee useful gradients if ∇xa\nabla_x a 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 pp and q=pgq=p_g are positive smooth densities, and differentiation can be exchanged with integration, the expected gradient when updating GG with D∗D^* frozen coincides with the gradient of KL⁡(q∥p)−2JSD⁡(p∥q)\KL(q\|p)-2\operatorname{JSD}(p\|q). The second exercise proves this identity via functional derivatives. Do not substitute D∗(q)D^*(q) 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.

InteractiveThe generator signal

For a fake sample, D = σ(a). The vertical line marks the selected value.

Both losses are minimized with respect to the generator. Their derivatives with respect to logit a are −D and D−1. As D approaches zero, the first slope tends to zero and the second tends to −1. These derivatives include the derivative of the sigmoid. The generator parameter gradient also multiplies by ∂a/∂θ, which itself can be small or zero.

-4.0
D = σ(a)
0.0180
Saturating slope
−0.0180
Non-saturating slope
−0.9820
Compare losses and their derivatives with respect to the discriminator logit as its confidence in the fake sample changes.

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 min⁡xmax⁡yxy\min_x\max_y xy. The simultaneous descent field in xx and ascent field in yy is (−y,x)(-y,x): it points perpendicular to vector (x,y)(x,y) 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 zz 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 DD remain fixed while differentiating through its input. The lab leaves DD 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, DD receives five steps for every GG 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.

[ ]Networks and manual gradientsBrowser
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)
[ ]Training: steps 1 to 200Browser
advance_both(200)
[ ]Training: steps 201 to 400Browser
advance_both(200)
[ ]Training: steps 401 to 600Browser
advance_both(200)
[ ]Training: steps 601 to 800Browser
advance_both(200)
[ ]Training: steps 801 to 1000Browser
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.

[ ]Sample evolutionBrowser
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.

[ ]Train a DCGAN with fixed noiseLocal GPU
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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofOptimizing the classifier
Prove: For fixed p and q, derive D* and the optimal GAN value under the theorem assumptions.
0
First work at points where p and q are strictly positive.

Step 1 of 3. What equation follows from differentiating with respect to D?

ProofThe non-saturating field
Prove: For smooth positive densities and valid differentiation under the integral, relate the generator gradient with frozen D* to a function of p_g.
0
Use q=p_g, p=p_data and m=(p+q)/2. During this step the gradient does not pass through the dependence of D* on q.

Step 1 of 3. What is the functional derivative of KL(q||p) with respect to q?

NumericEquilibrium value
Using natural logarithms, what is V(D*, G) when p_g = p_data?
CodeStable losses on logits
Implement gan_losses(real, fake, kind). real and fake are arrays of logits. Return discriminator loss, mean softplus(−real) plus mean softplus(fake), and generator loss: mean −softplus(fake) for kind='minimax' or mean softplus(−fake) for kind='non_saturating'. Use np.logaddexp for stability and reject other names.
import numpy as np

def gan_losses(real, fake, kind):
  pass
Shift+Enter to run
QuizWhat do the curves show?
D and G losses oscillate while a few sample classes repeatedly appear. Which conclusion is best supported?
Key idea

A 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.