Gradient clipping: direction, scope and order
梯度裁剪
Derive norm clipping as projection, compare coordinate clipping and implement stable clipping of huge finite vectors.
gradient-clippingLimit the proposed signal without confusing the norm
A gradient vector(3,4) has Euclidean norm 5. To cap the whole vector at norm 2 while retaining its direction, multiply both entries by 2/5, giving(1.2,1.6). Clipping each coordinate to the interval[−2,2] instead gives(2,2), whose norm is√8 and whose direction has changed. These are different operations.
Pascanu, Mikolov and Bengio,2013, Section 3.2, Algorithm 1 gives norm rescaling when a threshold is exceeded. The fixed PyTorch 2.8 clip_grad_norm_ documentation defines a norm across the gradients of the supplied parameter collection. This chapter implements its own pure list operation, using those definitions to clarify the scope of the norm.
Read vector norms and exploding gradients first. Clipping can limit a finite gradient; it cannot reconstruct information already lost to nonfinite arithmetic.
Global norm clipping projects onto a ball
For a gradient g and threshold τ≥0, Euclidean norm clipping is:
If g is already in the ball, it is its own nearest point. Otherwise expand the squared distance. At a fixed length of u, the dot product uᵀg is maximized by aligning u with g, by Cauchy–Schwarz. Along that direction the nearest permitted radius is τ. This proves the projection formula; zero gradients need no division.
For nonzero g and positive τ, global clipping preserves its direction and only shrinks its magnitude. Coordinate clipping is instead projection onto a box. Clipping different parameter groups separately constrains separate balls, not the one ball over the entire concatenated gradient.
For plain SGD using learning rate η≥0:
This is an update-length bound for the stated rule, not a loss-decrease theorem. Momentum can add an existing velocity, weight decay can add another term, and an adaptive optimizer can rescale coordinates. In those cases the bound on the supplied gradient alone is not a bound of the same form on the complete parameter update.
Clipping and averaging do not commute
Let a scalar stochastic gradient G be−1 or 3, each with probability 1/2. Its mean is 1. With τ=1:
Thus clipping an unbiased stochastic gradient can introduce bias. Clipping each microbatch before accumulation is generally different from accumulating correctly scaled gradients and clipping once. Neither ordering can be silently substituted for the other in a reproduction.
A common gradient-scale factor also changes the meaning of a numerical threshold. If gradients have been multiplied for numerical reasons, the threshold must refer to the intended unscaled gradient or be adjusted consistently. This follows from the norm’s scaling, not from a particular framework’s default behavior.
Avoid overflowing while measuring a finite vector
The complete Python 3.12 program first scales all entries by their maximum absolute value. The resulting squared sum is bounded by the vector length. It compares this normalized radius with τ/scale and constructs a clipped result without forming an overflowing original norm or multiplying huge entries by an underflowed scale factor.
from math import sqrt, isfinite, hypot
def clip_gradient(gradient, threshold, mode='global'):
g=list(gradient);tau=threshold
if not 1<=len(g)<=64 or any(type(v) not in (int,float) or abs(v)>1e308 or not isfinite(v) for v in g):
raise ValueError('one to 64 finite gradient values bounded by 1e308 required')
if type(tau) not in (int,float) or abs(tau)>1e300 or not isfinite(tau) or tau<0:
raise ValueError('finite nonnegative threshold at most 1e300 required')
if mode not in ('global','value'):raise ValueError('global or value mode required')
g=list(map(float,g));tau=float(tau)
if mode=='value':return [min(tau,max(-tau,v)) for v in g]
scale=max(abs(v) for v in g)
if scale==0 or tau==0:return [0.0]*len(g)
normalized=[v/scale for v in g]
radius=sqrt(sum(v*v for v in normalized))
if radius<=tau/scale:return g
return [v*(tau/radius) for v in normalized]
if __name__=='__main__':
g=[3,4]
for mode in ('global','value'):
result=clip_gradient(g,2,mode)
print(mode,'result:',result,'norm:',f'{hypot(*result):.9f}')
separate=clip_gradient([3],2)+clip_gradient([4],2)
print('two separately clipped scalar parameters:',separate)
print('mean of clipped samples (-1,3):',sum(clip_gradient([g],1)[0] for g in (-1,3))/2)
print('clip of mean sample:',clip_gradient([1],1)[0])
for tau in (1.0,1e-300):
result=clip_gradient([1e308]*64,tau)
print('large finite vector: threshold',tau,'clipped norm',f'{hypot(*result):.9g}')
Actual output:
global result: [1.2000000000000002, 1.6] norm: 2.000000000
value result: [2.0, 2.0] norm: 2.828427125
two separately clipped scalar parameters: [2.0, 2.0]
mean of clipped samples (-1,3): 0.0
clip of mean sample: 1.0
large finite vector: threshold 1.0 clipped norm 1
large finite vector: threshold 1e-300 clipped norm 1e-300
The 64-entry vector has finite entries of 10³⁰⁸, but its mathematical norm exceeds the largest finite binary 64 number. The implementation can still compute a finite clipped direction. At threshold 10⁻³⁰⁰ it also retains nonzero output components. Rounding and very small unrepresentable components remain possible; stable evaluation does not supply infinite precision.
The function returns a new list and rejects NaN and infinity. The documented PyTorch operation modifies gradients in place and returns their total norm; we do not claim to reproduce its complete API, kernel details or epsilon conventions. No PyTorch dependency is needed here.
Evaluation requires O(d) scalar work and O(d) storage. Tests check the(3,4) reference, unchanged vectors inside the ball, zero threshold, direction ratios, the averaging counterexample, huge finite inputs and rejection of invalid values. Global norm bounds are checked with a floating-point tolerance.
A clipped update may still be a bad update
A bounded step can point toward a poor minibatch objective or be too large for local curvature. Repeated clipping can also change the effective optimization behavior and hide an incorrect loss scale. Track how often clipping occurs and the relevant pre-clip magnitudes, then inspect the reason rather than treating a finite result as proof of healthy training.
The norm’s scope matters in distributed or sharded training: the collection of gradients supplied must match the intended global quantity. Per-layer and per-worker clipping are different algorithms unless their aggregation makes them equivalent under explicit conditions. This small program has one vector and does not implement distributed reduction.
A zero or nonfinite gradient requires a different diagnosis. Clipping cannot restore a detached computation graph, repair invalid data or recover a gradient direction that became NaN. For very small true gradients, reducing large components elsewhere does not manufacture the missing signal.
Which object is being constrained?
- What is global Euclidean clipping of(3,4) at threshold 2?
Answer 1: (1.2,1.6), with norm 2 and the original direction.
- Does separately clipping the two scalar parameters at 2 enforce a global norm bound 2?
Answer 2: No. It yields(2,2), with norm√8.
- What is the mean after clipping equally likely scalar gradients−1 and 3 at 1?
Answer 3: Zero, whereas clipping their mean gives 1.
- Does the bound ητ necessarily cover a momentum optimizer’s entire update?
Answer 4: No. Existing velocity and other update terms can contribute beyond the clipped gradient.
Record the threshold and the aggregation order
The original norm-clipping paper motivates rescaling and treats its threshold as a hyperparameter. Its practical heuristic is not a universal choice for every model. The fixed-version library documentation clarifies the supplied-parameter scope and nonfinite-error option; our implementation chooses explicit rejection and a separate return convention.
The projection proof, noncommuting expectation example and scaled numerical routine are original. When reporting a training run, specify norm type, parameter scope, threshold, loss reduction, accumulation order and optimizer. Continue to minibatches and epochs and steps to make those training-loop choices measurable.
Make a prediction, then check
Does clipping commute with averaging in general?
Learning objectives
- Distinguish global norm, coordinate and group clipping.
- Check aggregation order and nonfinite numerical limits.
Prerequisites & connections
Explore related knowledge →References
- On the difficulty of training recurrent neural networks
Razvan Pascanu; Tomas Mikolov; Yoshua Bengio · 2013 - torch.nn.utils.clip_grad_norm_ — PyTorch 2.8
PyTorch contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Shared recurrent gradients, transient powers, stable clipping, exact minibatch distributions and accumulated-update traces are checked against literal references, analytic identities and finite differences. All four examples use the standard library.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- On the difficulty of training recurrent neural networks · Section3.2 Algorithm1 physicalpage6, norm rescaling and threshold discussion; not a general loss-decrease guarantee.
- torch.nn.utils.clip_grad_norm_ — PyTorch 2.8 · Fixed2.8 clip_grad_norm_: supplied-parameter concatenated norm, in-place operation, returned total norm and error_if_nonfinite; no API clone claimed.
Related topics