(critic, real, fake, device)
| 28 | |
| 29 | |
| 30 | def 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 | |
| 53 | def save_checkpoint(model, optimizer, filename="my_checkpoint.pth.tar"): |
nothing calls this directly
no outgoing calls
no test coverage detected