AI Logic

Architectures

Wasserstein GAN (WGAN)

Updated:

Architecture of WGAN. Left: the flow in which fake data, made by passing noise z through the generator g_θ, and real data x are fed to a critic f_w without a sigmoid, which outputs real-valued scores. Right: alternating training that updates the critic 5 times with weight clipping and then updates the generator once, and how the critic's loss, as an estimate of the EM distance, corresponds to image quality.

Background and Overview

WGAN (Wasserstein GAN) is a generative model that replaces the discriminator of a GAN with a "critic" that rates realism with a real-valued score, and trains by measuring the distance between two distributions (the EM distance) through the difference between the scores of real and fake samples. Like a GAN, it trains the generator and the critic alternately, but its loss uses neither log nor sigmoid, and it keeps the critic's weights within a small range (clipping) so that the distance estimate holds.

It was proposed by Arjovsky, Chintala, and Bottou in the 2017 paper "Wasserstein GAN".

The original GAN was known for unstable training. It required careful balancing of the generator and discriminator, was sensitive to network architecture, and suffered from mode collapse, in which the generator produces only a few kinds of images. Moreover, the loss value did not indicate whether training was progressing well. The paper traced the root of these problems to "how the closeness of two distributions is measured", and showed the following.

  • The EM distance gives meaningful gradients even when the distributions do not overlap: for distributions lying on low-dimensional manifolds, such as images, the Jensen–Shannon divergence (JS) that a GAN implicitly uses gets stuck at a constant value and yields no gradient. The EM distance decreases continuously as the distributions get closer.
  • Training is stable: the critic may be trained close to optimality, removing the need to balance the generator and critic. Generators without batch normalization, and even fully connected generators, can be trained, and no mode collapse was observed in the paper's experiments.
  • The loss reflects training progress: the critic's loss is an estimate of the EM distance, so the lower it gets, the better the generated images become.

As an everyday analogy, a GAN discriminator is a judge who only answers "real or fake"; while the fakes are poor, it simply says "all fake" and gives no hint about what to fix. The WGAN critic is a judge who scores "how far from real" a sample is; even when the fakes are poor, the score rises as they improve, so the direction of improvement is clear.

Theory

Like a GAN, WGAN consists of two networks: a generator and a network that evaluates it (left side of the figure at the top of the article). However, since the evaluating network does not output a probability, the paper calls it a critic rather than a discriminator.

  • Generator gθg_\theta: transforms noise z∼p(z)\boldsymbol{z} \sim p(\boldsymbol{z}) into gθ(z)g_\theta(\boldsymbol{z}), which has the same shape as the data. Its distribution is denoted Pθ\mathbb{P}_\theta.
  • Critic fwf_w: takes an input and outputs a single real-valued score. The experiments use the DCGAN discriminator with its final sigmoid removed.

The EM distance

The closeness of the training data distribution Pr\mathbb{P}_r and the generator distribution Pθ\mathbb{P}_\theta is measured by the following EM distance (Earth Mover distance, Wasserstein-1 distance) (Eq. 1).

W(Pr,Pθ)=inf⁡γ∈Π(Pr,Pθ)E(x,y)∼γ[ ∥x−y∥ ]W(\mathbb{P}_r, \mathbb{P}_\theta) = \inf_{\gamma \in \Pi(\mathbb{P}_r, \mathbb{P}_\theta)} \mathbb{E}_{(\boldsymbol{x}, \boldsymbol{y}) \sim \gamma}\big[\, \|\boldsymbol{x} - \boldsymbol{y}\| \,\big]

Π(Pr,Pθ)\Pi(\mathbb{P}_r, \mathbb{P}_\theta) is the set of all joint distributions γ(x,y)\gamma(\boldsymbol{x}, \boldsymbol{y}) whose marginals are Pr\mathbb{P}_r and Pθ\mathbb{P}_\theta, respectively. γ(x,y)\gamma(\boldsymbol{x}, \boldsymbol{y}) is a plan for "how much earth to move from x\boldsymbol{x} to y\boldsymbol{y}", and the EM distance is the cheapest transport cost of reshaping a pile of earth shaped like one distribution into the shape of the other.

Estimating the EM distance with a critic

