Backpropagation Through Time

Backpropagation through time (BPTT) trains an RNN by unrolling it over the steps of a sequence. The unrolled network is a deep feedforward network with the same weights in every step. Ordinary backpropagation runs on it. In a stacked RNN the gradients flow down through the layers and backward through time.

Write the vanilla RNN as with pre-activation . Here , , and . The loss is , or alone for a many-to-one task. Gradients with respect to vectors are row vectors, and . Each shared weight collects one term per step:

The Jacobian of one step is . A loss at step reaches an earlier state through a product of Jacobians:

The backward pass gets all of these from the recursion , which starts at .

The product has factors, so its size changes geometrically with the distance:

  • Vanishing gradients: if at every step, the gradient shrinks at least as fast as . With , steps multiply it by at most .
  • Exploding gradients: in a linear RNN, and the product is . If the spectral radius exceeds , almost every gradient grows like . With , steps multiply it by about . If , it vanishes.
  • tanh: the derivative lies in , so . Saturated units shrink the gradient further. The sigmoid has .
  • ReLU: the derivative is or , so active units pass through unchanged. No factor below limits a growing product, and the state itself can grow without bound.

A stable forward pass, in which old inputs fade, therefore gives an exponentially decaying backward pass. This is why RNNs find long-range dependencies hard to learn.

The forward pass takes sequential steps of work each, and the backward pass costs about twice as much. BPTT stores every , so memory grows as per sequence and layer. A nonlinear RNN cannot run its steps in parallel. A linear recurrence can, with a parallel scan of depth .

Not Taught in Lecture

The lecture derives the Jacobian product and the vanishing case. The exploding case and the comparison of tanh and ReLU come from the homework. The cost counts and the parallel scan come from the discussion section. The norm bounds follow Pascanu, Mikolov and Bengio (2013), and the scan operator follows Blelloch (1990).

Intuition

To train an RNN, we need to know how a change to changes the losses at later steps. Unrolled, the loop becomes a chain of copies of the same layer. Each copy uses once, and the gradient for is the sum of the gradients of all copies. To reach a state steps back, the gradient passes through Jacobians. If each Jacobian multiplies the gradient by , then of them multiply it by about . The figure plots the factor on a log scale.

\usepackage{tikz}
\begin{document}
\definecolor{hot}{HTML}{D9483B}
\definecolor{cold}{HTML}{2F80ED}
\definecolor{mid}{HTML}{8A8A8A}
\begin{tikzpicture}[x=0.13cm,y=1cm]
\draw[->,thick] (0,-2.6) -- (0,2.7);
\draw[->,thick] (0,-2.6) -- (54,-2.6) node[right] {$k$};
\foreach \v/\l in {-2/{10^{-2}},-1/{10^{-1}},0/{1},1/{10},2/{10^{2}}} {\draw (0,\v) -- (-1,\v) node[left] {$\l$};}
\foreach \x in {0,10,20,30,40,50} {\draw (\x,-2.6) -- (\x,-2.7) node[below] {$\x$};}
\node[below] at (25,-3.1) {steps back, $k = t-s$};
\node[rotate=90] at (-9,0) {factor $\rho^{k}$};
\draw[cold,very thick] (0,0) -- (50,-2.288) node[right] {$\rho = 0.9$};
\draw[cold,very thick,dashed] (0,0) -- (50,-1.114) node[right] {$\rho = 0.95$};
\draw[mid,very thick] (0,0) -- (50,0) node[right] {$\rho = 1$};
\draw[hot,very thick,dashed] (0,0) -- (50,1.059) node[right] {$\rho = 1.05$};
\draw[hot,very thick] (0,0) -- (50,2.070) node[right] {$\rho = 1.1$};
\fill[cold] (20,-0.915) circle (2pt) node[below left] {$0.12$};
\fill[hot] (20,0.828) circle (2pt) node[above left] {$6.7$};
\fill[cold] (50,-2.288) circle (2pt);
\fill[hot] (50,2.070) circle (2pt);
\end{tikzpicture}
\end{document}

In a linear RNN, . The same power of sets how much still affects . If old inputs fade from the state, their gradients fade at the same rate. Long memory with usable gradients needs close to . A value slightly below still vanishes over long spans, and a value slightly above explodes.

Properties

(Short Paths Dominate) Long-range terms make up a tiny share of the total gradient, so gradient descent tends to fit short-range patterns first.

The gradient for is a double sum over a loss step and an earlier step . Each term contains the factor , which passes through Jacobians. With , this factor has norm at most times when . The total gradient can still be large, and short-range terms make up almost all of it. The term for inputs steps apart can be smaller than the noise in a minibatch gradient. A loss at every step adds more terms to the double sum. Most of the new terms are short-range as well.

