L2 Gradient Penalty
Problem Statement
Implement an L2 gradient penalty term, commonly used in Wasserstein GANs (WGAN-GP).
Background
The gradient penalty encourages the norm of gradients to be close to 1. Given an input, you compute gradients of the output w.r.t. the input and penalize when the norm deviates from 1.
Your Task
The starter code creates a model and input. Compute the gradient of the model's output with respect to the input (with graph creation enabled so you can backprop through the penalty). Then compute the L2 norm of that gradient and penalize its deviation from 1.
Output Format
Returns a dictionary with "output_value", "grad_norm", and "penalty".
Example
None
{'output_value': 1.2696, 'grad_norm': 0.9247, 'penalty': 0.0057}- We start by seeding the random number generator with
torch.manual_seed(42)to ensure reproducibility, then create a linear modelnn.Linear(3, 1)and an input tensor[[1.0, 2.0, 3.0]]withrequires_grad=True. - The model output is computed as
output = model(input), which applies a linear transformation to the input: , where and are the model's weights and bias. - We then compute the gradients of the output with respect to the input using
torch.autograd.grad()withcreate_graph=True, and calculate the L2 norm of these gradients: . - Finally, we calculate the gradient penalty as , which encourages the norm of gradients to be close to 1, and return the results in a dictionary with the output value, gradient norm, and penalty value, all rounded to 4 decimals.
Constraints
- Use torch.autograd.grad with create_graph=True
- Gradient penalty = (||grad||_2 - 1)^2
- Input must have requires_grad=True