---
title: Recurrent networks and sequences
heading: Networks with state, the recurrent network as a nonlinear IIR filter, backpropagation through time and why its gradients explode or vanish, clipping, and the gated LSTM and GRU cells that carry memory across long sequences
eyebrow: S14 · Lesson 27 · Recurrent networks
xp: 50
---

::: hook
A feedforward network sees each input on its own. Speech, sensor streams and text need memory of what came before. A recurrent network adds it the way an IIR filter does: by feeding its own output back. That feedback brings a filter's problems along. A pole inside the unit circle forgets the past exponentially fast, one outside it blows up, and training a recurrent network runs into the same two failures in its gradients.
:::

::: play
- The curves show how much a hidden state still depends on something that happened k steps earlier.
- The solid curve is a simple recurrent network whose feedback multiplies the state by a gain ρ each step (the weight times the activation's slope): below 1 it fades exponentially, above 1 it explodes.
- The dashed curve is an LSTM's memory cell, multiplied each step by its forget gate σ(b): a bias of 3 or more holds memory for dozens of steps, and the gradient through the cell follows the same product.
:::

```sim plot
view: graph
x: k = 0..100
y: g = 0.000001..1000000 log
slider: p = 0.5..1.5 = 0.9
slider: b = -2..8 = 3
plot: p^k | label: simple recurrent network
plot: (1/(1 + exp(-b)))^k | dashed | label: LSTM cell
```

::: predict
## A linear recurrent network updates $h_t = 0.9h_{t-1} + x_t$. How much does an input from 50 steps ago still contribute to $h_t$?

- [ ] Nothing at all
- [x] About 0.5% of its original size
- [ ] About 5%
- [ ] About 45%

::: reveal
The input is multiplied by 0.9 at every step: $0.9^{50}$ = 0.0052. The network is a one-pole filter with its pole at 0.9 and a memory time constant of $-1/\ln 0.9$ = 9.5 steps. Remembering something for hundreds of steps needs a pole within a fraction of a percent of 1, which a plain recurrent network can't keep while also learning.
:::
:::

::: nameit
## Recurrent networks

A recurrent network keeps a hidden state $\mathbf h_t$ and updates it from the previous state and the current input:
$$\mathbf h_t = \tanh(W\mathbf h_{t-1} + U\mathbf x_t + \mathbf b), \qquad \mathbf y_t = V\mathbf h_t + \mathbf c$$
The same weights serve every step, so with H hidden units and D inputs the recurrence has $H(H + D) + H$ parameters whatever the sequence length. Linearized, it is a multichannel IIR filter whose poles are the eigenvalues of W (times the activation slopes): stable when they lie inside the unit circle.

## Backpropagation through time

Unrolled over T steps, the network is a T-layer feedforward network with shared weights, and backpropagation applies. The gradient of the state at time t with respect to the state k steps earlier is a product of k Jacobians, $\prod \text{diag}(\phi')W$, so its size grows or shrinks roughly as $\rho^k$, with ρ the largest gain per step. With ρ < 1 the gradient **vanishes**, and the network can't learn dependencies longer than a few time constants; with ρ > 1 it **explodes**. **Gradient clipping** rescales the gradient whenever its norm exceeds a threshold θ, $\mathbf g \leftarrow \mathbf g\,\theta/\|\mathbf g\|$, which cures explosions but not vanishing. **Truncated** backpropagation stops after a fixed window of steps to bound the cost.

## Gated cells

The **LSTM** adds a memory cell updated additively, under gates that are sigmoids of the input and state:
$$\mathbf c_t = \mathbf f_t \odot \mathbf c_{t-1} + \mathbf i_t \odot \mathbf g_t, \qquad \mathbf h_t = \mathbf o_t \odot \tanh(\mathbf c_t)$$
Along the cell, the gradient is multiplied only by the forget gates, which the network can hold near 1; initializing the forget gate's bias to 1 or more starts it with long memory. Four gates and candidates give $4[H(H + D) + H]$ parameters. The **GRU** merges the cell and state with two gates and a candidate: $3[H(H + D) + H]$.
:::

::: example
## Count the parameters of a simple recurrent layer, a GRU and an LSTM, each with 256 hidden units on 100 inputs.

::: solution
1. **One block.** Recurrent, input and bias weights:
   $$\begin{aligned} &256 \times (256 + 100) + 256 \\ &= 91{,}392 \end{aligned}$$
2. **Count the blocks.** The simple layer has one, the GRU three (update gate, reset gate, candidate) and the LSTM four (forget, input and output gates, candidate):
   $$\begin{aligned} \text{GRU} &= 3 \times 91{,}392 \\ &= 274{,}176 \\ \text{LSTM} &= 4 \times 91{,}392 \\ &= 365{,}568 \end{aligned}$$
3. **Work per step.** Each step costs about as many multiply-adds as parameters, so the LSTM is four times the work of a simple layer of the same width.

**Answer:** the simple layer has 91,392 parameters, the GRU 274,176 and the LSTM 365,568.
:::
:::

::: example
## An LSTM's forget gate is initialized with a bias of 1, or of 5, and inputs that leave its activation near the bias. How long does the cell remember?

::: solution
1. **Bias of 1.** σ(1) = 0.731, so the cell's contents fall by that factor each step, a time constant of
   $$\begin{aligned} \tau &= -1/\ln 0.731 \\ &= 3.2\ \text{steps} \end{aligned}$$
   barely better than a simple network.
2. **Bias of 5.** σ(5) = 0.9933 gives
   $$\tau = 149\ \text{steps}$$
3. **Why start positive.** That is why forget biases are initialized positive: training can shorten a memory that starts long more easily than it can discover one that starts short, since the gradient through a short memory has already vanished.

**Answer:** the cell remembers for about 3.2 steps with a bias of 1, and about 149 steps with a bias of 5.
:::
:::

::: example
## A 10,000-step sequence is trained with backpropagation truncated to 100 steps. How much gradient is lost for a simple network with per-step gain 0.95, and for an LSTM cell with forget gate 0.999?

::: solution
1. **Simple network.** Contributions from beyond the window are scaled by at most
   $$0.95^{100} = 0.006$$
   so truncation loses almost nothing, because the network couldn't use those steps anyway.
2. **LSTM.** Its contributions are scaled by
   $$0.999^{100} = 0.90$$
   so truncation throws away dependencies the cell could carry.
3. **What to do.** Long-memory models need longer windows, or carrying the state across windows while cutting only the gradient.

**Answer:** the simple network's lost contributions are scaled by at most 0.006, so almost nothing is lost; the LSTM's are scaled by 0.90, so truncation discards dependencies it could use.
:::
:::

::: check
kind: parts
given: H = 32 | 128 | 512; D = 10 | 64 | 300; K = 2 | 20

## A simple recurrent layer has {H} hidden units on {D} inputs, followed by a linear output layer of {K} units.

::: part
answer: H*(H + D) + H
unit: parameters
tolerance: 0

### How many parameters does the recurrent layer have?

::: misses
- [H*D + H] The state feeds back through an H × H matrix too.
- [any] $H(H + D) + H$.
:::
:::

::: part
answer: K*(H + 1)
unit: parameters
tolerance: 0

### And the output layer?

::: misses
- [any] $K(H + 1)$.
:::
:::
:::

::: check
kind: parts
given: H = 64 | 256 | 1024; D = 32 | 128 | 512

## A recurrent layer with {H} hidden units reads {D} inputs per step.

::: part
answer: 4*(H*(H + D) + H)
unit: parameters
tolerance: 0

### How many parameters does an LSTM layer have?

::: misses
- [H*(H + D) + H] That's a simple layer; the LSTM has four such blocks.
- [3*(H*(H + D) + H)] That's a GRU.
- [any] $4[H(H + D) + H]$.
:::
:::

::: part
answer: 3*(H*(H + D) + H)
unit: parameters
tolerance: 0

### And a GRU layer?

::: misses
- [any] $3[H(H + D) + H]$.
:::
:::
:::

::: check
kind: parts
given: w = 0.5 | 0.9 | 0.99; k = 5 | 20 | 100

## A linear recurrent unit updates $h_t = \given{w}h_{t-1} + x_t$.

::: part
answer: w^k
tolerance: 0.5%

### How much of an input from {k} steps ago remains in $h_t$?

::: misses
- [1 - w^k] That's the part that has faded.
- [any] $w^k$.
:::
:::

::: part
answer: -1/ln(w)
unit: steps
tolerance: 0.5%

### What is its memory time constant?

::: misses
- [1/(1 - w)] That's close, but the exact time constant is $-1/\ln w$.
- [any] $-1/\ln w$.
:::
:::
:::

::: check
kind: parts
given: p = 0.7 | 0.9 | 1.1 | 1.3; T = 10 | 50

## The backward signal through a recurrent network is multiplied by a gain of about {p} per step.

::: part
answer: p^T
tolerance: 0.5%

### By what factor has it changed after {T} steps?

::: misses
- [p*T] The factors multiply.
- [any] $\rho^T$.
:::
:::

::: part
answer: ln(1000)/abs(ln(p))
unit: steps
tolerance: 0.5%

### After how many steps has it changed by a factor of 1000?

::: misses
- [any] $\ln 1000/|\ln\rho|$.
:::
:::
:::

::: check
kind: parts
given: b = 0 | 1 | 3 | 6

## An LSTM's forget gate sits at its bias, {b}.

::: part
answer: 1/(1 + exp(-b))
tolerance: 0.5%

### What fraction of the cell's contents survives each step?

::: misses
- [any] σ(b).
:::
:::

::: part
answer: -1/ln(1/(1 + exp(-b)))
unit: steps
tolerance: 0.5%

### What is the cell's memory time constant?

::: misses
- [any] $-1/\ln\sigma(b)$.
:::
:::
:::

::: check
kind: parts
given: n = 8 | 40 | 300; c = 1 | 5; g = 2 | -6

## A gradient's norm is {n}, and training clips it to norm {c}.

::: part
answer: c/n
tolerance: 0.5%

### By what factor is the gradient scaled?

::: misses
- [n/c] Clipping shrinks it.
- [any] θ/‖g‖.
:::
:::

::: part
answer: g*c/n
tolerance: 0.5%

### What does a component of {g} become?

::: misses
- [c] Clipping by norm scales every component by the same factor, keeping the direction.
- [any] Scale it by θ/‖g‖.
:::
:::
:::

::: check
kind: choice

## Why can an LSTM learn dependencies hundreds of steps long when a simple recurrent network can't?

- [ ] It has more parameters
- [ ] Its activations are linear
- [x] Its memory cell is updated by adding to a gated copy of itself, so the gradient along the cell is multiplied only by forget gates the network can hold near 1, rather than by a weight matrix and activation slopes at every step
- [ ] It processes the sequence backward as well as forward

::: misses
- [1] Parameter count doesn't stop gradients vanishing.
- [2] Its gates and outputs are nonlinear.
- [4] That's a bidirectional network, a different idea.
:::
:::

::: check
kind: derivation
vars: w = -0.95..0.95, u = 0.1..5, k = 0..50, x = -3..3

## A linear recurrent unit updates $h_t = wh_{t-1} + ux_t$, starting from zero.

::: step
answer: u*w^k

### What is $h_k$ after a unit impulse at time 0?
:::

::: step
answer: u*x/(1 - w)

### What does $h_t$ settle to under a constant input x?
:::

::: right
Right. A one-pole filter: the impulse response is geometric and the DC gain is u/(1 − w).
:::
:::

::: explain
## Why do gradients in a recurrent network vanish or explode over long sequences?

::: model
Backpropagating from a late output to an early input passes through every step in between, and each step multiplies the signal by the recurrent weights and the activation's slope. A product of many such factors behaves like a power: if the typical gain per step is below one, the gradient shrinks exponentially and the network can't learn that early inputs matter; if it's above one, the gradient grows exponentially and training diverges. It's the same as a feedback filter with its pole inside or outside the unit circle. Clipping tames explosions, and gated cells avoid vanishing by giving the memory an additive path whose gain the network controls directly.
:::
:::

::: practice
::: check
given: H = 100 | 400; D = 20 | 200
answer: 4*(H*(H + D) + H)
unit: parameters
tolerance: 0

## LSTM parameters: H = {H}, D = {D}?

::: misses
- [any] $4[H(H + D) + H]$.
:::
:::

::: check
given: w = 0.8 | 0.95 | 0.995
answer: -1/ln(w)
unit: steps
tolerance: 0.5%

## Memory time constant at gain {w}?

::: misses
- [any] $-1/\ln w$.
:::
:::

::: check
given: b = 0 | 1 | 2 | 3 | 4 | 5
answer: -1/ln(1/(1 + exp(-b)))
unit: steps
tolerance: 0.5%

## Cell time constant at forget bias {b}?

::: misses
- [any] $-1/\ln\sigma(b)$.
:::
:::
:::
