How to train a sampler that has no density: a classifier learns to tell its samples from real data, the generator learns to fool it, and the game minimizes the Jensen–Shannon divergence.
Take a network that turns Gaussian noise into 64×64 images. You can draw samples and score them, but not compute the probability of a training image: that is an integral over all noise vectors that map near it, with no closed form. How do you train it without maximum likelihood?
A two-sample test decides from two sets of samples whether they come from the same distribution. In high dimension no fixed statistic is sharp enough, so learn one: a classifier that tells real images from generated ones. Where it beats chance shows where the generator is wrong; if the generator matches the data, no classifier beats a coin. A generative adversarial network (GAN) trains the sampler against such a classifier (Goodfellow et al., 2014).
Likelihood and sample quality can disagree anyway. A model that puts weight 0.01 on the true density and 0.99 on noise loses at most ln100≈4.6 nats per image: the logarithm is increasing, so ln(0.01p+0.99q)≥ln(0.01p)=lnp−ln100. The log-likelihood of an image grows with its number of pixels, so in high dimension this loss is negligible, yet 99 samples in 100 are noise (CS236, lecture 9).
Sample noise z from a simple prior pz, such as a standard Gaussian, and pass it through the generatorG, a network with parameters θg. The outputs G(z) have some distribution pg on image space. The discriminatorD, with parameters θd, receives either a generated sample, labelled y=0, or a data point x∼pdata, labelled y=1, and outputs D(x)∈(0,1), the probability that its input is real.
Figure
The GAN game as a picture
Noise z passes through the generator G; its outputs G(z), with distribution p_g, reach the discriminator D with the label y = 0, and real data x ~ p_data with the label y = 1. D outputs the probability that its input is real. The small plots sketch the noise, generator and data densities.
The generator never sees a training image; its only signal is the gradient of the discriminator’s output. The model is implicit: it defines pg by a sampling procedure and never writes down a density.
The discriminator wants D(x) near 1 on real data and D(G(z)) near 0 on fakes. The generator wants the opposite on its fakes. Both goals are measured by one value function
which the discriminator maximizes and the generator minimizes: the game is minGmaxDV(G,D).
Where the value function comes from: binary cross-entropy#
The discriminator is a binary classifier, so its natural loss is the binary cross-entropy between a label y and a prediction y^:
H(y,y^)=−[ylny^+(1−y)ln(1−y^)].
A real sample has y=1 and costs −lnD(x). A fake has y=0 and costs −ln(1−D(G(z))). In a stream with as many real samples as fakes, each kind has weight 21, so by linearity of expectation the mean loss is
The two networks take turns, each step on a minibatch of size m (Goodfellow et al., 2014, Algorithm 1).
Fix G. Draw real samples x(1),…,x(m) and noise z(1),…,z(m), and take a gradient ascent step on θd along
∇θdm1i=1∑m[lnD(x(i))+ln(1−D(G(z(i))))].
Fix D. Draw fresh noise and take a gradient descent step on θg along
∇θgm1i=1∑mln(1−D(G(z(i)))).
The generator’s step drops the first term because lnD(x) on real data does not depend on θg. Step 1 can be repeated k times per generator step; the original paper used k=1 (see the balance section).
Global optimality: the generator matches the data#
Why should this game end with pg=pdata? The argument has two steps. It assumes that both distributions have densities on the same space and that D can be any function (Goodfellow et al., 2014, Section 4).
Step 1: the optimal discriminator for a fixed generator#
The generated samples x=G(z) have density pg, so the second expectation can be taken over x∼pg:
V(G,D)=∫[pdata(x)lnD(x)+pg(x)ln(1−D(x))]dx.
D can take any value at every x, so we maximize the integrand pointwise. Write a=pdata(x), b=pg(x) and s=D(x). For a,b>0,
f(s)f′(s)s∗=alns+bln(1−s),=sa−1−sb=0,=a+ba.
The second derivative, −a/s2−b/(1−s)2, is negative, so s∗ is the unique maximum. Where only one density is positive, f is monotone and the same formula gives the endpoint, s∗=1 or 0; where both vanish, D does not matter.
Figure
Each point x is a one-variable maximization
With a = p_data(x) and b = p_g(x) fixed, a ln s + b ln(1 − s) is concave in s = D(x) and peaks at s* = a / (a + b). Solid: a = 0.6, b = 0.3, so s* = 2/3 and the maximum is −0.573. Dashed: a = b = 0.45, so s* = ½ and the maximum is −0.624.
For a fixed generator the best discriminator is therefore
DG∗(x)=pdata(x)+pg(x)pdata(x).
It is the posterior probability of “real” when real and fake samples are equally likely a priori.
Figure
The optimal discriminator compares the two densities
D*(x) = p_data(x) / (p_data(x) + p_g(x)) is close to 1 where only real data live, close to 0 where only generated samples live, and ½ where the densities are equal (in the plotted range, at x ≈ 0.90). Densities: p_data = 0.6·N(−1.5, 0.6²) + 0.4·N(0.6, 0.5²), p_g = N(1.8, 0.85²).
Step 2: substitute the optimal discriminator and recognize JS#
Put DG∗ back into V, using 1−DG∗=pg/(pdata+pg):
The Jensen–Shannon divergence compares each distribution with the mixture m=21(pdata+pg). To bring it in, write each denominator as 2m and pull out the 2, which costs ln2 per expectation:
The second line is the definition of KL, and the third the definition of JS, DJS(p∥q)=21DKL(p∥m)+21DKL(q∥m), multiplied by 2.
Against an optimal discriminator, the generator minimizes the Jensen–Shannon divergence. DJS≥0, with equality only when the two densities coincide, so the unique minimum is
GminC(G)=−2ln2≈−1.386at pg=pdata,
where D∗=21 everywhere. For the two densities of the figure, DJS≈0.430 nats and C(G)≈−0.526.
Let pdata and pg live on disjoint sets. Then D∗=1 on the data and 0 on the fakes, DJS=ln2 and C(G)=0, wherever pg sits. Moving the generator closer to the data, without overlap, does not change C at all.
The generator’s gradient is ∇xD at its samples, sent back through G. Disjoint compact supports lie a distance δ>0 apart. A smooth function equal to 1 within δ/3 of the data and 0 within δ/3 of the fakes makes both logarithms in V zero, their maximum, so it is an optimal discriminator; it is constant around every fake, so its gradient there is zero, and so is the generator’s (Arjovsky and Bottou, 2017, Theorem 2.1; Theorem 2.2 extends it to manifolds that do not align).
This is the usual case. A generator built from affine maps and ReLU-type or smooth increasing activations maps its noise into a countable union of manifolds of dimension at most dimz, which has zero volume when dimz is below the number of pixels (Arjovsky and Bottou, 2017, Lemma 1). Natural images are believed to concentrate near a low-dimensional set too. After an arbitrarily small random shift, two such sets meet, if at all, in a lower-dimensional set that carries no mass (Lemmas 2 and 3), as two curves in three-dimensional space miss each other. The fitting note saw the same saturation of JS in one dimension; the Wasserstein GAN replaces JS with a distance that keeps a slope.
Red: data density p_data; blue: generator density p_g; green: discriminator output D(x). A discriminator step moves D towards D* = p_data / (p_data + p_g); a generator step moves p_g towards where D is high (dashed blue in panel 3: p_g before the step). At equilibrium p_g = p_data and D = ½. Curves computed from explicit densities.
Watch the discriminator curve. Each D step makes it high over the data and low over the fakes; each G step pushes the fakes up its slope. When the two densities coincide, the curve is flat at 21.
The picture assumes an optimal D before every generator step and unlimited capacity. Real networks, updated a few steps at a time, can oscillate or settle on a few modes (Goodfellow, 2016).
The minimax generator loss Ezln(1−D(G(z))) is rarely used. Already the original paper trains the generator to maximize lnD(G(z)) instead, that is, to minimize the non-saturating loss
LG=−EzlnD(G(z)).
Why change it? Early in training D rejects fakes confidently, d=D(G(z))≈0. Compare the slopes of the two losses in d:
∂d∂ln(1−d)∂d∂(−lnd)=−1−d1≈−1,=−d1→−∞.
At d=0.05 the slopes are −1.05 and −20. Through the logit ℓ, with d=σ(ℓ) and ∂d/∂ℓ=d(1−d), the minimax loss has slope −d, which vanishes as D grows confident, and the non-saturating loss −(1−d), largest there: the minimax loss gives the weakest signal to the worst generator.
Figure
Saturating and non-saturating generator losses
Top: both losses fall as d = D(G(z)) grows. At d = 0.05 the minimax loss ln(1 − d) has slope −1.05 and −ln d has slope −20. Bottom: the same losses against the logit ℓ, d = σ(ℓ), the path the gradient takes into the networks: ln(1 − σ(ℓ)) saturates with slope −d = −0.05, while −ln σ(ℓ) keeps slope −(1 − d) = −0.95.
Both losses share the fixed point pg=pdata, but the non-saturating loss is no longer the minimax game. With D=D∗ computed for the current generator and held fixed, its expected gradient is the gradient of DKL(pg∥pdata)−2DJS(pdata∥pg) (Arjovsky and Bottou, 2017, Theorem 2.5), derived below. The first term, a reverse KL, punishes fakes where the data have little mass and barely punishes missed data modes, one reason for dropped modes.
Derivation
Let pθ be the generator’s density, θ0 the current parameters and D∗=pdata/(pdata+pθ0), frozen. Assume pθ is differentiable in θ, that ∇θ and ∫ can be swapped, and that pdata>0 wherever pθ>0. Two facts do the work. For a fixed function h, Ezh(Gθ(z))=∫pθh, so its gradient is ∫∇pθh. And ∫∇pθ=∇1=0, so constants added to h drop out.
Each divergence is ∫ϕ(pθ(x))dx for a function ϕ of the value p=pθ(x), so its gradient is ∫ϕ′(pθ)∇pθdx by the chain rule. With a=pdata(x):
The last line is the first fact read backwards. The second line also shows that the minimax loss Ezln(1−D∗(Gθ(z))) has the gradient of 2DJS, as Step 2 says.
The non-saturating loss also leaves the disjoint-support problem in place. Near a perfect discriminator D(G(z))≈0, and the gradient −∇xD/D divides one small error by another. If the errors of D and of ∇xD are independent zero-mean Gaussian noise, the ratio has a Cauchy distribution, which has no mean and no variance (Arjovsky and Bottou, 2017, Theorem 2.6). The updates become noisy instead of vanishing.
where softplus(t)=ln(1+et) is evaluated stably as max(t,0)+ln(1+e−∣t∣), the two-term log-sum-exp. The discriminator then minimizes Exsoftplus(−ℓ(x))+Ezsoftplus(ℓ(G(z))) and the generator Ezsoftplus(−ℓ(G(z))).
Computing σ first fails where the discriminator is confident: in 32-bit floating pointσ(ℓ) rounds to 1 once ℓ exceeds about 17, so ln(1−σ(ℓ))=−∞ where softplus gives about −17. PyTorch provides the stable form as binary_cross_entropy_with_logits.
strided convolutions instead of pooling, transposed convolutions to upsample;
batch normalization in both networks, except at the generator’s output and the discriminator’s input;
no fully connected hidden layers: the noise is reshaped into a 4×4 map with 1024 channels;
ReLU in the generator, Tanh at its output, images scaled to [−1,1];
LeakyReLU with slope 0.2 in the discriminator.
Training used Adam with learning rate 2⋅10−4 and β1=0.5 (the usual 0.9 oscillated), minibatches of 128 and weights from N(0,0.022).
The rules keep the gradient signal dense: max-pooling passes gradient to one input per window and ReLU none for negative inputs, while strided convolutions and LeakyReLU pass some everywhere. Batch normalization let deep generators start learning without collapsing all samples to one point. Later models upsample by resizing and a convolution, which avoids checkerboard artifacts.
The discriminator is the generator’s only source of gradient, so the two must improve at comparable speeds, tuned by k, the learning rates and the capacities. A discriminator that rejects every fake leaves the generator vanishing or noisy gradients: weaken it. One that lags points the generator in poor directions: update it more often. The WGAN makes a strong critic help instead.
The losses say little about sample quality: track samples from fixed noise vectors and an FID, where a collapse shows first. Gradient-norm clipping guards against explosive updates.
One-sided label smoothing trains the discriminator toward 0.9 instead of 1 on real samples (Salimans et al., 2016). Why only the real side? With targets α for real and β for fake samples, the pointwise integrand of Step 1 becomes Alns+Bln(1−s) with A=αpdata+βpg and B=(1−α)pdata+(1−β)pg, maximized at A/(A+B):
D∗(x)=pdata(x)+pg(x)αpdata(x)+βpg(x).
Look at a region where the generator puts much more mass than the data, with r=pdata/pg small. To first order in r, D∗≈β+(α−β)r, and the non-saturating loss is
−lnD∗−lnD∗≈−lnα−lnr≈−lnβ−βα−βrβ=0,β>0.
With β=0 the loss follows the log density ratio, and its gradient does not fade as r shrinks. With β>0 the gradient carries the factor r, so fakes far from the data barely move. Hence only the real label is smoothed.
Random label flipping of a fraction ε of the labels is, in expectation, two-sided smoothing with α=1−ε, β=ε (cross-entropy is linear in the target), so it is used sparingly.
In mode collapse the generator maps most of its noise to a few outputs the current discriminator accepts. The discriminator judges each sample on its own, so nothing tells the outputs to differ (Salimans et al., 2016); when it rejects the collapsed mode, the generator moves to another. The reverse-KL term makes dropping a mode cheap.
Take data from eight Gaussians of standard deviation 0.02 on a circle. A standard GAN puts almost all its mass on one mode at a time and rotates from mode to mode, never covering all eight (Metz et al., 2017). Nearly every sample lies on a real mode while one mode in eight is covered: precision near 1, recall near 1/8 (toy values). FID penalizes the missing modes; each sample alone looks perfect.
Minibatch discrimination lets the discriminator compare samples within a batch (Salimans et al., 2016). A learned tensor maps a feature vector f(xi) to a matrix Mi with rows Mi,b, giving the features
The vector o(xi) is appended to f(xi); a collapsed batch has large o, which the discriminator learns to reject.
Unrolled GANs let the generator anticipate the discriminator’s reply (Metz et al., 2017). Starting from the current θD, take K ascent steps of the discriminator and score the generator against the result:
The generator descends VK through the K steps; the discriminator is updated with V. By the chain rule,
dθGdVK=∂θG∂V+∂θDK∂VdθGdθDK.
The first term alone favours putting all mass on the point D likes most; the second sees that the discriminator would reject such a collapse. K=0 is the standard GAN; with K=10 the eight-Gaussian generator covers all modes. A buffer of earlier fakes, cheaper, keeps an abandoned mode punished.
A conditional GAN (Mirza and Osindero, 2014) gives both networks a label c, such as a class. The generator produces G(z,c) and the discriminator judges pairs D(x,c):
where pc is the label distribution of the data. Generated pairs have the joint pc(c)pg(x∣c), and the optimality argument applied to pairs gives pg(x,c)=pdata(x,c): a realistic image with the wrong label can be rejected, so the generator follows the label, as in the conditional VAE.
with f convex, lower semicontinuous and f(1)=0; f(u)=ulnu gives DKL(P∥Q). The tool is the convex conjugatef∗(t)=supu{ut−f(u)}. By definition f(u)≥tu−f∗(t) for every t: each line of slope t and intercept −f∗(t) lies below f. For a convex, lower semicontinuous f these lines recover it, f(u)=supt{tu−f∗(t)}, the Fenchel–Moreau theorem (Boyd and Vandenberghe, 2004, Section 3.3.2 and Exercise 3.39). For the differentiable f of the table below, two lines prove it. The inequality gives supt{tu−f∗(t)}≤f(u). The tangent at u, of slope tu=f′(u), lies below f and touches it at u, so the supremum defining f∗(tu) is attained at u: f∗(tu)=tuu−f(u), and the slope tu reaches f(u). For example, f(u)=21(u−1)2 has its supremum at u=1+t, so f∗(t)=t+21t2.
Figure
The convex conjugate read off a tangent line
A convex f(u) = ½(u − 1)² (blue) and slope t = 1. The tangent with slope t (amber) touches f at u* = 2, where f′(u*) = t; its intercept is −f*(t) = −1.5. Equivalently, f*(t) is the largest vertical gap between the line t·u (dashed) and f, reached at the same u* (green).
Substitute this at every point, with u=p(x)/q(x) and a slope T(x) that may depend on x:
The second line chooses the slope at each point; nothing is lost, because T(x)=f′(u(x)) attains every pointwise supremum at once (Nguyen, Wainwright and Jordan, 2010). The inequality comes from restricting T to a network family T. With P=pdata and Q=pg, the last line is a two-player game that needs only samples.
A fixed increasing output activationgf maps the network’s unconstrained output v(x) into the domain of f∗, T(x)=gf(v(x)). The usual choices, with P the data:
Divergence
f(u)
gf(v)
f∗(t)
DKL(P∥Q)
ulnu
v
et−1
DKL(Q∥P)
−lnu
−e−v
−1−ln(−t), t<0
Pearson χ2
(u−1)2
v
t+t2/4
squared Hellinger
(u−1)2
1−e−v
t/(1−t), t<1
2DJS
ulnu−(u+1)ln2u+1
ln2−ln(1+e−v)
−ln(2−et), t<ln2
GAN
ulnu−(u+1)ln(u+1)
−ln(1+e−v)
−ln(1−et), t<0
The GAN row has f(1)=−ln4, so its divergence is 2DJS−ln4; with T=lnD the bound is the value function V(G,D). The fifth row differs from it by a constant and trains the same way.
Evaluate the composition f∗(gf(v)) in one piece, as with softplus above. Row by row it is ev−1, v−1, v+v2/4, ev−1, softplus(v)−ln2 and softplus(v).
Optional depth: a squared-error discriminator and the divergence it minimizes. The rest of the note does not depend on it.
The least-squares GAN (LSGAN) also repairs the gradient for fakes the discriminator already accepts that are still far from the data (Mao et al., 2017). Its discriminator regresses toward b on real samples and a on fakes, and the generator asks for the score c:
With a sigmoid cross-entropy, a fake far on the real side of the boundary has almost no gradient: the slope of −lnσ(ℓ) is −(1−σ(ℓ))→0. The squared loss is flat only at D=c, so a fake scored beyond c is pulled back toward the level set D=c, which helps if that set runs through the data.
Figure
Least squares pull far-away fakes back
Top: real data N(1, 1), red, and fakes N(−1, 1), blue; a BCE discriminator with logit 2x and a least-squares one, D(x) = 0.25x + 0.5, share the boundary x = 0. Bottom: the update −∂L_G/∂x each generator loss gives a fake at x, scaled to 1 at x = −1. A fake at x = 4 gets 0.0004 from BCE and −0.67 from least squares, back toward x = 2.
The optimal discriminator. For a fixed generator the integrand 21pdata(D−b)2+21pg(D−a)2 is a parabola in D, minimized at
D∗(x)=pdata(x)+pg(x)bpdata(x)+apg(x).
Add 21Epdata[(D(x)−c)2] to the generator’s loss; it does not depend on G. At D=D∗ the extended loss is
Choose b−c=1 and b−a=2, for example a=−1, b=1, c=0. The numerator becomes (pdata−pg)2=4(m−pg)2 and the denominator 2m, with m=21(pdata+pg):
C(G)=∫m(x)(pg(x)−m(x))2dx=χPearson2(pg∥m).
Like the JS identity, it compares the generator with the mixture, here through χ2. The 0–1 coding misses these conditions, yet its 2C(G)=∫φ(pg(x))dx, with φ(q)=q2/(pdata(x)+q), is still minimized at pg=pdata among densities. The constraint ∫pg=1 is needed: without it pg=0 would give 0. At each x, φ′′(q)=2pdata2/(pdata+q)3>0, so φ is convex, and φ′(pdata)=43 at every x. The tangent bound then gives
A GAN samples with one forward pass, and nothing in its loss averages plausible images into a blur. The price is what the game never computes: without a density, models are compared on samples, with FID and precision and recall; without an encoder, the code of an image needs an optimization over z or a second network, as in the autoencoding GANs.
For images, realism often counts for more than variety. For molecules in drug discovery, variety is the point, and a likelihood-trained model such as the VAE, whose loss charges every underweighted mode, is the safer choice (BMML lecture notes, 2026), though not a guarantee, as the next section shows.
The failures row is typical behaviour, not theorems. Blur comes from a fixed-variance Gaussian decoder: its squared error is minimized by the average of the images compatible with z. Mode collapse is a failure of the optimization: at the global optimum of the game, pg=pdata covers every mode.
Nor does a VAE guarantee coverage: its forward KL charges an underweighted mode only in proportion to the mode’s mass. Let the data put mass 0.05 on one mode and 0.95 on the rest, on disjoint regions, and the model fit each region exactly but give the rare mode 0.005. The density ratio is constant on each region, and
per sample, invisible next to a log-likelihood of thousands of nats. The ELBO is also only a bound, so training maximizes the bound, not the likelihood.
The GANs notebook of the HSE-LAMBDA Deep Generative Models course trains three models; cells are counted from 1, markdown included. It has no saved outputs, so it documents procedures only.
Unconditional GAN on MNIST zeros (cells 4–16: data in 4–6, the model and its training from 7). Images at 32×32, resize-convolution upsampling, BCE with logits, one-sided smoothing 0.9 (also the generator’s target, so its loss is minimized at D(G(z))=0.9), clipping at 1, one D step per G step; noise scaled by 0.7 at sampling.
Conditional GAN on CIFAR-100 (cells 17–26). The label enters each network as a learned extra channel; Adam with β1=0.5 for both.
f-GAN (cells 27–33). The table’s activations and conjugates, trained with JS and applied one after the other with plain exp and log: in 32-bit floats a logit above about 17 rounds 2−et to 0 and the loss on that fake to +∞ (at v=16 it already gives 15.25 instead of 15.31). The composed softplus forms avoid this.
JS gives no slope whenever the two distributions do not overlap, however close. The next note replaces it with the Wasserstein distance, which shrinks steadily as the samples approach the data, and asks what constraint the discriminator then needs.
I. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D. Warde-Farley, S. Ozair, A. Courville, Y. Bengio. Generative adversarial nets. NeurIPS, 2014. Algorithm 1; Section 3 (the non-saturating loss); Section 4 (optimal discriminator and global optimum).
M. Arjovsky, L. Bottou. Towards principled methods for training generative adversarial networks. ICLR, 2017. Lemmas 1–3 (the generator’s image has zero volume; perturbed manifolds meet in lower dimension), Theorems 2.1–2.2 (a perfect, locally constant discriminator), Theorem 2.5 (the gradient of the non-saturating loss), Theorem 2.6 (Cauchy-distributed updates).
T. Salimans, I. Goodfellow, W. Zaremba, V. Cheung, A. Radford, X. Chen. Improved techniques for training GANs. NeurIPS, 2016. Sections 3.2–3.4: minibatch discrimination, historical averaging, one-sided label smoothing.
L. Metz, B. Poole, D. Pfau, J. Sohl-Dickstein. Unrolled generative adversarial networks. ICLR, 2017. Section 2 (the unrolled objective), Section 3.1 and Figure 2 (eight Gaussians on a circle).
S. Boyd, L. Vandenberghe. Convex Optimization. Cambridge University Press, 2004. Section 3.3.2 (the conjugate of the conjugate) and Exercise 3.39(d) (its proof outline).
S. Ermon et al. Stanford CS236: Deep Generative Models. Course notes on GANs and lecture 9: likelihood-free learning, two-sample tests, mode collapse.
R. Isachenko. Deep Generative Models, MIPT and YSDA, 2025. Lecture 5: likelihood-free learning, GAN optimality, mode collapse, the Wasserstein GAN.
BMML team. Байесовские методы в анализе данных (Bayesian methods in data analysis), lecture notes, lectures 1–6, 2026. GitHub repository. Section 6.31: VAE against GAN, realism against diversity for images and molecules.