PIXELBANKv9.1.0
Menu

Problem Statement

Implement gradient clipping by value, which clamps each gradient element individually.

Background

Unlike norm-based clipping (which scales), value-based clipping clamps each gradient element to [-clip_value, clip_value] independently.

Your Task

The starter code creates a model, computes a loss, and calls backward. Find the maximum absolute gradient value before clipping, apply value-based gradient clipping with clip_value=0.5, then find the maximum absolute gradient value again after clipping.

Output Format

Returns a dictionary with "max_grad_before", "max_grad_after", and "was_clipped".

Example:

Input:
None
Output:
{'max_grad_before': 140.9498, 'max_grad_after': 0.5, 'was_clipped': True}
Reasoning:
  • We start by initializing the model and computing the Mean Squared Error (MSE) loss between the input [[5.0, 10.0, 15.0]] and target [[0.0, 0.0]], which results in a loss value.
  • The backward call computes the gradients of the loss with respect to the model's parameters, and we record the maximum absolute gradient value before clipping, which is approximately 140.9498140.9498.
  • We then apply gradient clipping with a clip_value of 0.50.5 using torch.nn.utils.clip_grad_value_, which clamps each gradient element to the range [−0.5,0.5][-0.5, 0.5].
  • After clipping, the maximum absolute gradient value becomes 0.50.5, and since the maximum absolute gradient value before clipping (140.9498140.9498) is greater than the clip_value (0.50.5), we set "was_clipped" to True.

Constraints:

  • Use torch.nn.utils.clip_grad_value_
  • clip_value=0.5
solution.py

Test Results

0/0
Run code to see test results.
Gradient Clipping by Value - Easy | PixelBank