Vanishing and exploding gradients
Quick answer
Gradients in a recurrent network pass through many state transitions. Repeated multiplication can shrink them toward zero or amplify them, making early inputs hard to learn from or training unstable. Examples are static Python snippets tested locally on CPU; PyTorch is required for selected examples. ByteMind execution is unverified.
Gradient sensitivity
Expected output (locally tested): 0.5 0.000977 1.0 1.0 2.0 1024.0. Increasing the horizon magnifies the difference in sensitivities.
How it works
For scalar linear h_t=w*h_(t-1)+x_t, the derivative of h_T with respect to h_0 is w^T. With w=0.5 and T=10 the magnitude is about 0.000977; with w=2 it is 1024. For nonlinear vector networks the product contains Jacobian matrices; tanh adds derivatives 1-h_t² that can be near zero in saturation. Spectral properties, activation values and the actual trajectory matter; scalar examples are not a universal stability criterion. Gradient norm clipping rescales the concatenated gradient when its norm exceeds a threshold, preserving direction before optimizer updates. It limits exploding gradient norms but cannot restore a vanished gradient. Gated cells, sensible initialization and shorter dependency paths can help, without guaranteeing perfect memory. Truncated BPTT reduces computational history but prevents learning via paths cut at a boundary.
Clip a known gradient
import torchp=torch.nn.Parameter(torch.zeros(2))p.grad=torch.tensor([3.,4.])n=torch.nn.utils.clip_grad_norm_([p],2.)print(round(n.item(),3),[round(v,3) for v in p.grad.tolist()])Expected output (locally tested): 5.0 [1.2, 1.6]. The reported norm is the pre-clipping norm; the new norm is approximately 2.
Common mistakes
Do not treat clipping as a solution to vanishing gradients. Do not clip after the optimizer step or assume bounded activations imply bounded derivatives through all time steps.
Practice and next steps
Calculate scalar sensitivity at several horizons and use PyTorch clipping to inspect a known 3-4-5 gradient vector.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Vanishing and exploding gradients — knowledge check
Apply vanishing and exploding gradients to small examples and debugging scenarios.
Scalar w=0.5 over ten transitions produces what?
What does norm clipping mainly address?
When clip gradients?
Why can tanh contribute to vanishing gradients?
What does truncated BPTT sacrifice?