09 / 33 · GANs
Generative adversarial networks
The GAN as a two-player minimax game, its value function read as a binary cross-entropy, the alternating training loop, the optimal discriminator, the Jensen–Shannon identity behind the global optimum, why practice uses the non-saturating generator loss computed from logits, the practical rules that make training work (DCGAN architecture, balancing the players, label smoothing, remedies for mode collapse), and the conditional, f-GAN and least-squares extensions.
Entropy, cross-entropy and KL divergence · Binary cross-entropy · Expectation
On this page 12
The VAE trains its generator through a bound on the likelihood and pays for it with blurry samples. A generative adversarial network (GAN) avoids likelihoods altogether (Goodfellow et al., 2014). The generator is a network that turns noise into samples, and it is trained only through a second network, the discriminator, which tries to tell generated samples from real ones. The model is implicit: we can sample from it, but we cannot evaluate its density.
Two facts organize this note; the rest shows where they come from.
- If the discriminator is optimal, the generator’s objective becomes the Jensen–Shannon divergence in disguise: . Training the generator then means minimizing .
- If the supports of the two distributions do not overlap and the discriminator is (near-)optimal, the minimax generator loss gives no useful gradient: JS is stuck at its maximum wherever sits, and the optimal discriminator is constant around the generated samples.
Notation. is the data density, the noise prior, the generator with parameters , the density of the generated samples , and the discriminator with parameters ; is the probability that is real, with . A network with a sigmoid output takes values in and can only approach the endpoints. Logarithms are natural.
Reading route. A first pass follows the game, the alternating updates, the optimal discriminator and its JS identity, the non-saturating loss computed from logits, mode collapse, and then the Wasserstein GAN. The f-GAN and least-squares extensions are optional depth.
The setup#
Sample noise , for example a standard Gaussian, and pass it through the generator. The output is a generated sample, and its distribution is . The discriminator receives either a generated sample, labelled (fake), or a data point , labelled (real), and outputs the probability that its input is real.
The GAN game as a picture
The generator never sees real data directly. It learns only through the discriminator’s output, and the discriminator learns to separate the two streams.
A minimax game#
The two networks play a minimax game: the discriminator maximizes its success, and the generator minimizes the discriminator’s success. Success is measured by the value function
and the game is .
The discriminator wants close to on real data and close to on fakes; both make larger. The generator wants close to , which makes the second term very negative.
Where the value function comes from: binary cross-entropy#
The discriminator is a binary classifier, so start from the binary cross-entropy between a label and a prediction :
- For a real sample, , and .
- For a fake sample, , and .
For one real and one fake sample the total is . Averaging over many such pairs turns the sums into expectations:
which for continuous distributions reads
This is exactly . So is the negative binary cross-entropy of the discriminator: maximizing over is the same as training as an ordinary classifier with a BCE loss. The two terms have equal weight because the classifier sees real and fake samples in equal proportion, a class prior of . With other proportions both and the optimal discriminator below change.
How to optimize: alternate the players#
The two players take turns, each with a minibatch of size (Goodfellow et al., 2014, Algorithm 1).
- Fix . Take real samples and noise samples , and update by gradient ascent along
- Fix . Take fresh noise samples and update by gradient descent along
The generator step uses only the second term because the first term does not depend on : involves real data and only, so its gradient with respect to is zero. Step 1 may be repeated times per generator step; the original paper used . How to choose is discussed under balancing the two players.
Global optimality: the generator matches the data#
The game is won when the generator’s distribution equals the data distribution. The proof has two steps (Goodfellow et al., 2014, Proposition 1 and Theorem 1).
Step 1: the optimal discriminator for a fixed generator#
As in Goodfellow et al. (2014), Section 4, we assume that both distributions have densities on the same space and that can be any function (infinite capacity). When the first assumption fails, and the paragraph on non-overlapping supports below covers that case.
Rewrite the second expectation over generated samples: has density , so . Then, for fixed ,
can be chosen freely at every , so the integrand can be maximized pointwise. Write , and . If , the function on has
so is the unique maximum, and it lies inside . If exactly one density vanishes, is monotone on and its maximum sits at an endpoint: where (only data) and where (only fakes). The formula gives these values too; a sigmoid output can only approach them. Where both densities vanish, does not matter (Goodfellow et al., 2014, Proposition 1).
Each point x is a one-variable maximization
Hence, for a fixed generator, the best discriminator is
The optimal discriminator compares the two densities
Step 2: substitute the optimal discriminator and recognize JS#
Plug back into . Since ,
The Jensen–Shannon divergence (defined here) compares each distribution with the mixture . Written with expectations,
To make the denominators match, divide each by inside the logarithm and pay for each expectation, because . With ,
that is,
Since , with equality only when , the minimum over is reached only at :
where everywhere. For the two densities in the optimal-discriminator figure, nats and , computed by numerical integration both from the definition of and from the JS formula.
This also explains the warning about non-overlapping supports. If and live on disjoint sets, then on the data and on the fakes, and , no matter where exactly sits. So is flat in the generator’s parameters. Backpropagation, however, does not differentiate : it sends the gradient of through a fixed , and that gradient contains at the generated samples. When the supports are disjoint compact sets, or manifolds that do not perfectly align, there is an optimal discriminator that equals on a whole neighbourhood of the generated samples, so there and the generator’s gradient vanishes (Arjovsky and Bottou, 2017, Theorems 2.1–2.2). For a discriminator within of , in value and gradient, the gradient norm is at most , where bounds the generator’s Jacobian (Theorem 2.4).
This is not an exotic case. A generator built from affine maps and pointwise nonlinearities maps into a countable union of manifolds of dimension at most (Lemma 1), and natural images are believed to concentrate near a low-dimensional manifold. Two such manifolds almost never overlap on a set of positive measure: they may cross, but only on a lower-dimensional set (Lemmas 2–3). So a perfect discriminator exists and however close the two manifolds are (Theorems 2.2–2.3). It is the same saturation of JS that the fitting note observed in one dimension. The WGAN note replaces JS with the Wasserstein-1 distance to fix it.
Training as a picture#
How the two players move during training
- At the beginning, is far from and the discriminator is arbitrary.
- After updating , approaches : high over the data, low over the generated samples.
- After updating , the gradient of guides towards regions that classifies as data, so moves towards .
- Finally, and the discriminator cannot tell them apart: .
The picture is idealized. The theory assumes that reaches its optimum after every generator step and that both players can represent any function. In practice both are networks trained a few steps at a time, and the alternating updates can oscillate or collapse onto a few modes of the data (mode collapse) instead of converging (Goodfellow, 2016, Section 5.1.1). The remedies are collected under mode collapse and how to fight it.
Which generator loss is used in practice?#
The minimax loss for the generator, , is rarely minimized directly. Already the original paper recommends (Goodfellow et al., 2014, Section 3) training the generator to maximize instead, that is, to minimize
the non-saturating loss. In code this is the BCE of the discriminator’s output on generated samples with the “real” label.
The problem with the minimax loss. When is good, it rejects fakes confidently: . Then . A small value does not by itself mean a small gradient; what matters is the slope of the loss with respect to , and further back through the network:
At the slopes are and . The discriminator ends in a sigmoid, , and . Per logit the gradients are therefore for the minimax loss and for the non-saturating one. The minimax loss saturates at the logit, which is where the gradient enters the network: its gradient vanishes exactly when the generator is worst, while the non-saturating gradient is largest there.
Saturating and non-saturating generator losses
Both losses decrease as grows, so they push the generator in the same direction, and for the optimal discriminator they share the fixed point (Goodfellow et al., 2014, Section 3). The non-saturating version is no longer the minimax game exactly. With , its expected gradient equals the gradient of (Arjovsky and Bottou, 2017, Theorem 2.5). The first term is a reverse KL: it punishes fake-looking samples heavily and missing modes only lightly, one explanation for mode dropping. The non-saturating loss fixes the weak gradients early in training, but not the disjoint-support problem of the previous section: if the discriminator’s error around is modelled as independent noise, its updates become unstable rather than vanishing, with infinite variance (Theorem 2.6).
Computing the losses from logits#
The discriminator network ends in a logit , and . Both logarithms in the losses are functions of that never need itself:
with . The first line is , and the second uses . Softplus is evaluated as , so the exponential never overflows. The discriminator’s loss becomes and the non-saturating generator loss .
Computing first and the logarithm afterwards fails exactly where the discriminator is confident. In 32-bit floating point, rounds to exactly once exceeds about 17, so returns where the softplus form returns about , and no gradient passes through the rounded sigmoid. Deep-learning libraries provide the stable form as binary cross-entropy with logits (binary_cross_entropy_with_logits in PyTorch).
Training GANs in practice#
The theory above assumes an optimal discriminator and networks of unlimited capacity. Real GANs are two finite networks trained a few steps at a time, and a set of empirical rules decides whether training works at all. None of them is a theorem; each is given here with the reason it helps.
Architecture: the DCGAN guidelines#
The first convolutional GANs that trained reliably on images followed five rules (Radford, Metz and Chintala, 2016, Section 3):
- No pooling. The discriminator downsamples with strided convolutions and the generator upsamples with fractionally strided (transposed) convolutions, so both networks learn their own resampling.
- Batch normalization in both networks, except at the generator’s output layer and the discriminator’s input layer, where it made the samples oscillate.
- No fully connected hidden layers. The generator’s first layer is a matrix multiplication whose output is reshaped into a small spatial map, with 1024 channels in the paper’s generator. The discriminator’s last convolutional features are flattened into a single sigmoid output.
- ReLU in the generator and a Tanh at its output, so that images lie in , like the training images scaled to that range.
- LeakyReLU in the discriminator, with slope .
The training details became defaults as well (Section 4): Adam with learning rate and , because the usual made training oscillate; minibatches of 128; weights initialized from ; and a 100-dimensional uniform noise vector.
The rules have reasons that earlier notes explain. Strided convolutions and LeakyReLU keep gradients dense: max-pooling sends a gradient to only one input of each window, and a ReLU sends none for negative inputs, while LeakyReLU keeps the slope there (see common remedies for vanishing gradients). Batch normalization was what made deep generators start learning, and it kept them from collapsing all samples to one point (Section 3). Inside the discriminator it also makes each output depend on the statistics of the whole minibatch, a weak form of the minibatch discrimination below (Salimans et al., 2016, Sections 3.2 and 3.5).
Later architectures change some rules but keep their purpose.
- Upsampling. A transposed convolution whose kernel size is not divisible by its stride overlaps unevenly and can leave checkerboard artifacts. Resizing followed by an ordinary convolution avoids the uneven overlap (transposed convolution or upsample + conv?).
- A fully convolutional discriminator. The last layer can be a convolution whose kernel covers the whole remaining feature map, for example on a map, which returns one logit per image without a fully connected layer. Radford et al. found that global average pooling instead increased stability but slowed convergence (Section 3).
- Dropout in the discriminator. Dropping whole feature maps at random, as in the denoising autoencoder, regularizes the discriminator so that it fits the training images less closely.
- The latent code. No theory fixes its size. A code that is too small cannot represent the variety of the data; DCGAN uses 100 dimensions, and 100 to 256 are common. A convolutional generator can also start from a small spatial grid of noise, such as with a few channels, and double the resolution in every block, .
- Sampling from a narrowed prior. Scaling the noise down at sampling time, for example drawing instead of , gives more typical but less varied images. The samples then come from a different distribution than the one the generator was trained on. This prior narrowing is a truncation-like heuristic, often loosely called the truncation trick, which trades recall for precision; strictly, scaling a Gaussian is not sampling a truncated one, which BigGAN does by resampling values beyond a threshold. Any metric computed on such samples measures the modified distribution, so the sampling scale has to be reported with it.
Balancing the two players#
The discriminator is the generator’s only source of gradient, so the two must improve at comparable speeds. The original paper already warns that a generator trained too long against a fixed discriminator maps too many values of to the same (Goodfellow et al., 2014, Section 6). The knobs are the number of discriminator steps per generator step, the two learning rates and the capacity of each network.
- The discriminator saturates: it rejects the fakes with near certainty, and the generator’s gradients shrink. The minimax loss saturates, and with disjoint supports even the optimal discriminator gives no direction. Update the discriminator less often, lower its learning rate, or reduce its capacity.
- The generator struggles, or collapses to a few modes, while the discriminator’s feedback is unstable: the discriminator lags behind and points in poor directions. Update it more often, .
Neither extreme works. Too many discriminator steps make the generator’s gradients vanish; too few leave a discriminator that cannot give meaningful feedback. The next note changes the objective so that a strong critic helps rather than hurts.
Three habits complete the picture. Gradient-norm clipping (common remedies) guards against occasional explosive updates; Nowozin, Cseke and Tomioka found Adam and clipping useful in their largest experiment (2016, Section 3.2). A small architecture or dataset first checks that the pipeline works. And samples should be looked at often: the two losses move against each other and do not measure sample quality, so samples, and later metrics such as the Inception Score, are what reveals a collapse early.
Label smoothing and label flipping#
One-sided label smoothing trains the discriminator against the target instead of on real samples, so that it never becomes fully confident (Salimans et al., 2016, Section 3.4). Why only on real samples? Let the targets be for real and for fake samples. The integrand of Step 1 becomes with and , so its maximum is at :
Look at a region where the generator puts much more mass than the data, so that the ratio is small. There to first order in .
- With , the non-saturating loss follows the log density ratio, and its gradient does not shrink as does.
- With , it is , whose gradient carries the small factor : fakes far from the data barely move.
So only the real label is smoothed. With the optimal output is at most : where the two densities are equal it is instead of .
Random label flipping swaps the labels of a small random fraction of the discriminator’s training examples. The binary cross-entropy is linear in the target , so in expectation flipping replaces the targets and by and . It is two-sided label smoothing with and , plus noise. It keeps the discriminator from becoming overconfident, but by the argument above its fake half weakens the pull on fakes far from the data, so it is used sparingly, if at all.
Mode collapse and how to fight it#
In mode collapse the generator maps most of its noise to a few outputs that the current discriminator accepts. Salimans et al. (2016, Section 3.2) describe the mechanism. The discriminator judges each sample on its own, so its gradient points the same way for all similar samples, and nothing tells the generator’s outputs to differ from each other. When the discriminator learns to reject the collapsed mode, the generator moves to another one, and the two can chase each other indefinitely. The reverse-KL term of the non-saturating loss (above) is a second reason: dropping a mode costs it little. The remedies attack different parts of this mechanism.
- Minibatch discrimination lets the discriminator compare samples (Salimans et al., 2016, Section 3.2). An intermediate feature vector is multiplied by a learned tensor , which gives a matrix . For each of its rows , the closeness of two samples is , and the layer outputs , summed over the minibatch. The vector is concatenated with and fed to the next layer, separately for real and generated minibatches. A collapsed batch contains many near-identical samples and therefore large values of , which the discriminator can learn to reject.
- Unrolled GANs let the generator anticipate the discriminator’s answer (Metz et al., 2017, Sections 2.2–2.4). Write the value function as . Starting from , take gradient-ascent steps of the discriminator, , and define the surrogate . The generator descends , backpropagating through the steps, while the discriminator is still updated with . By the chain rule the gradient of has two terms (Section 2.4): the usual at the unrolled discriminator, and a term through that describes how the discriminator would react to the generator’s move. The first term alone pushes toward a collapse: against a fixed discriminator, the best generator puts all its mass on the single point that the discriminator likes most. The second term sees that a collapsed generator would quickly be rejected, which discourages the collapse. is the standard GAN. If the inner steps converge to an optimal discriminator, approaches the true generator objective ; for a neural discriminator the inner ascent need not converge, or may reach only a local optimum, so a large is an approximation, not a guarantee.
- History. Historical averaging adds to each player’s cost, where are the parameters at past step : a pull toward the average of all past parameters that damps oscillations (Salimans et al., 2016, Section 3.3). Training the discriminator partly on a buffer of samples from earlier generators, half of each discriminator minibatch in Shrivastava et al. (2017), Section 2.3, keeps it from forgetting the modes the generator visited before, so the generator cannot return to them unpunished.
- Several discriminators. GMAN trains the generator against discriminators and combines their values with a softened maximum, from the mean to the maximum as a parameter goes from to (Durugkar, Gemp and Mahadevan, 2017, Section 4.1). The mean is a lenient teacher and the maximum a harsh adversary.
- A different distance. The Wasserstein GAN, with a gradient penalty or spectral normalization on its critic, gives useful gradients even when the supports do not overlap. The original WGAN, trained with weight clipping, showed no evidence of mode collapse in any of its authors’ experiments (Arjovsky, Chintala and Bottou, 2017, Section 4.3).
Extensions#
Conditional GAN#
A conditional GAN (Mirza and Osindero, 2014) gives both networks a label , such as a class: the generator produces and the discriminator judges pairs . Let be the joint distribution of data and labels and its label marginal. The value function becomes
where the second expectation is over and . This is the original game played on pairs : the generated pairs have the joint , and the argument of the previous sections, applied to pairs, shows that the optimum matches the joints, . A realistic image paired with the wrong label lies outside the data joint, so the discriminator can reject it, and the generator learns to follow the condition. It is the GAN counterpart of the conditional VAE.
f-GAN#
Optional depth: the game for any f-divergence through convex conjugates. The rest of the note does not depend on it.
The original GAN minimizes JS. An f-GAN (Nowozin, Cseke and Tomioka, 2016) generalizes the game to any f-divergence
for a convex, lower semicontinuous with ; gives . The key tool is the convex conjugate . Rearranged, its definition says for every : each line with slope and intercept lies below the graph of , and for differentiable the line with touches it at . For convex, lower semicontinuous these lines recover exactly, (the Fenchel–Moreau theorem). For example, , half the Pearson generator, gives : the supremum of is at .
The convex conjugate read off a tangent line
Substitute this representation at every point, with , and let the slope depend on (Nguyen, Wainwright and Jordan, 2010; Nowozin, Cseke and Tomioka, 2016, Section 2.2, Eqs. 4–5):
The second line picks the best slope separately at every point. Over all functions with values in the domain of this loses nothing: for differentiable the supremum is attained at . The inequality appears in the third line, where is restricted to a class , such as a neural network family.
With , and a neural network, the right-hand side is a two-player game: plays the discriminator’s role and maximizes, and the generator minimizes. Both expectations need only samples, never densities, which is what makes the bound usable for an implicit model. The original GAN is one case, with a generator that is not normalized. With we have rather than : this is a normalized generator plus the constant , and since the divergence is shifted by the same constant, , and the conjugate is for . Writing with gives , and the bound becomes exactly (Nowozin, Cseke and Tomioka, 2016, Section 2.4, Tables 1 and 6).
Output activations. The bound needs inside the domain of , which for most divergences is not the whole real line. f-GAN therefore lets the network output an unconstrained number and maps it through a fixed increasing output activation , so that (Section 2.4, Eq. 7). The game becomes
The table lists the usual choices (Tables 1 and 2). The convention is the one above: with and , and the generators are those of Nowozin et al. A condition after is its domain.
| Divergence | |||
|---|---|---|---|
| , | |||
| Pearson | |||
| squared Hellinger | , | ||
| , | |||
| GAN: , unnormalized | , |
Three remarks on the table.
- Every is increasing, so a large always means “looks real”.
- Nowozin et al. label the fifth row Jensen–Shannon, but with this the divergence is twice as defined in the entropy note. Its exceeds the GAN row’s by , so the two divergences differ by the constant , and the two rows train identically.
- The Pearson row uses . The generator of the example above gives half that divergence and the conjugate .
Compose before computing. Evaluating and then loses precision for the same reason as followed by (above), and Nowozin et al. recommend implementing the composition directly (Section 2.4, footnote 1). It is simple for every row: from top to bottom, , , , , and . For the GAN row , so is exactly minus the discriminator’s binary cross-entropy computed from its logit .
The generator’s step. As for the GAN, the generator can maximize instead of minimizing the fake term of . This keeps the stationary point, and Nowozin et al. found it useful for divergences other than the GAN’s as well (Section 3.2).
Least-squares GAN#
Optional depth: a squared-error discriminator loss and what its optimum minimizes. The rest of the note does not depend on it.
The non-saturating loss repairs the gradient for fakes that the discriminator confidently rejects. The least-squares GAN (LSGAN) also repairs the opposite case, fakes that the discriminator already accepts but that are still far from the data (Mao et al., 2017). Its discriminator has no sigmoid. It is a regression network with a real-valued output, trained toward the value on real samples and on fakes, and the generator wants its samples to be scored (Section 3.2, Eq. 2):
The common choice is the 0–1 coding , (Eq. 9): the discriminator regresses real samples to 1 and fakes to 0, and the generator asks for 1. Mao et al. found that it performs like the coding below and used it in their experiments (Section 3.2.3).
Why least squares helps. The decision boundary is where lies halfway between and . A fake can lie on the real side of that boundary, so the discriminator already scores it as real, and still be far from the data. With the sigmoid cross-entropy such a sample has almost no loss and almost no gradient: the non-saturating loss flattens as the logit grows, with slope . The squared loss is flat only at , so a fake scored beyond is pulled back, but only as far as the level set . The discriminator is fixed during the generator’s step, so this moves such fakes toward the decision boundary, and for training to succeed the boundary should run through the data (Section 3.2.1).
Least squares pull far-away fakes back
The extra gradient comes from the shape of a learned real-valued discriminator, which keeps growing away from the boundary, as the linear one in the figure does. The unconstrained optimal discriminator below lies between and everywhere, and far from both distributions its squared loss can flatten too.
The optimal discriminator and Pearson . For a fixed generator, the discriminator’s loss can be minimized pointwise, as in Step 1. The integrand is a parabola in with its minimum at (Eq. 5)
Add to the generator’s loss the term ; it does not depend on , so it changes no gradient. At , using , the extended loss is (Eqs. 4 and 6)
Choose and , for example , , (Eq. 8). Then and the numerator is . With the mixture we have and , so
the Pearson row of the f-GAN table with in place of and in place of . This mirrors the JS identity of the original GAN, which compares both distributions with the same mixture through KL divergences. is zero only when , that is, . Mao et al. write the same quantity as (Eq. 7), with the reference measure as the first argument. For the two Gaussians of the figure, (a toy value, by numerical integration).
The 0–1 coding does not meet these conditions: there , and , which equals , not , at . It is still minimized there. The integrand is convex in , and at its derivative with respect to , , equals at every : the optimality condition for a convex objective under the constraint .
Strengths and weaknesses#
Strengths.
- Sampling is one forward pass of the generator, and training needs only backpropagation: no Markov chains, no inference over latent variables during learning and no intractable integral (Goodfellow et al., 2014, Section 6).
- The model can represent very sharp, even degenerate distributions (Section 6). Nothing averages plausible images into a blur, as the squared error of a Gaussian decoder does.
- The same game accepts labels, other divergences and other losses, as the extensions above show.
Weaknesses.
- No density. has no explicit form (Section 6), so the likelihood of test data cannot be computed, and models cannot be compared by it. The two losses do not measure sample quality, and there is no clear stopping criterion. Evaluation needs sample-based metrics, the subject of the Inception Score and the notes after it.
- No way back. The generator maps to , but nothing maps an image back to its code. Finding the code of a given image needs an optimization over or an extra network trained for the purpose.
- Unstable training. The alternating updates can oscillate, and the two players must be kept in balance.
- Mode collapse. The generator can cover a few modes well and drop the rest.
- Memorization. A generator can reproduce training images, so samples should be compared with their nearest training images. Radford et al. de-duplicated their largest training set to make memorization less likely (2016, Section 4.1.1).
Notebook#
The GANs notebook of the HSE-LAMBDA Deep Generative Models repository (pinned commit; cell numbers count every cell from 1) implements all three models. The notebook has no saved outputs; it documents procedures, not results.
- Cells 1–2: the minimax objective and the list of tricks the notebook uses: one-sided label smoothing, gradient clipping, dropout in the discriminator, a reduced latent variance at sampling time, a balanced update ratio and batch normalization in the generator.
- Cells 5–16: unconditional GAN on MNIST zeros, resized to and scaled to , batch size 128 with
drop_last=True.- Cell 9: the networks. The latent is a spatial grid, 4 channels on a grid, not a vector, and it is drawn inside the generator’s
forward. EachUpsampleBlockdoubles the resolution bilinearly and then applies twice a convolution, batch norm and LeakyReLU(0.2). Three blocks take to with 32, 64 and 128 channels, and a convolution with Tanh gives the image. EachDownsampleBlockapplies a stride-2 convolution and a convolution, each followed by batch norm, LeakyReLU(0.2) andDropout2d(0.3), and three blocks take to . The discriminator is fully convolutional: a final convolution turns the map into one logit. The docstrings speak of four blocks and of a global average, but the code has three blocks and no pooling. Against the DCGAN guidelines, the generator uses LeakyReLU instead of ReLU and resize-convolutions instead of transposed convolutions, the generator’s channel count grows rather than shrinks with the resolution, and the discriminator applies batch norm right after its first convolution. - Cell 10 sets the hyperparameters: learning rate for both networks, 30 epochs, one discriminator step per generator step (
update_ratio = 1), gradient-norm clipping at and one-sided label smoothing . - Cell 11 gives the guidance on the update ratio summarized under balancing the two players.
- Cell 12 builds the networks and the optimizers: Adam with the default betas for and betas for , each with a step schedule that halves the learning rate every 20 epochs.
- Cell 13 is the training loop with
binary_cross_entropy_with_logits. The discriminator loss is the mean of BCE on real images (target 0.9) and on detached fakes (target 0), which is up to the factor and the smoothing. The generator loss is the non-saturating BCE towards the real label. Here the smoothed target is also used for the generator, so the exact loss is , minimized at rather than . The schedulers are stepped once per epoch. Every 5 epochs the loop saves a checkpoint intoweights/, as does the conditional loop of cell 23; the notebook never creates that directory, sotorch.savefails unless it already exists. - Cells 14–16 plot the losses, sample a grid and list common tricks: one-sided label smoothing, random label flipping, batch normalization in both networks, “avoiding sparse gradients” with the log-sigmoid (the logit form of the losses), and mode collapse with minibatch discrimination, a history of old generators and WGAN as remedies. Cell 15 multiplies the latent by when sampling, so the grid shows the generator applied to a reduced-variance prior rather than samples from itself, the truncation-like prior narrowing; cells 25 and 33 do the same for the other two models.
- Cell 9: the networks. The latent is a spatial grid, 4 channels on a grid, not a vector, and it is drawn inside the generator’s
- Cells 17–26: conditional GAN on CIFAR-100. Cell 19 sets batch size 32, learning rate and Adam betas for both networks, no learning-rate schedule, 30 epochs, smoothing (again also in the generator’s target) and gradient clipping at . In cell 22 the generator embeds the label with
Embedding(100, 16), reshaped into one channel next to the 4 noise channels, and the discriminator embeds it withEmbedding(100, 1024), reshaped into one channel next to the RGB image. The blocks are those of cell 9, with dropout 0.3 in the discriminator. Cell 23 alternates one discriminator and one generator step. Cell 26 lists what the condition buys: control over the class, samples focused on class-specific features, and variety across classes. - Cells 27–33: f-GAN.
Activation_gandConjugate_f(cell 29) implement and from the table for"KLD","RKL","CHI","SQH","JSD"and"GAN", in the same convention: the Pearson conjugate is .VLossis the mean of andQLossthe mean of . Cell 31 selects JS and reuses the unconditional networks: learning rate , Adam with default betas for and for , 100 epochs, no clipping, smoothing or schedule. In cell 32 the generator maximizes on generated samples rather than minimizing the fake term of the bound, the non-saturating surrogate of the generator’s step; the direct form is left as a commented alternative. Two implementation notes. The activation and the conjugate are evaluated one after the other with plainexpandlog. In 32-bit floating point the JS and GAN conjugates return once a fake’s output exceeds about 17, because or rounds to , and the GAN activation returns for below about , whereexp(-v)overflows. The composed forms and avoid both (compose before computing). Andloss_real.backward(retain_graph=True)keeps a graph that is never used again. - Cells 34–36: the choice of latent size (a 100-dimensional vector or a small grid, doubled by each upsampling layer), transposed convolutions against upsampling followed by a convolution, a comparison of variants (the original GAN, WGAN, LSGAN, f-GAN and the conditional GAN), the key challenges with their remedies (gradient penalties, unrolled GANs and several discriminators against mode collapse; label smoothing, balanced learning rates and spectral normalization for stability; the Inception Score, FID and KID for evaluation), practical tips and a list of pros and cons. The body covers them under training GANs in practice, least-squares GAN and strengths and weaknesses; KID is covered with FID.
Next#
The disjoint-support argument showed that JS gives no gradient whenever the supports are disjoint, even when the generator’s samples are close to the data. The next note replaces it with a distance that shrinks continuously as the two distributions approach each other: the Wasserstein distance.
References#
- I. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D. Warde-Farley, S. Ozair, A. Courville, Y. Bengio. Generative adversarial nets. NeurIPS, 2014. Preprint arXiv:1406.2661.
- M. Arjovsky, L. Bottou. Towards principled methods for training generative adversarial networks. ICLR, 2017.
- T. Salimans, I. Goodfellow, W. Zaremba, V. Cheung, A. Radford, X. Chen. Improved techniques for training GANs. NeurIPS, 2016.
- M. Mirza, S. Osindero. Conditional generative adversarial nets. arXiv:1411.1784, 2014.
- S. Nowozin, B. Cseke, R. Tomioka. f-GAN: Training generative neural samplers using variational divergence minimization. NeurIPS, 2016.
- X. Nguyen, M. J. Wainwright, M. I. Jordan. Estimating divergence functionals and the likelihood ratio by convex risk minimization. IEEE Transactions on Information Theory, 56(11), 2010.
- I. Goodfellow. NIPS 2016 tutorial: Generative adversarial networks. arXiv:1701.00160, 2016.
- A. Radford, L. Metz, S. Chintala. Unsupervised representation learning with deep convolutional generative adversarial networks. ICLR, 2016. DCGAN; Section 3: architecture guidelines; Section 4: training details.
- X. Mao, Q. Li, H. Xie, R. Y. K. Lau, Z. Wang, S. P. Smolley. Least squares generative adversarial networks. ICCV, 2017. Section 3.2: losses, benefits and the Pearson χ² connection.
- L. Metz, B. Poole, D. Pfau, J. Sohl-Dickstein. Unrolled generative adversarial networks. ICLR, 2017.
- I. Durugkar, I. Gemp, S. Mahadevan. Generative multi-adversarial networks. ICLR, 2017.
- A. Shrivastava, T. Pfister, O. Tuzel, J. Susskind, W. Wang, R. Webb. Learning from simulated and unsupervised images through adversarial training. CVPR, 2017. Section 2.3: a history of generated images for the discriminator.
- M. Arjovsky, S. Chintala, L. Bottou. Wasserstein GAN. arXiv:1701.07875, 2017; ICML 2017.
- HSE-LAMBDA, Deep Generative Models course repository:
GANs.ipynb.