An exploding gradient has an extremely large norm, which can drive parameter updates far beyond the intended step—even with a small learning rate—and degrade or prevent learning. It can occur in very deep networks. section 5.1.2
Gradient clipping limits unusually large gradient values:
- Choose a threshold and clamp each value to its positive or negative bound. For threshold 5, [1, −2, 1000, 3, −7] becomes [1, −2, 5, 3, −5]. section 5.3.3
- In PyTorch, register a hook on each model parameter and clamp its gradient; clipping may not help when training is already going well, but recurrent neural networks are a common use case. section 5.3.3
fc_model.apply(weight_reset)
for p in fc_model.parameters():
p.register_hook(lambda grad: torch.clamp(grad, -5, 5))
optimizer = torch.optim.AdamW(fc_model.parameters())
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, epochs//3)
fc_results_nesterov_coslr_clamp = train_network(fc_model, loss_func,
train_loader, test_loader=test_loader, epochs=epochs,
optimizer=optimizer, lr_schedule=scheduler,
score_funcs={’Accuracy’: accuracy_score}, device=device)
See the PyTorch parameter-hook example that clamps gradients between −5 and 5. section 5.3.3
Figure 5.2 A toy example showing three scenarios for gradient descent. Each is a contour plot of a 2D optimization going from red (high values, bad) to dark green (low values, good). The ideal case is at the top left, where each gradient heads exactly toward the solution. The top right shows noisy gradients that cause the descent to head in not quite the correct direction, requiring more steps. The bottom left shows exploding gradients, where we begin to take steps that are far too large and head away from the solution. The bottom right shows vanishing gradients, where the gradient becomes so small that we have to take an excessive number of steps to get to the solution.
The contour plots contrast oversized steps that head away from the solution with ideal, noisy, and vanishing-gradient paths. section 5.1.2




