For a vanilla RNN ht=tanh⁡(Wht−1+Uxt+b) with loss L=∑tLt, how does backpropagation through time give ∂LT/∂hk for k<T, and why do gradients over long time spans vanish or explode?

Sequence models and transformers, Recurrent networks
Level L3 Intermediate. Length Long. Nature Mat Mathematical.

What's being asked

Whether you can unroll the recurrence, write the gradient as a product of per-step Jacobians, and bound it using the singular values of W.

Key idea

Here ht is the hidden state at step t, xt the input, and W,U,b are shared across time. The one-step Jacobian is Jt=∂ht∂ht−1=diag⁡(1−ht2) W. Chaining these, latest step on the left, gives ∂hT∂hk=JTJT−1⋯Jk+1, so ∂LT∂hk=(JTJT−1⋯Jk+1)⊤∂LT∂hT. If γ≤1 bounds tanh⁡′ and σmax⁡(W) is the largest singular value of W, then ∥∂hT∂hk∥≤(γ σmax⁡(W))T−k, and so ∥∂LT∂hk∥≤(γ σmax⁡(W))T−k∥∂LT∂hT∥.

Steps

  1. Write the pre-activation at=Wht−1+Uxt+b, so ht=tanh⁡(at). Use tanh⁡′(at)=1−ht2, applied element-wise.
  2. One-step Jacobian: Jt=∂ht∂ht−1=diag⁡(1−ht2) W, where diag⁡(⋅) puts a vector on the diagonal of a matrix.
  3. Chain over time, with the latest step on the left: ∂hT∂hk=JTJT−1⋯Jk+1. So ∂LT∂hk=(JT⋯Jk+1)⊤∂LT∂hT. The order matters, because matrix products do not commute.
  4. Bound each factor: ∥Jt∥≤∥diag⁡(1−ht2)∥ ∥W∥≤γ σmax⁡(W), with γ≤1. Hence ∥∂hT∂hk∥≤(γ σmax⁡(W))T−k, and the gradient norm is at most this times ∥∂LT∂hT∥. If σmax⁡(W)<1/γ, the gradient vanishes geometrically (a sufficient condition). Exploding requires σmax⁡(W)>1/γ (a necessary condition, not a sufficient one).
  5. Weight gradient: W is shared, so ∂L∂W=∑t∑k≤t∂Lt∂ht∂ht∂hk∂+hk∂W, where ∂+ means the immediate dependence at step k (holding hk−1 fixed). Long-range terms (t−k large) are exponentially small, so the RNN learns mainly short-range dependencies.
  6. Remedies: gradient clipping, g←τg/∥g∥ when ∥g∥>τ (rescale the gradient g to norm τ), for exploding gradients; LSTM or GRU gating and orthogonal initialisation of W; and truncated BPTT (backpropagating through only the last few steps) to cut cost.

Common mistakes

How long your answer should be

About a page; 6–8 minutes.

Last checked on 4 December 2026.

Read this

Previous in Sequence models and transformers: In scaled dot-product attention, why divide QK⊤ by dk, where Q and K are the query and key matrices and dk is the key dimension?
Next in Sequence models and transformers: What are the LSTM cell equations, and why does the cell state ease the vanishing-gradient problem of a vanilla RNN? How does a GRU differ, and how many parameters does each have for input size 100 and hidden size 128?