Recurrent Neural Networks

A recurrent neural network (RNN) processes a sequence one time step at a time. It keeps a hidden state that summarizes the inputs seen so far. Time runs over , with input and output . The model is causal, which means that depends only on . Signal processing offers two causal ways to map inputs to outputs:

  • FIR filter (finite impulse response): , with taps . Tap sets how much the input from steps ago counts. This is a convolution over time with kernel size , and it ignores inputs older than steps.
  • IIR filter (infinite impulse response): and . A finite hidden state carries the past forward, so one input can affect every later output. The steps must run in order.

A CNN shares weights across space, like an FIR filter. An RNN shares weights across time, like an IIR filter.

The linear time-invariant (LTI) state-space model is the simplest IIR filter:

with , and . Unrolling the recursion gives

With , the output has the FIR form with taps . These taps exist for every , so their number has no fixed limit.

The traditional RNN puts a nonlinearity , usually sigmoid or tanh, inside the state update:

with , , , and . The same parameters act at every step, so the parameter count does not depend on . The initial state is usually . An extra output term , with , works like a residual connection.

A vanilla RNN layer outputs its hidden state directly, which lets layers stack. A stacked RNN feeds the states of layer to layer as its inputs, with :

Deep stacks use vertical residual connections, vertical MLPs and LayerNorm at each time step. They do not use BatchNorm, and no normalization may use future time steps.

The same network serves several task shapes:

  • Many-to-one: the network reads the whole sequence and predicts once from , as in classifying a sentence.
  • Aligned many-to-many: the network predicts at every step, as in labeling each frame of an audio clip.
  • One-to-many: the network starts from one input, such as an image, and produces a sequence of outputs.

Not Taught in Lecture

The names of the task shapes come from the homework, not the lecture. The lecture’s examples put a loss on every output, which is the aligned many-to-many shape.

Homework Notation

The homework writes the RNN layer as and adds the readout . In the lecture’s symbols, , , , , and . The lecture steps from to , and the homework steps from to . Both describe the same recurrence. The Kalman filter section below uses for the hidden state of a system, not for the input.

Intuition

Speech, text, control signals and sensor readings arrive in order. A prediction at time may depend on inputs from long before. A model can see the past in two ways. One is a fixed window of recent inputs, as in an FIR filter or a 1D convolution over time. The other is a running summary that the model updates at every step, as in an IIR filter. A running sum needs one number of state, and each new input is added to it. An FIR filter that reaches back equally far needs one tap per past step. An RNN learns its own update rule for the summary.

\usepackage{tikz}
\usetikzlibrary{arrows.meta}
\begin{document}
\definecolor{hot}{HTML}{D9483B}
\definecolor{cold}{HTML}{2F80ED}
\definecolor{grn}{HTML}{2F9E44}
\begin{tikzpicture}[>={Stealth[length=2.5mm]}, box/.style={draw,thick,minimum width=1.1cm,minimum height=0.8cm}]
\node (h0) at (0,0) {$\mathbf{h}_0$};
\foreach \t in {1,2,3,4} {
\node[box] (h\t) at (2.4*\t,0) {$\mathbf{h}_{\t}$};
\node (u\t) at (2.4*\t,-1.7) {$\mathbf{u}_{\t}$};
\node (y\t) at (2.4*\t,1.7) {$\mathbf{y}_{\t}$};
\draw[->,cold,thick] (u\t) -- node[left] {$\mathbf{B}$} (h\t);
\draw[->,grn,thick] (h\t) -- node[left] {$\mathbf{C}$} (y\t);
}
\foreach \s/\t in {0/1,1/2,2/3,3/4} \draw[->,hot,thick] (h\s) -- node[above] {$\mathbf{W}$} (h\t);
\draw[->,thick] (2.4,-2.5) -- node[below] {time} (9.6,-2.5);
\node at (6,-3.4) {each box computes $\mathbf{h}_t=\sigma(\mathbf{W}\mathbf{h}_{t-1}+\mathbf{B}\mathbf{u}_t+\mathbf{b}_h)$};
\end{tikzpicture}
\end{document}

The figure unrolls an RNN over four steps. Every step applies the same to the previous state and the same to the new input. The same reads out every output. The nonlinearity lets the update keep summaries that no linear system can, such as the largest value so far. Each needs , so the steps run one after another. Gradients also pass back through every step, which 5.3.2. Backpropagation Through Time covers.

Properties

(Nilpotent A Gives a Finite Filter) If for some , the LTI model is an FIR filter with taps.

Every tap with is then zero. A delay line shows that every FIR filter arises this way. Take scalar inputs, , a matrix that moves each state entry down one place, and . The state then holds the last inputs, . The readout gives back the FIR filter. Not every LTI model is an FIR filter. A running sum has and for every , and no FIR filter with finite matches it. When is diagonalizable, each tap is a combination of powers of its eigenvalues (12.2 Eigendecomposition). Eigenvalues inside the unit circle give memory that fades, and eigenvalues outside it make the taps grow.

(Memory Needs the Right State) The state must hold what future outputs need, and some useful summaries need a nonlinear update.

A running sum keeps , an LTI update with one number of state. A running average keeps . Its coefficients change with , so it is linear but not time-invariant. Tracking the two largest values of needs the maximum and the second largest . If the inputs have a known lower bound, both start at that bound. The update is then and . Without such a bound, the state also needs a count of the inputs seen so far, up to . No LTI model can do this. With its output is a linear function of the inputs, and the maximum is not linear. This is why the RNN puts a nonlinearity inside the update.

(Counterpart of a Convolution) The recurrent block keeps the design ideas of a CNN, with time in place of space and causality enforced.

