MCPcopy Create free account
hub / github.com/KeepTryingTo/Pytorch-GAN / gradient_penalty

Function gradient_penalty

ProGAN/utils.py:33–53  ·  view source on GitHub ↗
(critic, real, fake, alpha, train_step, device="cpu")

Source from the content-addressed store, hash-verified

31
32
33def gradient_penalty(critic, real, fake, alpha, train_step, device="cpu"):
34 BATCH_SIZE, C, H, W = real.shape
35 beta = torch.rand((BATCH_SIZE, 1, 1, 1)).repeat(1, C, H, W).to(device)
36 interpolated_images = real * beta + fake.detach() * (1 - beta)
37 interpolated_images.requires_grad_(True)
38
39 # Calculate critic scores
40 mixed_scores = critic(interpolated_images, alpha, train_step)
41
42 # Take the gradient of the scores with respect to the images
43 gradient = torch.autograd.grad(
44 inputs=interpolated_images,
45 outputs=mixed_scores,
46 grad_outputs=torch.ones_like(mixed_scores),
47 create_graph=True,
48 retain_graph=True,
49 )[0]
50 gradient = gradient.view(gradient.shape[0], -1)
51 gradient_norm = gradient.norm(2, dim=1)
52 gradient_penalty = torch.mean((gradient_norm - 1) ** 2)
53 return gradient_penalty
54
55
56def save_checkpoint(model, optimizer, filename="my_checkpoint.pth.tar"):

Callers 1

train_fnFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected