Gradient Clipping › Worked Example: Gradient Clipping in a Two-Parameter Network
Language AI HandbookAll chapters Gradient Clipping › Worked Example: Gradient Clipping in a Two-Parameter NetworkOne section · Sections in this chapter4 / 14 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
To solidify the mechanics, let's work through a concrete example with a tiny network where we can track every number. Consider a network with exactly two scalar parameters, and , and a simple quadratic loss. This stripped-down scenario lets us see exactly how each clipping method transforms the gradients and what effect that has on the parameter update.
Suppose after a forward and backward pass, we compute:
The gradient vector is , with global norm:
We will apply both clipping methods with threshold and compare the results.
Clip by value with : Each component is clamped independently to .
The clipped gradient is with norm . Notice what happened: the original gradient had , suggesting that should receive a larger update. After clipping, both parameters receive the same update magnitude of 5.0. The information that needed a bigger adjustment than has been discarded.
Clip by norm with : The entire gradient is scaled by .
The clipped gradient is with norm . The ratio is the same as the original ratio . The direction is perfectly preserved, and the magnitude is exactly at the threshold.
import torch
# Two-parameter gradient example
g = torch.tensor([8.0, 6.0])
tau = 5.0
# Clip by value
g_value = torch.clamp(g, -tau, tau)
# Clip by norm
g_norm_val = g.norm(p=2).item()
if g_norm_val > tau:
g_norm_clipped = g * (tau / g_norm_val)
else:
g_norm_clipped = g.clone()Worked Example: Two-Parameter Gradient Clipping ======================================================= Original gradient: [8.0, 6.0] Original norm: 10.0000 Threshold tau: 5.0 Clip by Value: Clipped gradient: [5.0, 5.0] Resulting norm: 7.0711 Ratio g1/g2 before: 1.3333 Ratio g1/g2 after: 1.0000 Direction preserved? No Clip by Norm: Scale factor: 0.5000 Clipped gradient: [4.0, 3.0] Resulting norm: 5.0000 Ratio g1/g2 before: 1.3333 Ratio g1/g2 after: 1.3333 Direction preserved? Yes
The output confirms the theoretical analysis. Clip by value modifies the gradient ratio from 1.33 to 1.00, erasing the relative information. Clip by norm maintains the exact ratio, preserving the directional intent of the original gradient while reducing its magnitude to the threshold.
This example, while small, captures the essential behavior in networks with millions of parameters. The gradient vector in a real network encodes the relative importance of updating every weight, and norm clipping respects that encoding while imposing a safe step size limit.