PIXELBANKv9.1.0
Menu

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:

Input:
None
Output:
{'output_value': 1.2696, 'grad_norm': 0.9247, 'penalty': 0.0057}
Reasoning:
  • We start by seeding the random number generator with torch.manual_seed(42) to ensure reproducibility, then create a linear model nn.Linear(3, 1) and an input tensor [[1.0, 2.0, 3.0]] with requires_grad=True.
  • The model output is computed as output = model(input), which applies a linear transformation to the input: output=wâ‹…input+boutput = w \cdot input + b, where ww and bb are the model's weights and bias.
  • We then compute the gradients of the output with respect to the input using torch.autograd.grad() with create_graph=True, and calculate the L2 norm of these gradients: grad_norm=∑i=13gradi2grad\_norm = \sqrt{\sum_{i=1}^{3} grad_i^2}.
  • Finally, we calculate the gradient penalty as (grad_norm−1)2(grad\_norm - 1)^2, 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
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
L2 Gradient Penalty - Medium | PixelBank