liveBook · Manning

Gradient penalty

As explained in Inside Deep Learning: Math, Algorithms, Models

A regularization term that constrains discriminator gradients during Wasserstein GAN training.

In WGAN-GP, a gradient penalty constrains discriminator gradients on interpolated real and generated samples. Reducing opportunities for vanishing gradients can help address mode collapse and make it easier for the generator to keep up with the discriminator. section 9.3.3

def train_wgan(D, G, loader, latent_d, epochs=20, device="cpu"):
G_losses = [] D_losses = []

G.to(device) D.to(device)

optimizerD = torch.optim.AdamW(D.parameters(), #1 
 lr=0.0001, betas=(0.0, 0.9)) 
optimizerG = torch.optim.AdamW(G.parameters(), #2
 lr=0.0001, betas=(0.0, 0.9))

for epoch in tqdm(range(epochs)): 
    for data in tqdm(loader, leave=False): 
    if isinstance(data, tuple) or len(data) == 2: 
        data, class_label = data 
        class_label = class_label.to(device) 
    elif isinstance(data, tuple) or len(data) == 1: 
        data = data[0] 
    batch_size = data.size(0) 
    D.zero_grad() 
    G.zero_grad() 
    real = data.to(device)
#1 Sets up Adam optimizer for D
#2 Sets up Adam optimizer for G

The PyTorch implementation interpolates real and fake inputs, computes discriminator gradients with autograd, and penalizes their L2 norm’s deviation from 1. It weights this penalty by 10 in the discriminator loss. section 9.3.3

Toy-grid GAN

A WGAN-GP training loop applies the penalty to mixed real and generated samples while training on a toy grid. section 9.3.3

How Inside Deep Learning: Math, Algorithms, Models covers it

How deep it goes
Implements interpolation, autograd gradient calculation, a unit-norm deviation penalty, and a weight of 10 in the discriminator loss.
Examples
Uses a toy-grid GAN and interpolated real and generated inputs to demonstrate the penalty.
What you can do after
Apply via PyTorch autograd to compute the penalty on mixed samples and include it in discriminator loss.
How it connects
Connects WGAN-GP with Wasserstein GAN training, the generator, discriminator, and mode collapse.

Also explained in

Compare how 2 books explain gradient penalty →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Inside Deep Learning: Math, Algorithms, Models. The section links point to the parts of the book it draws on.