v9.1.1
Menu

Gradient Clipping by Norm

easyFREEGradient ManipulationPyTorch Advanced

Problem Statement

Implement gradient clipping by norm to prevent exploding gradients.

Background

Norm-based gradient clipping scales all gradients so their total L2 norm doesn't exceed a threshold. This is essential for training RNNs and Transformers.

Your Task

The starter code creates a model, computes a loss, and calls backward. Compute the total gradient norm before clipping, apply norm-based gradient clipping with max_norm=1.0, then compute the norm again after clipping.

Output Format

Returns a dictionary with "norm_before", "norm_after", and "was_clipped".

Example

Input
None
Output
{'norm_before': 1463.896, 'norm_after': 1.0, 'was_clipped': True}
Reasoning
  • No arguments: a seeded linear layer maps 4 inputs to 2 outputs, with input x=[10,20,30,40]x = [10, 20, 30, 40] and target [1,1][1, 1]. The prediction is y^≈[27.42,5.00]\hat y \approx [27.42, 5.00], so the mean squared error is 26.422+4.0022≈357.05\frac{26.42^2 + 4.00^2}{2} \approx 357.05.
  • Averaging over 2 outputs cancels the factor 2, so the bias gradient is y^−y≈[26.42,4.00]\hat y - y \approx [26.42, 4.00]. The weight gradient is its outer product with xx; its first row is 26.42⋅[10,20,30,40]≈[264.2,528.4,792.7,1056.9]26.42 \cdot [10, 20, 30, 40] \approx [264.2, 528.4, 792.7, 1056.9].
  • The total norm treats all gradient entries as one long vector: ∥gW∥2+∥gb∥2=1463.6522+26.7232≈1463.896\sqrt{\lVert g_W \rVert^2 + \lVert g_b \rVert^2} = \sqrt{1463.652^2 + 26.723^2} \approx 1463.896, which is norm_before.
  • That exceeds the threshold 1.01.0, so every gradient is scaled by 1.0/1463.896≈0.0006831.0 / 1463.896 \approx 0.000683. Direction is kept and only the length shrinks, so the norm becomes 1.01.0 (norm_after).
  • was_clipped is True because 1463.896>1.01463.896 > 1.0. Notice that the large inputs inflate the weight gradient. A norm already below 1.01.0 would be left alone, and both norms would match.

Constraints

  • Use torch.nn.utils.clip_grad_norm_
  • max_norm=1.0
  • Use MSE loss

Learn this in

More from PyTorch Advanced

solution.py

Test results

Sign in to run your code against the test cases.