3.1.11 · D3Neural Network Fundamentals

Worked examples — Vanishing and exploding gradients

2,908 words13 min readBack to topic

This page is the "grab-bag of cases" companion to Vanishing and exploding gradients. The parent note built the one master equation; here we exercise it against every situation you could meet: shrinking, growing, borderline, zero, degenerate, real-world, and an exam twist. Guess each answer before reading the steps.

Recall The one formula we keep reusing

For an -layer network the early-layer gradient scales like Here (Greek letter "gamma") is just one number: how much the error signal gets multiplied by each time it crosses one layer. If the signal grows, if it shrinks, if it is preserved. is the number of layers, so is the number of layer-to-layer links the signal must cross. That is the whole engine. Every example below just plugs numbers into .


The scenario matrix

Every case this topic can throw at you falls into one of these cells. The examples that follow each fill one cell — together they cover the whole grid.

Cell What makes it distinct Regime Example
A (small gain) Vanish Ex 1
B (large gain) Explode Ex 2
C (balanced by init) Stable Ex 3
D exactly, limit as Boundary Ex 4
E Degenerate: (dead ReLU / saturation) Zero gradient Ex 5
F Choosing init to force (solve for ) Design Ex 6
G Real-world: NaN loss, diagnose & clip Explode + fix Ex 7
H Exam twist: mixed layers, per-link product Mixed Ex 8

The figure below plots the gradient scaling (vertical axis, on a log scale) against the number of layers (horizontal axis), for four values of the per-layer gain . Read it like this: the red curve (, Cell A) dives straight down — vanishing; the orange curve (, Cell B) climbs straight up — exploding; the green horizontal line (, Cells C/D) stays flat at forever — perfectly preserved; the blue curve (, Cell D) looks flat at first but slowly bends downward, showing that even a hair below eventually vanishes at great depth. The dashed gray line marks the "signal preserved" level of .

Figure — Vanishing and exploding gradients

Cell A — the classic vanish

  1. Compute the per-layer gain. Why this step? is the single number that decides everything; we always find it first. Here it is well below , so we already know we are vanishing.
  2. Count the links. layers links between them. Why this step? The signal is multiplied once per link, not per layer — off-by-one here is the most common error.
  3. Raise to the power. Why this step? Each of the 14 links multiplies by ; compounding fourteen times is what makes it astronomically small.

Verify: , so . Since , the reciprocal is — matches. The layer-1 gradient is ten billion times smaller. It is frozen.


Cell B — the classic explode

  1. Find . Given directly: , so we expect growth. Why this step? Sign of tells the regime before any arithmetic.
  2. Links: . Why this step? Same link-counting rule; a 20-layer net has 19 gaps.
  3. Compound. Why this step? A "modest" per link compounds to nearly six hundred times across 19 links — this is why "it looks close to 1" is a trap.

Verify: use logarithms as an independent check. , times gives . Exponentiating back, — the same value as the direct power . So the gradient is scaled by roughly : weights update wildly, loss NaN. See Gradient Descent for why an oversized step overshoots.


Cell C — balanced by good init

  1. Gain. He init restores the variance ReLU throws away, giving . Why this step? This is the design goal from the parent note — every good init exists to push to .
  2. Links: .
  3. Power. Why this step? raised to any power is — depth becomes free.

Verify: trivially. Neither vanish nor explode; a 50-layer net is trainable. Contrast Ex 1: same idea, different , opposite fate.

Note — a related but distinct fix. Careful init is one way to reach . Residual (skip) connections achieve stable gradients by a different mechanism: the skip makes each layer compute , so its local sensitivity is . The identity gives the gradient a guaranteed additive "pass-through" path of gain exactly , even if the learned branch has a poorly-scaled gain. That is different from tuning the multiplicative gain of a single dense layer to ; ResNets add an extra route rather than fix the existing one. Both are used together in practice.


Cell D — the exact boundary and its limit

  1. Exact boundary. . Why this step? At exactly the product is a constant — the only value that survives infinite depth.
  2. Just below. . Why this step? Any base strictly less than , raised to ever-larger powers, still collapses to — just more slowly. The boundary is a knife-edge.
  3. How slow? Solve for the "half-life in layers": . Why this step? It quantifies "slow": every ~69 layers the signal halves. Deep enough, even vanishes.

Verify: , ; ratio . So is not safe at extreme depth — only exactly is. This is why practitioners chase , not "close to ".


