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

Function gradient_penalty

cnn-CGANCode/utils.py:30–50  ·  view source on GitHub ↗
(critic, real, fake, device)

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected