Loading...
Implement gradient clipping by norm to prevent exploding gradients.
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.
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.
Returns a dictionary with "norm_before", "norm_after", and "was_clipped".
None
{'norm_before': 892.5765, 'norm_after': 1.0, 'was_clipped': True}nn.Linear(4, 2) and seed with torch.manual_seed(42) to ensure reproducibility.[[10.0, 20.0, 30.0, 40.0]] and target [[1.0, 1.0]] are used to compute the MSE loss, which is then used to calculate the gradients using the backward method.max_norm threshold of 1.0.torch.nn.utils.clip_grad_norm_ with max_norm=1.0, resulting in a total gradient norm AFTER clipping of 1.0, and since the norm before clipping was greater than 1.0, was_clipped is set to True.