(Eigenvalues Versus Norms) The spectral radius decides the long-run size of , while the operator norm bounds every single step.

For any square matrix, as exactly when . The powers of a matrix far from symmetric can still grow over the first few steps. The matrix has but . Its powers have norms , , , and for to . They fall to at . The condition rules out such growth, because (4.9b Operator Norm). For a symmetric the two quantities agree, .

(Tanh Versus ReLU) A tanh RNN keeps its state bounded and its gradients tend to vanish, while a ReLU RNN can explode in both passes.

With tanh, every entry of stays in for any weights. Large pre-activations push units toward , where the derivative is near . A recurrent weight above can then still give a Jacobian well below . With ReLU, , where is diagonal with a for each active unit and otherwise. Active units pass the gradient through without shrinking it. If stretches vectors of active units, the state and the gradient both grow geometrically. Inactive units block the gradient completely. See 3. Activation Functions for the derivatives.

(Cost and Memory) BPTT keeps every state from the forward pass, so memory grows with and long sequences are split into blocks.

The backward recursion needs and at every step. For tanh, , so storing the states is enough. A batch of sequences through layers stores numbers. The steps also cannot run in parallel. Step needs , so a GPU must finish each step before it starts the next. In a stacked RNN, the cells with the same value of do not depend on each other. The stack therefore needs sequential rounds instead of . Traces that do not fit in memory are split into blocks of consecutive steps. The learned Kalman filter of 5.3.1. RNNs trains this way.

(Parallel Scan) A linear recurrence can be computed in parallel rounds, because composing affine steps is associative.

Each step of is the affine map , stored as the pair . Applying step and then step gives the pair

This operation is associative, so any grouping of the steps gives the same result. With , is the second entry of the combined pair for steps to . A prefix scan computes all combined pairs. The Hillis-Steele scan takes rounds and work. The Blelloch scan takes about rounds and work. With a dense , each combine is a matrix product that costs . Scans are therefore practical mainly when is diagonal. The backward pass of a linear recurrence is another linear recurrence, run in reverse. It can use a scan too. A nonlinear breaks the method, because compositions of maps do not keep a fixed small form.

(Gradient Clipping) Rescaling any gradient whose norm exceeds a threshold prevents one exploding gradient from producing a huge update.

Not Taught in Lecture

Gradient clipping follows Pascanu, Mikolov and Bengio (2013) and Goodfellow et al., Deep Learning, §10.11.1.

Clipping by norm replaces the gradient of all parameters with

The direction stays the same, and the step length is at most for learning rate . Where the loss rises sharply, one exploding gradient can otherwise move the parameters far from where training was. Clipping does nothing for vanishing gradients. Those need changes to the architecture, such as the gated cells in 5.3.1. RNNs.

(Truncated BPTT) Backpropagating through only the last steps caps memory at and ignores longer gradient paths.

Not Taught in Lecture

Truncated BPTT goes back to Williams and Peng (1990).

Truncated BPTT splits a long sequence into chunks of steps. The forward pass carries the hidden state across chunk boundaries, so the state still holds older information. The backward pass stops at the start of each chunk and treats the incoming state as a constant. Each chunk gives one parameter update, so training on a long stream updates more often. Gradient paths longer than steps are cut. The network then gets no direct gradient for dependencies that span more than steps.

Derivation

We want the gradient of with respect to the shared matrix . Give each step its own copy , and set every copy equal to . The loss depends on only through the copies, so the multivariable chain rule gives

The Easy example below checks this rule against direct differentiation on a scalar model. Copy enters only through . Entry of changes at rate , so . Since acts entrywise, . The state affects through and through , which gives the backward recursion

Unrolling it gives , with the empty product for equal to . Each term is the Jacobian product from the callout. Summing over gives the formula for . The same steps with or in place of give the gradients for and .

Examples

(Easy) Gradient of a Room-Temperature Model

A room’s temperature deviation from its setpoint follows , with . The room keeps the fraction of its deviation at each step, and the heater adds with . The heater commands are , and . The loss asks for zero deviation at every step.

(Medium) Same Weight, Two Activations

A one-unit RNN computes with and a constant input . Compare with .

(Medium) Memory Budget for Speech

A speech model stacks RNN layers with units. It reads audio features per frame at frames per second. One batch holds clips of seconds, in 32-bit floats.

(Hard) A Parallel Scan by Hand

A scalar linear recurrence has and inputs . Each step is the pair , and pairs combine by .

See Also