The infimum in Eq. 1 cannot be computed as is. Instead, it is rewritten in the following form using the Kantorovich–Rubinstein duality (Eq. 2).

W(Pr,Pθ)=sup⁡∥f∥L≤1Ex∼Pr[f(x)]−Ex∼Pθ[f(x)]W(\mathbb{P}_r, \mathbb{P}_\theta) = \sup_{\|f\|_L \le 1} \mathbb{E}_{\boldsymbol{x} \sim \mathbb{P}_r}\big[f(\boldsymbol{x})\big] - \mathbb{E}_{\boldsymbol{x} \sim \mathbb{P}_\theta}\big[f(\boldsymbol{x})\big]

The supremum is taken over all 1-Lipschitz functions ff (functions whose slope is at most 1 in magnitude everywhere). Representing ff with a neural network fwf_w and training it to maximize the difference between the mean scores of real and fake samples gives an estimate of the EM distance at the maximum (Eq. 3).

max⁡w∈W  Ex∼Pr[fw(x)]−Ez∼p(z)[fw(gθ(z))]\max_{w \in \mathcal{W}} \; \mathbb{E}_{\boldsymbol{x} \sim \mathbb{P}_r}\big[f_w(\boldsymbol{x})\big] - \mathbb{E}_{\boldsymbol{z} \sim p(\boldsymbol{z})}\big[f_w(g_\theta(\boldsymbol{z}))\big]

If all fwf_w are KK-Lipschitz, this value estimates K⋅W(Pr,Pθ)K \cdot W(\mathbb{P}_r, \mathbb{P}_\theta). Since KK is a constant, it does not affect training. As a simple way to keep fwf_w Lipschitz, the paper clips the weights to the range [−c,c][-c, c] after every update. If the weights are bounded, the slope of fwf_w is also bounded.

Training procedure

Algorithm 1 of the paper is as follows (right side of the figure at the top of the article). The defaults are learning rate α=0.00005\alpha = 0.00005, clipping parameter c=0.01c = 0.01, batch size m=64m = 64, and number of critic updates ncritic=5n_{\mathrm{critic}} = 5, used in all of the paper's experiments.

  1. Sample a minibatch of training data {x(i)}i=1m\{\boldsymbol{x}^{(i)}\}_{i=1}^m and a minibatch of noise {z(i)}i=1m\{\boldsymbol{z}^{(i)}\}_{i=1}^m.
  2. Update the critic with RMSProp in the direction that increases the quantity below.
  3. Clip the critic's weights ww to [−c,c][-c, c].
  4. Repeat 1–3 ncriticn_{\mathrm{critic}} times.
  5. Sample a new minibatch of noise and update the generator with RMSProp in the direction that increases 1m∑ifw(gθ(z(i)))\frac{1}{m}\sum_i f_w(g_\theta(\boldsymbol{z}^{(i)})).
  6. Repeat 1–5 until the generator converges.

The quantity increased in step 2 is the following.

1m∑i=1mfw(x(i))−1m∑i=1mfw(gθ(z(i)))\frac{1}{m}\sum_{i=1}^{m} f_w\big(\boldsymbol{x}^{(i)}\big) - \frac{1}{m}\sum_{i=1}^{m} f_w\big(g_\theta(\boldsymbol{z}^{(i)})\big)

The generator update is based on Theorem 3 of the paper. If the critic is optimal, the gradient of the EM distance with respect to the generator is ∇θW(Pr,Pθ)=−Ez[∇θf(gθ(z))]\nabla_\theta W(\mathbb{P}_r, \mathbb{P}_\theta) = -\mathbb{E}_{\boldsymbol{z}}\big[\nabla_\theta f(g_\theta(\boldsymbol{z}))\big]. In other words, raising the score of fake samples corresponds to lowering the EM distance.

The paper itself states that weight clipping is "a clearly terrible way to enforce a Lipschitz constraint". If cc is large, it takes a long time for the weights to reach the limits of the range, making it hard to train the critic to optimality. If cc is small, gradients tend to vanish when there are many layers or when batch normalization is not used (as in RNNs). The paper calls for research into better methods.

Why Training Is Stable

WGAN's stability comes from the property of the EM distance that it "decreases continuously as the distributions get closer, even when they do not overlap".

The difference when distributions do not overlap

