AI Wiki中文/EN

Vanishing gradients: follow the derivative direction

梯度消失

Contrast exact contracting, expanding and cancelling Jacobian products with a centered sigmoid chain and conditional norm bounds.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

An error signal can become too small to matter

A prediction can have substantial error while an early layer receives only a tiny derivative. The chain of intervening operations may shrink the signal before it reaches that layer. This is different from a small gradient because the model is already near a useful optimum, or a zero gradient caused by a disconnected computation.

Depth in a feedforward network and elapsed steps in an unrolled recurrent network both create derivative products. Pascanu, Mikolov and Bengio,2013, Sections 1–2.1 analyzes temporal components using Jacobians. D2L, Section 5.4.1 introduces the feedforward problem. We use exact two-dimensional examples to separate bounds from actual directions.

Read the chain rule, Jacobian and sigmoid and tanh first. The program measures input derivatives and transported gradients at fixed parameters; it does not train a recurrent model.

The chain contains matrices, not just activation slopes

For column-valued states hₗ=fₗ(hₗ₋₁), let Jₗ be the Jacobian of that layer at the evaluated state. If g_L is a terminal scalar objective’s gradient with respect to h_L:

g0=J1TJ2T⋯JLTgL,∥g0∥2≤(∏ℓ=1L∥Jℓ∥2)∥gL∥2.g_0=J_1^TJ_2^T\cdots J_L^Tg_L,\qquad \|g_0\|_2\le\left(\prod_{\ell=1}^{L}\|J_\ell\|_2\right)\|g_L\|_2.

The matrix 2-norm is its largest singular value. If every factor norm is at most a fixed ρ strictly below 1, the transported gradient is bounded byρᴸ times the terminal norm. This is a sufficient contraction condition. A product of upper bounds larger than 1 is not evidence that every vector expands; the actual directions and products matter.

For an affine layer followed by elementwise activation, J=D W, where D contains the activation derivatives. Weight magnitudes and orientation therefore matter alongside activation slopes. For recurrent parameters shared across time, the complete parameter gradient also sums contributions from different time steps. A small long-range contribution does not imply the total parameter gradient must be small.

The same factor norm can hide opposite outcomes

Consider:

A=[2001/2],B=[1/2002],∥A∥2=∥B∥2=2,BA=I.A=\begin{bmatrix}2&0\\0&1/2\end{bmatrix},\qquad B=\begin{bmatrix}1/2&0\\0&2\end{bmatrix},\qquad \|A\|_2=\|B\|_2=2,\qquad BA=I.

Ten copies of A transport terminal direction(0,1) to(0,1/1024), but direction(1,0) to(1024,0). Alternating A and B for ten layers gives the identity. Every individual factor has norm 2, yet one path shrinks, another expands and another preserves both coordinates.

These are linear maps, so their Jacobians do not depend on the state. They supply exact counterexamples to conclusions based only on individual factor norms. General Jacobians need not commute; reverse traversal and transposes must remain in the correct order. The tests include a noncommuting pair to catch an implementation that accidentally works only for diagonal matrices.

A sigmoid chain can shrink even at its center

Set h₀=1/2 and define each layer with the same scalar weight w and bias−w/2:

hℓ=σ ⁣(w(hℓ−1−1/2)),h0=1/2⟹hℓ=1/2,∂hL∂h0=(w4)L.h_\ell=\sigma\!\left(w(h_{\ell-1}-1/2)\right),\qquad h_0=1/2\Longrightarrow h_\ell=1/2,\qquad \frac{\partial h_L}{\partial h_0}=\left(\frac w4\right)^L.

Every preactivation is zero at this input, where sigmoid has its largest derivative 1/4. With w=2, twenty layers still give derivative 2⁻²⁰, about 9.54×10⁻⁷. With w=4, the derivative at this particular input is 1. Neither result is a global training guarantee: different inputs move the chain away from the center, and changing weights changes its behavior.

Transport the direction actually supplied

The complete Python 3.12 program applies transposed 2×2 Jacobians in reverse order using exact fractions. A separate floating-point evaluator computes the sigmoid chain and its analytic derivative using stable exponential branches.

from fractions import Fraction as F
from math import exp, isfinite


def backward(matrices, terminal):
    matrices=[[list(row) for row in a] for a in matrices];g=list(terminal)
    if len(matrices)>20 or len(g)!=2 or any(len(a)!=2 or any(len(row)!=2 for row in a) for a in matrices):
        raise ValueError('at most 20 two-by-two matrices and a two-vector required')
    entries=g+[v for a in matrices for row in a for v in row]
    if any(type(v) not in (int,F) or abs(v)>4 for v in entries):
        raise ValueError('rational entries bounded by 4 required')
    g=list(map(F,g))
    for a in reversed(matrices):
        g=[sum((F(a[i][j])*g[i] for i in range(2)),F(0)) for j in range(2)]
    return g


