Generative Adversarial Networks: Two-Player Minimax Game implicit generators · binary log-loss critic · optimal log density ratio · Jensen–Shannon saturation · non-saturating loss & mode dropping
Implicit Generators and Why Likelihood Misleads
Motivation
Maximum likelihood estimation requires evaluating \log q_\theta(x) at every training observation, whereas an implicit generator defines a distribution directly through a sampling program x' = G_\theta(z) with z \sim \mathcal{N}(0, I_{d_z}):
Singular support (d_z \ll d_x): Mapping d_z = 100 Gaussian numbers to d_x = 784 Fashion-MNIST pixels concentrates q_\theta on a 100-dimensional manifold with no density on \mathbb{R}^{784} (and no tractable Jacobian determinant).
High likelihood \neq realistic samples (Theis et al., 2016): The mixture \tilde{p}(x) = 0.01\,p_{\textrm{data}}(x) + 0.99\,p_{\textrm{noise}}(x) satisfies \log \tilde{p}(x) \ge \log p_{\textrm{data}}(x) - \log 100, falling short of the true distribution by at most 4.6 nats while producing 99\% noise.
Two-Sample Comparison via a Binary Classifier
The Minimax Architecture
Just as a domain classifier detects covariate shift between training and test inputs, a GAN trains a binary discriminator (critic)D: \mathcal{X} \to \mathbb{R} to separate real data from generated samples:
Balanced mixture protocol: Draw source label y \sim \textrm{Bernoulli}(\frac{1}{2}). If y = 1, sample x \sim p (real data); if y = 0, sample x' = G(z) \sim q (generator). Pooled samples follow m(x) = \frac{1}{2}(p(x) + q(x)).
Realness logit D(x): Applying the logistic sigmoid \sigma(t) = 1/(1 + e^{-t}) maps the unconstrained critic score D(x) to an estimate of the posterior P(y = 1 \mid x).
Alternating updates:D updates its weights to classify real vs. fake minibatches; G updates its weights using gradients backpropagated through D.
Equal-variance shift (p = \mathcal{N}(0, 1),q = \mathcal{N}(\mu, 1)): The quadratic x^2/2 terms cancel, leaving an affine critic that flips sign at the midpoint x = \mu/2.
Unequal covariances (\Sigma_p \neq \Sigma_q): The log density ratio retains the quadratic term -\frac{1}{2}x^\top(\Sigma_p^{-1} - \Sigma_q^{-1})x, requiring a nonlinear neural network (e.g., leaky-ReLU MLP).
Minimax Value and the Jensen–Shannon Divergence
Population Objective
\max_D V(D) = D_{\textrm{KL}}(p \,\|\, m) + D_{\textrm{KL}}(q \,\|\, m) - 2\log 2 = 2\,\mathrm{JS}(p, q) - 2\log 2
Substituting \sigma(D^\star) = \frac{p}{2m}: With mixture m = \frac{1}{2}(p + q), the optimal value function reduces to the Jensen–Shannon divergence\mathrm{JS}(p, q).
Unique global equilibrium (q = p): Since \mathrm{JS}(p, q) \ge 0 with equality iff q = p, minimizing \max_D V(D) uniquely recovers q = p at value -2\log 2.
Mutual information identity:\mathrm{JS}(p, q) equals the mutual information I(x; y) between a draw x \sim m and its binary source label y \in \{0, 1\}.
Why \mathrm{JS} saturates in high dimensions: When p and q lie on disjoint low-dimensional manifolds, every sample reveals its label y with certainty, freezing \mathrm{JS}(p, q) = \log 2 \approx 0.6931 nats with zero slope.
Saturating vs. Non-Saturating Generator Gradients
Gradient Rescaling
In practice, the generator takes a gradient step against a fixed critic D. Both generator losses push each sample x' = G_\theta(z) along the same spatial direction \nabla_\theta D(G_\theta(z)), differing only in their scalar weight:
Saturating minimax loss(\min_\theta \mathbb{E}_z[\log \sigma(-D(x'))]):\nabla_\theta \mathcal{L}_{\textrm{sat}} = -\mathbb{E}_z\Big[\underbrace{\sigma(D(x'))}_{w_{\textrm{sat}}(x')}\,\nabla_\theta D(G_\theta(z))\Big] When D rejects x'(D(x') \ll 0),w_{\textrm{sat}}(x') \approx e^{D(x')} \to 0.
Non-saturating loss(\min_\theta -\mathbb{E}_z[\log \sigma(D(x'))]):\nabla_\theta \mathcal{L}_{\textrm{ns}} = -\mathbb{E}_z\Big[\underbrace{\sigma(-D(x'))}_{w_{\textrm{ns}}(x')}\,\nabla_\theta D(G_\theta(z))\Big] For rejected samples, w_{\textrm{ns}}(x') \to 1(w_{\textrm{ns}}/w_{\textrm{sat}} = e^{-D(x')}, giving 20\times more weight at D = -3 and 148\times at D = -5).
Envelope-theorem identity: Using -\log\sigma(D) = -D - \log\sigma(-D) at D = \lambda = \log(p/q), the non-saturating generator loss descends the softened reverse KL2\,D_{\textrm{KL}}(m \,\|\, p).
Asymmetric penalty: Spurious samples (q > 0 where p = 0) incur infinite cost (m\log(m/0) = \infty), whereas dropped data modes (q = 0 where p > 0) contribute only a finite integrand \tfrac{p}{2}\log\tfrac{1}{2}, so dropping one of two modes costs just \approx 0.26 nats.
Mode Dropping: Why Losing Half the Data Is Cheap
Failure Mode Analysis
Dropping 1 of 2 equal modes (q = 2p on mode 1, q = 0 on mode 2):
Maximum likelihood D_{\textrm{KL}}(p \,\|\, q) = \infty strictly forbids dropping a mode.
Non-saturating GAN charges only 2\,D_{\textrm{KL}}(m \,\|\, p) \approx 0.262 nats (and \mathrm{JS} \approx 0.216 nats) to drop half the dataset.
Zero local restoring gradient: On the covered mode, D^\star(x) = \log(p/2p) = -\log 2 is constant across \operatorname{supp}(q), so \nabla_x D^\star(G(z)) = \mathbf{0} provides no pull toward the missing mode.
Implementing Alternating Critic and Generator Steps
Framework Implementation
update_D detaches generated samples so no gradient flows into net_G, while update_G recomputes critic scores after net_D’s half-step and minimizes the non-saturating cross-entropy with target label 1:
def update_D(X, Z, net_D, net_G, trainer_D):"""Update the critic; return its log loss summed over both batches (per sample, the sum of two means: 2 log 2 at equilibrium).""" trainer_D.zero_grad() real_Y = net_D(X)# The generator is the fixed player here: detach its output fake_Y = net_D(net_G(Z).detach()) loss_D = (F.binary_cross_entropy_with_logits( real_Y, torch.ones_like(real_Y), reduction='sum') + F.binary_cross_entropy_with_logits( fake_Y, torch.zeros_like(fake_Y), reduction='sum')) loss_D.backward() trainer_D.step()return loss_D
Implementing Alternating Critic and Generator Steps (cont.)
Framework Implementation
def update_G(Z, net_D, net_G, trainer_G):"""Update the generator on the non-saturating loss; return its sum.""" trainer_G.zero_grad()# net_D changed in its half-step, so recompute the scores fake_Y = net_D(net_G(Z)) loss_G = F.binary_cross_entropy_with_logits( fake_Y, torch.ones_like(fake_Y), reduction='sum') loss_G.backward() # also fills net_D's .grad (update_D zeroes it) trainer_G.step()return loss_G
The Alternating GAN Training Loop
Training Infrastructure
train_gan alternates update_D and step_G across minibatches using Adam with reduced momentum \beta_1 = 0.5 (Radford et al., 2015) so first-moment estimates adapt quickly to the changing opponent:
def train_gan(net_D, net_G, data_iter, num_epochs, latent_dim, lr_D, lr_G, step_G=update_G, seed=None, on_epoch=None, ema=None):"""Alternate update_D and step_G over the minibatches with Adam (beta_1 = 0.5), calling ema.update(net_G) after every generator step and on_epoch(epoch) after each epoch if given; return each epoch's per-sample losses (loss_D, the sum of the critic's two batch means, and loss_G)."""if seed isnotNone: torch.manual_seed(seed) trainer_D = torch.optim.Adam(net_D.parameters(), lr=lr_D, betas=(0.5, 0.999)) trainer_G = torch.optim.Adam(net_G.parameters(), lr=lr_G, betas=(0.5, 0.999)) history = []
The Alternating GAN Training Loop (cont.)
Training Infrastructure
Each minibatch draws fresh latents, takes one critic step and one generator step, and sums the losses on the device:
for epoch inrange(1, num_epochs +1): loss_D, loss_G, n =0, 0, 0# summed on the device, read oncefor X, *_ in data_iter: # labels, if any, are ignored Z = torch.randn(X.shape[0], latent_dim, device=X.device) loss_D += update_D(X, Z, net_D, net_G, trainer_D).detach() loss_G += step_G(Z, net_D, net_G, trainer_G).detach()if ema isnotNone: ema.update(net_G) n += X.shape[0] history.append(torch.stack([loss_D, loss_G]) / n)if on_epoch isnotNone: on_epoch(epoch)return torch.stack(history).cpu().numpy()
Benchmark 1: Linear Generator on a 2D Tilted Gaussian
Closed-Form Verification
To test our theoretical predictions quantitatively, we generate 1{,}000 points from x = zA + b(z \sim \mathcal{N}(0, I_2)) so p = \mathcal{N}(b, A^\top A) and train a single linear layer G(z) = zA_q + \mu_q:
Exact closed-form Gaussian q: Because G is linear, q = \mathcal{N}(\mu_q, A_q^\top A_q) has an exact mean and covariance at every training step—even though training never evaluates q(x).
Nonlinear critic requirement: Because \Sigma_p \neq \Sigma_q, the true log density ratio \lambda(x) = \log(p(x)/q(x)) is quadratic in x, requiring a 3-layer leaky-ReLU MLP critic (2 \to 16 \to 16 \to 1, slope 0.2).
def make_nets(seed=7):"""The linear generator and the critic, all weights and offsets drawn from N(0, 0.02^2) by a generator seeded with seed.""" gen = torch.Generator().manual_seed(seed) net_G = nn.Sequential(nn.Linear(2, 2)) net_D = nn.Sequential(nn.Linear(2, 16), nn.LeakyReLU(0.2), nn.Linear(16, 16), nn.LeakyReLU(0.2), nn.Linear(16, 1))for w in [*net_G.parameters(), *net_D.parameters()]: nn.init.normal_(w, 0, 0.02, generator=gen)return net_G, net_D
Convergence to Equilibrium on the 2D Gaussian
Empirical Verification
Training for 20 epochs with batch size 8(lr_D = 0.05,lr_G = 0.005 so the critic tracks its best response) brings both losses to their theoretical equilibrium values within 10 epochs:
Equilibrium loss levels: Critic loss -V(D) rises to 2\log 2 \approx 1.386 (random guessing), and generator loss settles to \log 2 \approx 0.693.
Exact fit in nats: Evaluating the closed-form multivariate Gaussian KL divergence confirms that D_{\textrm{KL}}(q \,\|\, p) drops from 7.5\text{--}7.9 nats at initialization to 0.02\text{--}0.06 nats:
KL(q || p) at initialization: 7.501 nats
KL(q || p) after training : 0.021 nats
Does the Trained Critic Recover log(p/q)?
Checking the Density Ratio
Freezing a perturbed generator q(D_{\textrm{KL}}(q \,\|\, p) \approx 3.4 nats) and training a fresh leaky-ReLU critic against it for 2{,}000 steps tests whether D(x) recovers the analytical log density ratio \lambda(x) = \log(p(x)/q(x)):
High accuracy where samples overlap: Across 200 real and 200 generated points, D(x) tracks \lambda(x) with correlation \approx 0.98 and explained variance R^2 > 0.90:
correlation 0.982, R^2 0.962
Why extreme negative tails flatten (\lambda \ll 0): The piecewise-linear leaky-ReLU network extrapolates linearly rather than quadratically into the tails, and once D(x') \ll 0, the critic’s log-loss gradient \sigma(D(x')) \approx e^{D(x')} vanishes.
Saturating vs. Non-Saturating Loss from a Far Start
Controlled Ablation
Shifting the initial generator offset by (-6, 6) places q roughly 8 units from the data (D_{\textrm{KL}}(q \,\|\, p) \approx 345 nats). Running three seeds each under identical minibatches isolates the effect of the generator weight:
start of every run: KL(q || p) = 344.20 nats
non-saturating: final KL(q || p) = 0.03, 0.02, 0.03 nats
saturating: final KL(q || p) = 337.75, 334.37, 336.51 nats
By epoch 2, both critics easily separate the distant clouds (D(x') \ll 0, critic loss \approx 0).
Saturating generator (w_{\textrm{sat}} = \sigma(D(x')) \approx 0): Stalls completely near its starting point (still 335\text{--}340 nats after 20 epochs).
Non-saturating generator (w_{\textrm{ns}} = \sigma(-D(x')) \approx 1): Preserves the leaky-ReLU critic’s spatial slope \nabla_x D(x') and converges to within a few hundredths of a nat.
Scaling Up: MLP GAN on Fashion-MNIST Images
High-Dimensional Synthesis
On 60{,}000 Fashion-MNIST images (28 \times 28 = 784 pixels scaled to [-1, 1]), we train leaky-ReLU MLPs (G:100 \to 256 \to 512 \to 784 with \tanh; D: 784 \to 512 \to 256 \to 1) for 20 epochs (Adam \text{lr} = 2 \times 10^{-4}, \beta_1 = 0.5, batch size 64):
Visual quality: The MLP generator captures recognizable garment silhouettes (trousers, shirts, shoes, bags), though with grainy pixel textures because dense layers ignore 2D spatial locality.
Persistent gap from equilibrium: After 20 epochs, the critic loss (\sim 1.05) remains below 2\log 2 \approx 1.39 and the generator loss (\sim 1.4) above \log 2 \approx 0.69.
Diagnostic ambiguity: Without closed-form densities, loss curves alone cannot tell imperfect generation apart from critic memorization or dropped garment classes.
Concept Check: Optimal Critics and Gradient Weights
Check Your Understanding
Test your understanding of the classic minimax GAN analysis:
Gradient weight ratio: A generated sample receives discriminator logit D(x') = -5. By what factor is its per-sample gradient weight larger under the non-saturating loss than under the saturating minimax loss?
Reading an equilibrium critic loss: At the end of a training run, the discriminator loss reads 2\log 2 \approx 1.386. Does this certify that the generator distribution q matches the data distribution p?
Saturating critic hidden units: If you replace the critic’s leaky-ReLU activations with \tanh units on the far-start Gaussian problem, why does even the non-saturating generator stall?
Answers:
The weight ratio is \frac{w_{\textrm{ns}}(x')}{w_{\textrm{sat}}(x')} = \frac{\sigma(-D(x'))}{\sigma(D(x'))}= e^{-D(x')} = e^5 \approx \mathbf{148.4\times} (and e^3 \approx 20.1\times at D(x') = -3).
No. Any constant zero critic D(x) = 0 (e.g., an under-trained, dead, or heavily penalized critic) achieves loss 2\log 2 regardless of how far q is from p. You must evaluate samples or feature distances directly.
The non-saturating weight w_{\textrm{ns}}(x') = \sigma(-D(x')) \approx 1 only rescales the spatial gradient \nabla_\theta D(G_\theta(z)). If the critic’s internal \tanh hidden units saturate at \pm 1, then \nabla_x D(x') \approx \mathbf{0} and 1 \times \mathbf{0} = \mathbf{0}.