v9.1.1
Menu

Gradient Clipping by Value

easyFREEGradient ManipulationPyTorch Advanced

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': 70.3371, 'max_grad_after': 0.5, 'was_clipped': True}
Reasoning
  • There are no arguments. The seeded linear layer has a 2×32 \times 3 weight matrix WW and a bias of length 22. It maps x=[5,10,15]x = [5, 10, 15] to y^≈[4.6891,3.4734]\hat{y} \approx [4.6891, 3.4734], and the target is [0,0][0, 0].
  • The loss is the mean of y^i2\hat{y}_i^2 over the 22 outputs, so ∂L∂y^i=22y^i=y^i\frac{\partial L}{\partial \hat{y}_i} = \frac{2}{2}\hat{y}_i = \hat{y}_i. That makes each bias gradient equal to y^i\hat{y}_i, and ∂L∂Wij=y^i xj\frac{\partial L}{\partial W_{ij}} = \hat{y}_i \, x_j.
  • Row 0 of the weight gradient is [23.4457,46.8914,70.3371][23.4457, 46.8914, 70.3371] and row 1 is [17.3672,34.7343,52.1015][17.3672, 34.7343, 52.1015]. The largest magnitude over all 88 gradient entries is 4.6891×15≈70.33714.6891 \times 15 \approx 70.3371, which gives max_grad_before.
  • Value clipping replaces each entry gg with min⁡(max⁡(g,−0.5),0.5)\min(\max(g, -0.5), 0.5). Every entry here, even the smallest bias gradient 3.47343.4734, is above 0.50.5, so all 88 become exactly 0.50.5 and max_grad_after is 0.5.
  • Because 70.3371>0.570.3371 > 0.5, was_clipped is True. Notice that, unlike norm clipping, this erases the relative sizes: 70.337170.3371 and 3.47343.4734 both become 0.50.5.

Constraints

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

More from PyTorch Advanced

solution.py

Test results

Sign in to run your code against the test cases.