def sigmoid_chain(x, weight, depth):
    if type(depth) is not int or not 0<=depth<=20:raise ValueError('depth from zero to 20 required')
    if any(type(v) not in (int,float) or not isfinite(v) or abs(v)>4 for v in (x,weight)):
        raise ValueError('finite bounded input and weight required')
    derivative=1.0;h=float(x)
    for _ in range(depth):
        z=weight*(h-0.5);e=exp(-abs(z))
        h=1/(1+e) if z>=0 else e/(1+e)
        derivative*=weight*e/(1+e)**2
    return h,derivative


if __name__=='__main__':
    a=[[2,0],[0,F(1,2)]];b=[[F(1,2),0],[0,2]]
    for name,matrices,g in [('same, shrinking direction',[a]*10,[0,1]),
                            ('same, expanding direction',[a]*10,[1,0]),
                            ('alternating directions',[a,b]*5,[1,1])]:
        print(name,':',[str(v) for v in backward(matrices,g)])
    for weight in (2,4):
        value,derivative=sigmoid_chain(0.5,weight,20)
        print('centered sigmoid weight:',weight,'output:',value,'input derivative:',f'{derivative:.12g}')

Actual output:

same, shrinking direction : ['0', '1/1024']
same, expanding direction : ['1024', '0']
alternating directions : ['1', '1']
centered sigmoid weight: 2 output: 0.5 input derivative: 9.53674316406e-07
centered sigmoid weight: 4 output: 0.5 input derivative: 1

The first three results are exact rational products. The centered sigmoid values are also especially easy to check because 0.5 and powers of two have exact binary representations at these depths. Tests compare the analytic center formula, finite differences at moderate depth, a noncommuting matrix pair and malformed inputs.

For fixed 2×2 matrices, reverse transport costs O(L) rational operations and O(1) evolving gradient storage after the input matrices are materialized. Numerator and denominator sizes affect bit costs. A dense width-d version costs O(Ld²) matrix-vector arithmetic; explicitly building the complete matrix product is unnecessary for one transported gradient.

Diagnose why a gradient is small

A small derivative is not automatically numerical underflow. The exact value 1/1024 is small but represented exactly. Longer chains can eventually underflow in a particular number format, adding a numerical failure to an already small mathematical signal. Increasing precision does not remove the underlying contraction.

Check gradients at multiple layers together with activations, loss values and parameter updates. A detached graph, a mask that removes every example, an incorrectly averaged loss or a stationary fit can all produce small gradients for different reasons. Increasing the learning rate may amplify other gradients and destabilize later layers without restoring the lost directional information.

He initialization and Xavier initialization target useful initial moments, but do not force every Jacobian singular value to 1. Residual connections, gating and normalization alter the derivative paths; their benefits depend on their precise form. Gradient clipping limits large gradients and does not reconstruct a vanished one.

A norm bound is not the vector

  1. What happens to terminal direction(0,1) through ten copies of A?

Answer 1: It becomes(0,1/1024), despite each factor’s norm being 2.

  1. What happens through five alternating pairs A,B?

Answer 2: The full map and transported gradient are unchanged because each pair multiplies to the identity.

  1. What is the input derivative of the twenty-layer centered sigmoid chain with w=2?

Answer 3: 2⁻²⁰, or 1/1048576. Centering each sigmoid does not remove the weight-times-slope product.

  1. Does a vanishing long-term recurrent contribution prove the entire shared-parameter gradient is tiny?

Answer 4: No. The parameter gradient sums contributions, and shorter-range terms can remain large.

Preserve the scope of the gradient claim

The 2013 ICML paper is PMLR 28(3):1310–1318. Its sum-of-products analysis distinguishes temporal contributions from the complete parameter gradient and gives sufficient contraction conditions using singular-value bounds. We use those distinctions rather than claiming a local activation derivative predicts every training outcome.

The rational diagonal examples, noncommuting check and centered sigmoid chain are original. No recurrent benchmark or proposed regularizer from the paper is reproduced. Continue with the planned exploding gradients, gradient clipping and residual connections chapters to inspect other paths and interventions.

Make a prediction, then check

Can factors all having norm2 still shrink a particular gradient direction?

Choose one answer

Learning objectives

  • Distinguish a norm upper bound from directional transport.
  • Separate long-range contributions, total gradients and numerical underflow.

Prerequisites & connections

Explore related knowledge →

References

  1. On the difficulty of training recurrent neural networks
    Razvan Pascanu; Tomas Mikolov; Yoshua Bengio · 2013
  2. Numerical Stability and Initialization — Dive into Deep Learning 1.0.3
    D2L authors · 2023

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. Symmetry trajectories, exact sign-law moments, initializer sampling and directional Jacobian products 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.