Example 1 of the paper considers two parallel line segments in the plane. The real distribution P0\mathbb{P}_0 is uniform on a segment of length 1 on the vertical axis (x=0x = 0), and the generator distribution Pθ\mathbb{P}_\theta lies on the same segment shifted horizontally by θ\theta. The distances are then as follows.

DistanceWhen θ≠0\theta \ne 0When θ=0\theta = 0As a function of θ\theta
EM distance WW∣θ∣\lvert\theta\rvert0Continuous, with a gradient everywhere
JS divergencelog⁡2\log 20Stuck at a constant; gradient is 0
KL divergence+∞+\infty0Undefined
Total variation distance10Stuck at a constant; gradient is 0

As θ\theta approaches 0, JS, KL, and total variation do not change until θ=0\theta = 0. Since shifting the distribution slightly does not change the loss, θ\theta cannot be moved by gradients. Only the EM distance returns the size of the shift as is.

High-dimensional data such as images are thought to concentrate on low-dimensional manifolds. Such distributions hardly overlap. This is why, as the original GAN's discriminator approaches optimality, the JS divergence gets stuck at log⁡2\log 2 and no gradient reaches the generator.

The paper shows this for the general case.

  • Theorem 1: if the generator is continuous in θ\theta, then W(Pr,Pθ)W(\mathbb{P}_r, \mathbb{P}_\theta) is also continuous. Under further conditions, it is differentiable almost everywhere. This does not hold for JS and KL.
  • Corollary 1: an ordinary neural-network generator with a prior of finite expectation (Gaussian, uniform, etc.) satisfies those conditions.
  • Theorem 2: the criteria for convergence of distributions become weaker in the order KL, then JS and total variation, then the EM distance. The EM distance becomes small when distributions approach each other in the loosest sense.

The critic can be trained to optimality

In a GAN, making the discriminator too strong saturates JS so that no gradient reaches the generator, which is why the two had to be balanced. In WGAN, the closer the critic is to optimal, the more accurately the gradient of the EM distance is obtained. The paper tested this with two Gaussians and showed that the GAN discriminator quickly saturates and its gradients vanish, whereas the WGAN critic does not saturate and gives clean gradients that are nearly linear across the whole space (Figure 2).

The paper also states that being able to train the critic to optimality prevents mode collapse. Mode collapse arises because, for a fixed discriminator, the optimal generator "concentrates its output on the points to which the discriminator assigns the highest value". If the critic is close to optimal at every step, concentrating on such points does not lower the EM distance, so the generator cannot escape there.

Experimental Results

The paper trains WGAN on LSUN bedroom images (64×6464 \times 64, 3 channels) and compares it with a DCGAN trained with the standard GAN procedure (the −log⁡D-\log D form of the loss). The hyperparameters are the defaults of Algorithm 1 in all experiments. Results are presented as figures of generated images and learning curves; there are no numerical tables such as FID.

The loss corresponds to image quality

Recording the critic's loss (the estimate in Eq. 3) throughout training gave the following (Figure 3).

  • Whether the generator was a 4-layer fully connected network (512 units per layer, ReLU) or a DCGAN, image quality improved as the loss decreased.
  • When both the generator and critic were fully connected and training failed because the learning rate was too high, neither the loss nor the images changed.

Doing the same with a GAN, the JS estimate did not correspond to image quality and, in many cases, stayed near log⁡2≈0.69\log 2 \approx 0.69 (the maximum of JS) or increased (Figure 4). According to the paper, this is the first time a GAN loss has shown convergence behavior.

Training works with different generator architectures

The critic (the discriminator in GAN) was kept as the DCGAN one, and three generators were compared (Figures 5–7).

GeneratorWGANGAN
DCGAN generatorGenerates high-quality imagesGenerates high-quality images
DCGAN without batch normalization and with a constant number of filters per layer (a little over one tenth of the parameters)Was able to generate imagesTraining failed
4-layer fully connected (512 units per layer, ReLU)Generated images, though of lower quality than DCGANLow quality with severe mode collapse

The paper states that "in no experiment did we see evidence of mode collapse for the WGAN algorithm". It also explicitly notes that the images were not cherry-picked.

