When gradients misbehave
Gradients aren't always well-behaved. Exploding gradients grow unboundedly during training (especially in RNNs and Transformers with long sequences), causing weight updates of infinite magnitude. Vanishing gradients shrink toward zero, blocking learning in early layers.
Gradient clipping is the standard remedy for explosions. Two strategies:
- Clip by global norm (
clipnorm=1.0): scales all gradients so their combined L2 norm ≤max_norm. Recommended for RNNs and Transformers. - Clip by value (
clipvalue=0.5): clips each gradient component independently to[-clipvalue, +clipvalue].
tf.stop_gradient blocks gradient flow through part of a computation graph. The wrapped tensor appears as a constant to the gradient computation. Common use cases: target networks in DQN reinforcement learning, momentum encoders in contrastive learning, and any setting where you compute a value but don't want it to update via backprop.