Cell E — the degenerate zero

  1. Insert the zero factor. The product of per-link gains includes one factor with slope : Why this step? A single zero in a product zeroes the entire product — unlike a sum.
  2. Propagate. Why this step? Every layer upstream of the dead one gets multiplied through this , so they all receive exactly zero gradient.
  3. Interpret. Those upstream layers cannot learn — the dead neuron severs the signal path. Why this step? This is the "dead ReLU" failure the parent's third mistake warns about; slope- does not save you if the neuron is on the flat side.

Verify: for any finite , so the whole product is regardless of the other weights. Fixes: LeakyReLU (small nonzero slope) or Batch Normalization to keep pre-activations off the flat zone.


Cell F — design: solve for the init

Here = the number of inputs into a layer (the length of the vector it receives) and = the number of outputs it produces (the length of ). For a square hidden layer .

  1. Write the target. Require . Why this step? We are inverting the master formula — solving for the design variable instead of predicting an outcome.
  2. Plug the slope. , so . Why this step? At tanh does not shrink the signal, so the spectral norm of the weights alone must be .
  3. How an init recipe delivers . We cannot set the spectral norm directly with a random draw, but we can control the entry-wise variance. Xavier sets ; for a square layer this is . Why this step? Random-matrix theory says: for an matrix whose entries are independent with variance , the largest singular value concentrates near — of order , not exploding, but not exactly either. Key caveat: entry-wise variance only controls indirectly and approximately. To pin exactly you would need spectral normalization (divide by its measured largest singular value). Xavier/He get into the safe order-1 band; they do not guarantee the exact value.

Verify: the goal follows from (Step 2, exact algebra). The Xavier recipe with gives , std , and predicted spectral norm — order as claimed, and honestly not exactly , which is why spectral normalization exists when you need locked precisely.


Cell G — real-world diagnosis

  1. Recognise the regime. Loss rising super-linearly then NaN ⇒ exploding gradients (), matching Ex 2's pattern. Why this step? Diagnosis before treatment — vanishing would show flat loss, not blow-up.
  2. Apply clipping. The rule is when . New norm: Why this step? By construction clipping sets the norm exactly to the threshold; the direction (unit vector) is untouched.
  3. Shrink factor. Why this step? It quantifies how violent the explosion was — a overshoot, tamed to a safe step.

Verify: has norm . ✓ Direction preserved since we scaled by a positive scalar. See Backpropagation for where in the pipeline the clip is inserted (after the backward pass, before the optimizer step).


Cell H — exam twist: mixed layers

  1. Multiply the actual factors. The chain rule multiplies them (see Cell E's box), so Why this step? When layers differ we cannot use one ; we must take the true product of per-link gains. Working left to right: , , , .
  2. Compare to a naive average. Arithmetic mean of gains , which raised to the 5th power gives — predicting growth. Why this step? Shows the trap: the arithmetic mean over-predicts. Products care about the geometric mean, not the arithmetic one.
  3. Check with geometric mean. , and . Why this step? Confirms the correct summary statistic for compounding gains is the geometric mean; it reproduces the true product exactly, while the arithmetic mean does not.

Verify: direct product . ✓ Actual behaviour: mild vanishing (), the opposite of the naive-average prediction of growth. Exam lesson: multiply the real factors, never average them.


Active recall

Recall Test yourself

What is on this page, and what is ? ::: is the activation function (sigmoid/tanh/ReLU); is its derivative — the slope backprop multiplies by at each neuron. Which norm does mean on this page, and why that one? ::: The spectral norm (largest singular value); it is exactly the worst-case factor by which can grow or shrink the error vector. Which single number decides vanish vs explode, and what value is the goal? ::: The per-layer gain ; goal . For , , order of magnitude of shrink? ::: . For , , the scaling factor? ::: . Why is still unsafe at extreme depth? ::: Any base still tends to as ; only exactly survives (half-life ~69 layers). One dead-ReLU layer () affects which layers? ::: All layers upstream of it — a zero factor zeroes the whole product. Does Xavier/He init guarantee exactly? ::: No — it puts in the order-1 band via entry-wise variance; exact control needs spectral normalization. Clipping to threshold gives what norm and shrink factor? ::: Norm ; shrink factor ; direction unchanged. For mixed per-link gains, which mean summarises the product? ::: The geometric mean, not the arithmetic mean.