The critic's loss cannot be used as is as an evaluation metric for comparing generative models. Its value is scaled by a constant determined by the critic's architecture, and the critic's capacity is also limited. The paper does not claim it as a new evaluation metric either. It is used as a learning curve for monitoring training with the same critic.

Practical Considerations

Keep the following points in mind when using WGAN.

  • Do not put a sigmoid at the end of the critic: use the output as a real-valued score. The loss uses no log either, only the difference of mean scores.
  • Clip the weights every time: after each critic update, clip all weights to [−c,c][-c, c]. The paper uses c=0.01c = 0.01.
  • Update the critic more often: update the critic ncritic=5n_{\mathrm{critic}} = 5 times per generator update. The closer the critic is to optimal, the more accurate the gradient passed to the generator.
  • Use a small learning rate: the paper's learning rate is 0.000050.00005; training became unstable at high learning rates.
  • Monitor training with the loss curve: if the critic's loss (the difference between real and fake scores) is decreasing, training is progressing.

The paper reports that using a momentum-based optimizer such as Adam (β1>0\beta_1 > 0) for the critic sometimes made training unstable. The critic's loss changes as training proceeds (it is non-stationary), so momentum is thought to work against it. When the loss diverged, the cosine of the angle between the Adam update and the gradient was negative. For this reason, the paper uses RMSProp, which works well even on non-stationary problems.

Comparison with Other Methods

GAN and WGAN compared from the same viewpoints:

AspectGAN (2014)WGAN (2017)
Distance measuredJS divergence (when the discriminator is optimal)EM distance (Wasserstein-1)
Output of the evaluating networkProbability of being real (sigmoid)Real-valued score (no sigmoid)
LossBinary cross-entropy (uses log)Difference of mean scores
Constraint on the evaluating networkNone1-Lipschitz (approximated by weight clipping)
Update ratiokk discriminator updates per generator update (k=1k = 1 in experiments)5 critic updates per generator update
OptimizationGradient method with momentumRMSProp (learning rate 0.00005)
BalancingNeeded (gradients vanish if the discriminator is too strong)Mostly unnecessary (the stronger the critic, the better)
Meaning of the loss valueDoes not correspond to image qualityCorresponds to training progress

Rough guidelines for choosing are as follows.

  • GAN training is unstable and tuning the architecture or balance is a struggle: the ideas of WGAN (EM distance and critic) help. Being able to monitor training through the loss also makes trial and error easier.
  • Avoiding the weaknesses of weight clipping: methods that enforce the Lipschitz constraint in other ways were proposed later, such as WGAN-GP, which uses a gradient penalty, and Spectral Normalization, which normalizes the largest singular value of the discriminator's weights to 1.
  • Improving image quality itself: WGAN is a change of loss, so the generator architecture can be chosen independently. Start from the DCGAN architecture, and for high-resolution images use later architectures such as StyleGAN.
  • Also wanting likelihoods or a mapping to latent variables: VAE is a candidate.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
