Taming Gradient Decay in a 40-Layer Net and a 100-Step RNN
Machine LearningModel answerLast updated
Explain why gradients shrink or blow up with depth and time, and design a combined fix using activations, initialization, skip connections, normalization, and gated or attention-based sequence models.
Context
A content-recommendation team is building a ranking model over long user histories. They want to grow a fully connected scoring tower from 6 layers to 40 layers. They also want to try a plain unrolled RNN over click sequences of length T = 100.
Both models use sigmoid activations and default weight initialization. In training, the loss flattens out almost immediately. Gradients reaching the earliest layers are many orders of magnitude smaller than gradients at the output side.
What to cover
-
Derivation. For an
L-layer network withh_l = f(W_l h_{l-1} + b_l), write the chain-rule expression for the gradient of the loss with respect toW_1. Define the per-layer JacobianJ_l = ∂h_l / ∂h_{l-1}. Show how the magnitude (e.g. spectral norm) of these Jacobians makes gradients shrink or grow exponentially withL. -
Mitigations.
- Activations and initialization: Compare sigmoid, ReLU, and Leaky ReLU/GELU. State the variance-preservation condition that Xavier/Glorot and He/Kaiming initialization aim for, and explain why each initialization should be matched to its activation.
- Residual connections: With
h_l = h_{l-1} + F(h_{l-1}), derive∂h_L / ∂h_land explain why this gives gradients a direct path to early layers. - Normalization: Compare BatchNorm and LayerNorm, and explain how normalizing layer inputs stabilizes the backward pass.
-
Optimization vs. regularization. Classify each technique as mainly helping optimization or generalization, and point out where the two goals conflict.
-
Feed-forward vs. recurrent. Contrast how the problem appears in a 40-layer feed-forward net and in an RNN unrolled for 100 steps. Explain why initialization alone is usually not enough for a vanilla RNN, and how LSTM/GRU cells or Transformers address it.
Finish with a concrete recommended setup for both models.
Hints
Hint 1
Backprop through depth multiplies one Jacobian per layer, and each Jacobian is diag(f'(z)) times a weight matrix. Bound the product by the product of norms and plug in the sigmoid's maximum slope of 1/4.
Hint 2
For initialization, ask what keeps Var(z) the same from one layer to the next. Count how ReLU changes the second moment of its input, and check what happens when you mismatch the scheme and the activation.
Hint 3
For residual blocks, expand the product of (I + ∂F/∂h) and look at the identity term. For the RNN, notice that the same recurrent matrix appears at every step, so eigenvalues are raised to the power T − k.
Hint 4
For the optimization/regularization split, think about which techniques change the loss landscape and which change the function class or add noise.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Why depth multiplies Jacobians
Let z_l = W_l h_{l-1} + b_l and h_l = f(z_l). The layer Jacobian is
J_l = ∂h_l/∂h_{l-1} = diag(f'(z_l)) · W_l
The gradient for the first weight matrix is
∂L/∂W_1 = [ diag(f'(z_1)) · J_2ᵀ J_3ᵀ ··· J_Lᵀ · ∂L/∂h_L ] · h_0ᵀ
So the signal passes through L−1 Jacobians. By submultiplicativity:
‖∂h_L/∂h_1‖ ≤ ∏ ‖diag(f'(z_l))‖ · ‖W_l‖ ≤ (γ · σ_max)^(L−1)
where γ = max|f'| and σ_max is the largest singular value of the weights. If the per-layer gain is below 1, gradients vanish geometrically. If it is above 1, they explode.
For sigmoid, f' ≤ 0.25. Even with σ_max ≈ 1, a 40-layer stack gives a bound of about 0.25^39 ≈ 10⁻²⁴. Saturated units push f' toward 0 and make it worse. This matches the symptom: the bottom of the tower receives essentially no learning signal and the loss plateaus.
2. Mitigations
Activations
| Activation | Derivative | Comment |
|---|---|---|
| Sigmoid | ≤ 0.25, ~0 when saturated | Contracts at every layer, not zero-centered |
| ReLU | 1 for z>0, else 0 | No shrinkage on active units, but units can die |
| Leaky ReLU / GELU | Nonzero for z<0 | Avoids dead units; GELU is smooth and common in Transformers |
Initialization
For z = W h with n_in inputs, Var(z) = n_in · Var(W) · E[h²]. We want forward activation variance and backward gradient variance to stay constant across layers:
- Forward:
n_in · Var(W) · gain = 1 - Backward:
n_out · Var(W) · gain = 1
Xavier/Glorot uses Var(W) = 2/(n_in + n_out), a compromise between the two conditions. It assumes an activation that is roughly linear near zero (tanh).
He/Kaiming uses Var(W) = 2/n_in. The factor 2 compensates for ReLU zeroing half the pre-activations, since E[ReLU(z)²] = Var(z)/2.
Pairing matters. Xavier with ReLU loses about a factor of 2 in variance per layer, roughly 2⁻⁴⁰ over 40 layers. He with sigmoid cannot repair the 1/4 slope cap and pushes units into saturation. Also, initialization only sets gain ≈ 1 at step 0; it does not hold it there as weights change.
Residual connections
With h_l = h_{l-1} + F_l(h_{l-1}):
∂h_L/∂h_l = ∏_{k=l+1}^{L} (I + ∂F_k/∂h_{k-1}) = I + Σ_k ∂F_k/∂h_{k-1} + higher-order terms
The identity term delivers ∂L/∂h_L to every layer unattenuated, even if every ∂F_k is tiny. The gradient becomes a sum over many paths, including very short ones, instead of one long product. Practical points:
- Keep the skip path free of nonlinearities (pre-activation / pre-LN blocks put norm and activation inside F).
- Initialize the last layer in each branch near zero so blocks start as identity maps.
- Very deep residual stacks can still grow activations; scaling the branch or using LayerNorm controls that.
Normalization
- BatchNorm normalizes each feature across the batch. LayerNorm normalizes across the features of one example, so it does not depend on batch size and works for sequences and small or variable batches.
- Both keep pre-activations near zero mean and unit variance. Sigmoid/tanh stay out of saturation, so f' stays near its maximum, and ReLUs are less likely to die.
- Scale invariance:
Norm(αWx) = Norm(Wx), so∂L/∂(αW) = (1/α) ∂L/∂W. Weights that grow receive smaller gradients, which is self-stabilizing. - The normalization Jacobian projects out the mean and radial directions, so per-layer gain cannot drift arbitrarily.
3. Optimization vs. regularization
- Mainly optimization: activation choice, He/Xavier init, residual connections, LayerNorm, gradient clipping, warmup.
- Mixed: BatchNorm. Its main job is optimization, but batch-statistic noise acts as a mild regularizer that depends on batch size.
- Mainly regularization: dropout, weight decay, early stopping, data augmentation.
Trade-offs:
- Making a 40-layer net trainable unlocks capacity, which on engagement data can memorize heavy users. You need regularization alongside it.
- With normalization, weight decay mostly changes the effective learning rate rather than constraining the function.
- Dropout inside residual branches injects variance into the residual stream, and BatchNorm statistics can mismatch between train and inference.
4. Feed-forward vs. recurrent
Feed-forward (40 layers). Each W_l is separate, so the Jacobian product involves roughly independent matrices. Per-layer gain can be tuned near 1 with init, normalization, and skips. The failure is that lower layers do not learn.
RNN (T = 100). With h_t = f(W_hh h_{t-1} + W_x x_t):
∂h_T/∂h_k = ∏_{t=k+1}^{T} diag(f'(a_t)) · W_hh
The same W_hh is applied every step, so components along its eigen-directions scale like λ^(T−k). If the spectral radius is below 1 (after the f' shrinkage), gradients vanish; above 1, they explode. The failure is temporal: the model learns short-range patterns but cannot credit a click at step 100 to an event at step 1.
Why init is not enough. Orthogonal init sets the spectral radius to 1, but diag(f') still shrinks the product. That condition is a knife edge that training quickly perturbs, and with tied weights you cannot adjust gain per layer.
Fixes.
- LSTM:
c_t = f_t ⊙ c_{t-1} + i_t ⊙ g_t, so∂c_t/∂c_{t-1} ≈ diag(f_t). The path is additive and learned per step; with forget gates near 1 the gradient survives. Initializing the forget bias to about 1 helps. This is the recurrent analogue of a residual connection. GRU achieves a similar effect with(1 − z_t) ⊙ h_{t-1}. - Transformer: attention links any two positions in O(1) path length rather than O(T). Residuals plus LayerNorm handle depth. The O(T²) cost is fine at T = 100.
- Gradient clipping handles the exploding side, which gating does not fully remove.
Recommended setup
- Tower: GELU or ReLU, He initialization, pre-LN residual blocks with zero-initialized final branch layers, and modest dropout or weight decay.
- Optimizer: AdamW with learning-rate warmup and global-norm gradient clipping.
- Sequence model: a Transformer encoder (or an LSTM/GRU with forget bias ≈ 1 as a cheaper baseline).
- Monitoring: log per-layer gradient norms. A healthy model has roughly similar norms across depth.
Common mistakes
- Claiming ReLU alone fixes vanishing gradients (dead units and mismatched init remain).
- Pairing Xavier with ReLU, or He with sigmoid.
- Saying BatchNorm is purely a regularizer.
- Treating the RNN as just a deep feed-forward net, ignoring that the weights are tied.
- Forgetting that clipping addresses explosion, not vanishing.