A convolution shares one kernel across positions, and the RNN shares , and across time steps. It learns one update rule and runs on sequences of any length. Weight sharing also gives shift equivariance in time (5.2.1b. Equivariance and Invariance). For the LTI model with , delaying the input by steps delays the output by steps. A nonlinear RNN has this property exactly only when is a state that zero inputs leave unchanged. Causality is the new constraint. An image convolution looks in every direction, while the RNN may look only back. The skip term gives the input a direct path to , like a residual connection.

(Stacking on a Grid) A stacked RNN is a grid in which information moves forward in time and upward through the layers.

\usepackage{tikz}
\usetikzlibrary{arrows.meta}
\begin{document}
\definecolor{hot}{HTML}{D9483B}
\definecolor{cold}{HTML}{2F80ED}
\definecolor{grn}{HTML}{2F9E44}
\begin{tikzpicture}[>={Stealth[length=2.5mm]}, box/.style={draw,thick,minimum width=1.2cm,minimum height=0.8cm}]
\foreach \t in {1,2,3} {
\node[box] (a\t) at (2.8*\t,0) {$\mathbf{h}^{(1)}_{\t}$};
\node[box] (b\t) at (2.8*\t,2) {$\mathbf{h}^{(2)}_{\t}$};
\node (u\t) at (2.8*\t,-1.6) {$\mathbf{u}_{\t}$};
\node (y\t) at (2.8*\t,3.6) {$\mathbf{y}_{\t}$};
\draw[->,cold,thick] (u\t) -- node[left] {$\mathbf{B}^{(1)}$} (a\t);
\draw[->,cold,thick] (a\t) -- node[left] {$\mathbf{B}^{(2)}$} (b\t);
\draw[->,grn,thick] (b\t) -- node[left] {$\mathbf{C}$} (y\t);
}
\foreach \s/\t in {1/2,2/3} {
\draw[->,hot,thick] (a\s) -- node[below] {$\mathbf{W}^{(1)}$} (a\t);
\draw[->,hot,thick] (b\s) -- node[above] {$\mathbf{W}^{(2)}$} (b\t);
}
\draw[->,hot,thick] (1.2,0) -- (a1);
\draw[->,hot,thick] (1.2,2) -- (b1);
\node[left] at (1.1,0) {layer 1};
\node[left] at (1.1,2) {layer 2};
\draw[->,thick] (2.8,-2.3) -- node[below] {time} (8.4,-2.3);
\end{tikzpicture}
\end{document}

Each layer has its own and , shared across all time steps. Deep stacks borrow three tools from CNNs. Vertical residual connections add to the output of layer . Vertical MLPs act on each alone, like a 1x1 convolution. LayerNorm normalizes each over its own entries, so it uses only the current step. BatchNorm fails here for three reasons. The weights are shared across time, but the statistics of change with . Sequences in a batch also have different lengths, so late steps have few examples to average. Any statistic taken along the time axis would also use future steps and break causality.

(Kalman Filter as a Learned RNN) The steady-state Kalman filter is a linear RNN, so its matrices can be learned from recorded traces.

Consider the controlled linear Gaussian system

with noise and . The steady-state Kalman filter estimates the hidden state with

The gain is , where . This recursion is a linear RNN with state and inputs . Suppose the system matrices and noise covariances are unknown, but traces of , and are recorded. Then , and become learnable weights. Training minimizes the mean of over blocks of consecutive steps, and memory limits the block length. The linked note writes , , , and for the , , , and used here. Its prior covariance becomes in steady state.

(Identifiable Only Up to a Basis) Without , data on and fix the learned matrices only up to an invertible change of basis .

Write . Then

and the new process noise has covariance . Both systems give the same joint distribution of controls and observations (2.8b Change of Basis). No loss on and can prefer one of them. The lecture therefore assumes a diagonal . A linear head predicts from and . The loss compares the predicted and recorded . If the diagonal entries are distinct, the remaining freedom is to reorder and rescale the state coordinates.

(Gated and Bidirectional Variants) Gates, a second direction and an encoder-decoder split extend the vanilla RNN.

Not Taught in Lecture

The lecture covers only the vanilla RNN and its linear relatives. These variants follow Goodfellow et al., Deep Learning, §10.3, §10.4 and §10.10. Lecture 18 later covers the encoder-decoder, in 5.3.3. Sequence-to-Sequence Models.

The LSTM (Hochreiter and Schmidhuber, 1997) adds a cell state next to . Three sigmoid gates control the cell. The input gate decides what is written, and the forget gate decides what is erased. The output gate decides what is read out. The forget gate was added later by Gers et al. (2000). Along the cell, the gradient is multiplied by the forget gate at each step instead of by . With the forget gate near , gradients keep their size over many more steps. The GRU (Cho et al., 2014) is a smaller variant with an update gate and a reset gate. A bidirectional RNN runs one RNN forward and one backward and concatenates their states at each . Every output then sees past and future, which requires the whole sequence in advance, as in transcribing a recording. An encoder-decoder pair handles unaligned many-to-many tasks such as translation, as in 5.3.3. Sequence-to-Sequence Models. The encoder’s final state starts the decoder, so the whole input must fit in one fixed-size vector. That limit motivated attention and transformers, which replaced gated RNNs as the standard sequence models.

Examples

(Easy) Smoothing a Temperature Sensor

A thermostat smooths noisy readings with the scalar LTI model and , starting from .

(Medium) A ReLU RNN That Tracks the Maximum

A trader wants the highest price seen so far, and prices are positive. A ReLU RNN with three hidden units computes and , with , no biases and

(Hard) Two Models With the Same Behavior

Two engineers fit a two-state LTI model , to the same heater-to-temperature data. One finds the first set of matrices below, and the other finds the second set:

See Also