# Gradient Penalty for Wasserstein GAN (WGAN-GP)

This is an implementation of Improved Training of Wasserstein GANs.

WGAN suggests clipping weights to enforce Lipschitz constraint on the discriminator network (critic). This and other weight constraints like L2 norm clipping, weight normalization, L1, L2 weight decay have problems:

1. Limiting the capacity of the discriminator
2. Exploding and vanishing gradients (without Batch Normalization).

The paper Improved Training of Wasserstein GANs proposal a better way to improve Lipschitz constraint, a gradient penalty.

where $\lambda$ is the penalty weight and

That is we try to keep the gradient norm $\Vert \nabla_{\hat{x}} D(\hat{x}) \Vert_2$ close to $1$.

In this implementation we set $\epsilon = 1$.

Here is the code for an experiment that uses gradient penalty.

46import torch
48
49from labml_helpers.module import Module

52class GradientPenalty(Module):
• x is $x \sim \mathbb{P}_r$
• f is $D(x)$

$\hat{x} \leftarrow x$ since we set $\epsilon = 1$ for this implementation.

57    def __call__(self, x: torch.Tensor, f: torch.Tensor):

Get batch size

67        batch_size = x.shape[0]

Calculate gradients of $D(x)$ with respect to $x$. grad_outputs is set to ones since we want the gradients of $D(x)$, and we need to create and retain graph since we have to compute gradients with respect to weight on this loss.

73        gradients, *_ = torch.autograd.grad(outputs=f,
74                                            inputs=x,
76                                            create_graph=True)
79        gradients = gradients.reshape(batch_size, -1)
Calculate the norm $\Vert \nabla_{\hat{x}} D(\hat{x}) \Vert_2$
81        norm = gradients.norm(2, dim=-1)
Return the loss $\big(\Vert \nabla_{\hat{x}} D(\hat{x}) \Vert_2 - 1\big)^2$
83        return torch.mean((norm - 1) ** 2)
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 1, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 1, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.8473260998725891, "perplexity": 3638.064474048606}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2021-31/segments/1627046153521.1/warc/CC-MAIN-20210728025548-20210728055548-00605.warc.gz"}