WGAN of Arjovsky et al. (2017) (Algorithm 1)
- The critic has no final sigmoid and outputs a real-valued score
- Critic: maximize mean f(x) − mean f(G(z)) → clip weights to [−c, c] after every update
- Generator: maximize mean f(G(z))
- Defaults α = 0.00005, c = 0.01, m = 64, n_critic = 5. Optimizer is RMSProp (Adam was reported to be unstable)
- Networks have the same shape as DCGAN (64×64 color images). PyTorch has no built-in WGAN
"""

z_dim, lr, clip_c, m, n_critic = 100, 5e-5, 0.01, 64, 5
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"

G = nn.Sequential(                                   # generator: z [m, 100, 1, 1] -> [m, 3, 64, 64]
  nn.ConvTranspose2d(z_dim, 512, 4, 1, 0, bias=False), nn.BatchNorm2d(512), nn.ReLU(True),  # 4×4
  nn.ConvTranspose2d(512, 256, 4, 2, 1, bias=False), nn.BatchNorm2d(256), nn.ReLU(True),    # 8×8
  nn.ConvTranspose2d(256, 128, 4, 2, 1, bias=False), nn.BatchNorm2d(128), nn.ReLU(True),    # 16×16
  nn.ConvTranspose2d(128, 64, 4, 2, 1, bias=False), nn.BatchNorm2d(64), nn.ReLU(True),      # 32×32
  nn.ConvTranspose2d(64, 3, 4, 2, 1, bias=False), nn.Tanh(),                                # 64×64
).to(device)

critic = nn.Sequential(                              # critic: DCGAN discriminator without the sigmoid
  nn.Conv2d(3, 64, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, True),
  nn.Conv2d(64, 128, 4, 2, 1, bias=False), nn.BatchNorm2d(128), nn.LeakyReLU(0.2, True),
  nn.Conv2d(128, 256, 4, 2, 1, bias=False), nn.BatchNorm2d(256), nn.LeakyReLU(0.2, True),
  nn.Conv2d(256, 512, 4, 2, 1, bias=False), nn.BatchNorm2d(512), nn.LeakyReLU(0.2, True),
  nn.Conv2d(512, 1, 4, 1, 0, bias=False),            # [m, 1, 1, 1]; no sigmoid
  nn.Flatten(),
).to(device)

opt_c = torch.optim.RMSprop(critic.parameters(), lr=lr)
opt_g = torch.optim.RMSprop(G.parameters(), lr=lr)


def sample_z(n):
  return torch.randn(n, z_dim, 1, 1, device=device)


def train_step(real_batches):
  """real_batches: iterator yielding n_critic minibatches of real images ([m, 3, 64, 64], in -1 to 1)"""
  G.train(); critic.train()
  # (1) update the critic n_critic times
  for _ in range(n_critic):
    x = next(real_batches).to(device)
    fake = G(sample_z(x.size(0))).detach()           # do not backprop into the generator
    # maximize mean f(x) − mean f(G(z)) = minimize its negation
    loss_c = -(critic(x).mean() - critic(fake).mean())
    opt_c.zero_grad()
    loss_c.backward()
    opt_c.step()
    with torch.no_grad():                            # clip weights to keep the critic Lipschitz
      for p in critic.parameters():
        p.clamp_(-clip_c, clip_c)

  # (2) update the generator once: maximize mean f(G(z))
  loss_g = -critic(G(sample_z(m))).mean()
  opt_g.zero_grad()
  loss_g.backward()
  opt_g.step()                                       # only the generator is updated

  em_estimate = -loss_c.item()                       # estimate of (a constant times) the EM distance; log as a learning curve
  return em_estimate, loss_g.item()


# for generation, switch batch norm to running averages
G.eval()
with torch.no_grad():
  images = G(sample_z(64))                           # [64, 3, 64, 64], in -1 to 1

FAQ

Q. How does the WGAN "critic" differ from the GAN "discriminator"?
A.

A GAN discriminator outputs the probability (0 to 1) that the input is real and is trained with binary cross-entropy. A WGAN critic outputs a real-valued score without a sigmoid and is trained to maximize the difference between the mean scores of real and fake samples. Because its weights are clipped to keep it Lipschitz, that difference becomes an estimate of (a constant times) the EM distance. Since it does not answer with a probability, the paper calls it a "critic".

Q. Why are the weights clipped?
A.

To estimate the EM distance in its dual form (Eq. 2), the critic fwf_w must be a Lipschitz function (a function with a bounded slope). Keeping the weights within [−c,c][-c, c] also bounds the slope of fwf_w. The paper chose this method for its simplicity, but also admits that it is a poor method: it is sensitive to the choice of cc and can cause vanishing gradients or slow training. Later, methods such as the gradient penalty (WGAN-GP) and Spectral Normalization came into use.

Q. What does the WGAN loss value represent?
A.

The critic's loss (the difference between the mean scores of real and fake samples) is an estimate of the EM distance between the training data distribution and the generator distribution. In the paper's experiments, generated image quality improved as this value decreased. However, the value is scaled by a constant determined by the critic's architecture, so it cannot be used as a metric to compare models with different critics.

References

  1. Arjovsky, M., Chintala, S., & Bottou, L. (2017). Wasserstein Generative Adversarial Networks. Proceedings of the 34th International Conference on Machine Learning (ICML 2017), PMLR 70:214-223. arXiv:1701.07875.
  2. Goodfellow, I. J., et al. (2014). Generative Adversarial Nets. NeurIPS 2014. arXiv:1406.2661.