Introduction

Real-world data mostly doesn’t come as independent, fixed-size samples. It comes as ordered sequences, and order carries meaning. “The dog bit the man.” and “The man bit the dog.” contain identical tokens, but the order changes the meaning of the whole sentence. The same holds for speech, videos, financial markets, sensor streams, weather, DNA, and so on. Standard deep-learning architectures like MLPs assume independent, fixed-size inputs, and standard CNNs handle fixed-size structured inputs (e.g. images) but don’t natively model sequential order across time.

To handle sequences, an architecture must process inputs in the same temporal order they appear, while carrying a memory of what has come before.

Recurrent Neural Network

Recurrent Neural Networks are one of the earliest neural architectures designed for sequences. The core idea is to process a sequence one element at a time and let a hidden state act as a memory of what has happened so far. At each time-step $t$ the cell takes two inputs:

  1. the current element $x_t$
  2. the hidden state of the previous step $h_{t-1}$.

It combines them into an updated hidden state:

$$ \begin{aligned} z_t &= W_h h_{t-1} + W_x x_t + b_h \\\\ h_t &= \tanh(z_t) \end{aligned} $$

Here $W_h$ is the recurrent weight matrix (how the previous state influences the next), $W_x$ is the input weight matrix, and $b_h$ is a bias. The nonlinearity $\tanh$ squashes the pre-activation into $[-1, 1]$.

The crucial detail is that $W_h, W_x, b_h$ are the same at every timestep. This parameter sharing across the time-steps is what lets a fixed set of weights process a sequence of any length without the model growing with the sequence length. That sharing is both the elegance and, as we’ll see, the source of the training difficulty.

The hidden state is not itself a prediction; it is a compressed memory of the sequence so far. To produce an output we project it with a second weight matrix and bias and apply a softmax when we want a probability distribution over classes or a vocabulary:

$$ o_t = W_o h_t + b_o $$$$ \hat{y}_t = \mathrm{softmax}(o_t) $$

Depending on the task we read the output at every step (many-to-many, e.g. a language model predicting the next word after each position) or only at the final step (many-to-one, e.g. classifying the sentiment of a whole sentence).

Encoder-decoder (sequence-to-sequence)

A single RNN cell from the previous section maps a sequence to hidden states, but many real-world tasks map one sequence to another sequence of a different length: machine translation (a French sentence to an English one), summarization, image captioning (image to sentence), dialogue. The input and output lengths differ and are not known in advance, which a single many-to-many RNN cannot directly produce. The encoder-decoder architecture breaks the problem into two recurrent blocks, an encoder and a decoder, chained together (Cho et al., 2014; Sutskever et al., 2014).

Encoder. Reads the input $x_1, \dots, x_{T_x}$ one element at a time and generates its hidden state for every timestep using the formula stated above:

$$ \begin{aligned} h_t &= \tanh(W_h h_{t-1} + W_x x_t \\\\ &\quad + b_h) \end{aligned} $$

The hidden state generated from the last input will depend on the hidden state from the previous timestep which in turn will depend on the hidden state of the previous timestep. As a result the hidden state associated with the final input state will represent a summary of the entire input sequence and the hidden state for the previous timestep will represent a summary of the input up to that timestep and so on. Since the last hidden state holds the summary of the entire input sequence we call it the context vector $c$. For a vanilla encoder $c = h_{T_x}$ where $T_x$ is the final input timestep.

Decoder. A second RNN produces the output $y_1, \dots, y_{T_y}$ token by token in an autoregressive manner. The first step has no previous output yet, so its hidden state is seeded from the context vector ($s_0 = \tanh(W_c c)$, or simply $s_0 = c$), and the first output depends only on $c$. From there the decoder rolls forward one token at a time: the token it produced at step $t-1$ becomes the input at step $t$, and the hidden state updates as

$$ \begin{aligned} s_t &= \tanh(W_s s_{t-1} + U c \\\\ &\quad + W_y y_{t-1} + b_s) \end{aligned} $$

with each step emitting a distribution over the vocabulary

$$ \begin{aligned} p(y_t \mid y_{Here $y_{autoregressive: its output at step $t$ is fed back as input at step $t+1$. During training we feed the ground-truth token (teacher forcing), and at inference we feed the model’s own sample.

When does it stop? Because the decoder is autoregressive, it has no way to know in advance how long the output should be. During training this is not a problem: the target length $T_y$ is fixed and known, so we run exactly $T_y$ steps with teacher forcing. At inference the length is unknown for a new input, so the output vocabulary includes a special end-of-sequence token $\langle\text{eos}\rangle$ (often written <eos>). The decoder emits one token at a time and stops as soon as it produces <eos>, so the predicted output is the prefix up to that token. A maximum length cap is usually added as a safeguard in case the decoder never emits <eos>.

Dimensions. The context vector is $c \in \mathbb{R}^{d}$, the same size as the encoder’s hidden state. The decoder’s hidden state is $s_t \in \mathbb{R}^{d}$, so the recurrent weight is $W_s \in \mathbb{R}^{d \times d}$ and the context projection is $U \in \mathbb{R}^{d \times d}$. The token fed back, $y_{t-1}$, is represented as a vector of size $d_y$, so $W_y \in \mathbb{R}^{d \times d_y}$. The output layer $W_o \in \mathbb{R}^{N \times d}$ scores each of the $N$ tokens in the vocabulary, so $p(y_t \mid y_{

The bottleneck. The entire input must collapse into a single fixed vector $c$. Every token’s detail competes for the same $d$ dimensions, so for long inputs information is lost; early and fine-grained details get smeared into the summary. This is exactly what motivates attention.

Time complexity

In this section we first find the cost of a forward pass through a single RNN cell, then how that cost scales over a whole sequence.

A single RNN cell

The forward pass of one cell is

$$ z_t = W_h h_{t-1} + W_x x_t + b_h $$$$ h_t = \tanh(z_t) $$

The matrix-vector products. $W_h h_{t-1}$ multiplies a $d \times d$ matrix with a $d \times 1$ vector. A matrix multiplication is two nested loops: one over the $d$ output rows, and one over the $d$ entries of each dot product. This costs $d \cdot d = d^2$ multiply-adds, i.e. $\mathcal{O}(d^2)$. The second product, $W_x x_t$, is $d \times d_{in}$ by $d_{in} \times 1$, costing $d \cdot d_{in} = \mathcal{O}(d \cdot d_{in})$. Adding the bias is $\mathcal{O}(d)$.

The activation. $h_t = \tanh(z_t)$ applies the nonlinearity to each of the $d$ entries on its own; $\tanh$ is elementwise, so it costs $\mathcal{O}(d)$.

Total worst case. One forward pass through a single cell therefore costs

$$ \mathcal{O}(d^2 + d \cdot d_{in} + d) = \mathcal{O}(d^2) $$

The $\mathcal{O}(d^2)$ term from the hidden-state product dominates; $\mathcal{O}(d \cdot d_{in})$ is the input contribution, and the $\mathcal{O}(d)$ activation and bias are negligible. When the hidden size is at least the input size ($d \ge d_{in}$, the usual case), the worst case for one cell is $\mathcal{O}(d^2)$.

A full forward pass over a sequence

An RNN runs the same cell once per time step, so a sequence of $n$ tokens is a loop over $t = 1, \dots, n$, each iteration costing $\mathcal{O}(d^2)$:

$$ T_{\text{RNN}} = n \cdot \mathcal{O}(d^2) = \mathcal{O}(n d^2) $$

The hidden state is the memory carried forward, so the loop is inherently sequential: step $t$ needs $h_{t-1}$, which needs $h_{t-2}$, and so on. Even on hardware that parallelizes the matrix products, the $n$ time steps form an unbreakable chain, so the wall-clock time is at least $\mathcal{O}(n)$ serial cell evaluations. The $\mathcal{O}(n d^2)$ of arithmetic cannot be squeezed below that.

Training: backpropagation through time

Before we look at how backpropagation works for an RNN, we first go through the basics of backpropagation through a computation graph.

Gradients through a computation graph: upstream × local

Backpropagation is easiest to understand edge by edge. Consider the tiny arithmetic graph $z = a \cdot b + c \cdot d$ with $a = 2, b = 3, c = 4, d = 2$. The forward pass is

$$ u = a \cdot b = 6 $$$$ v = c \cdot d = 8 $$$$ z = u + v = 14 $$

Now traverse the graph backwards. At each node we track three quantities:

  • Upstream gradient: the gradient of the loss (here simply $z$) with respect to the node’s output, arriving from the direction of the loss.
  • Local gradient: the derivative of the node’s own operation with respect to its input, computed from the operation and the values cached on the forward pass.
  • Downstream gradient: the gradient with respect to the node’s input, which is what we pass further back:
$$ \text{downstream} = \text{upstream} \times \text{local} $$

Starting with $\partial z / \partial z = 1$:

nodeupstreamlocal gradientdownstream
$z = u + v$ $\partial z/\partial z = 1$ $\partial z/\partial u = 1,\ \partial z/\partial v = 1$ $\partial z/\partial u = 1,\ \partial z/\partial v = 1$
$u = a \cdot b$ $\partial z/\partial u = 1$ $\partial u/\partial a = b = 3,\ \partial u/\partial b = a = 2$ $\partial z/\partial a = 3,\ \partial z/\partial b = 2$
$v = c \cdot d$ $\partial z/\partial v = 1$ $\partial v/\partial c = d = 2,\ \partial v/\partial d = c = 4$ $\partial z/\partial c = 2,\ \partial z/\partial d = 4$

Direct differentiation confirms the result: since $z = ab + cd$, $\partial z/\partial a = b = 3$, $\partial z/\partial b = a = 2$, $\partial z/\partial c = d = 2$, and $\partial z/\partial d = c = 4$.

Two patterns from this example carry straight over to the RNN, and both show up in the table above:

  1. Sum node. At $z = u + v$ the local gradient with respect to each input is the partial derivative of the sum with respect to that input alone, holding the other constant; each derivative is $1$ ($\partial z/\partial u = 1$ and $\partial z/\partial v = 1$). A sum node passes the gradient arriving from its output on unchanged, which is why the upstream gradient at $u$ is $\partial z/\partial u = 1$ and at $v$ is $\partial z/\partial v = 1$. The companion rule is about a node with several outgoing branches: its gradient is the sum of the gradients coming back along every branch. In this example $z$ has a single downstream consumer, so nothing adds here, but the RNN does not have that luxury. The hidden state $h_t$ is read both by the output layer and by the next cell, so its gradient is the sum of those two branches, exactly the “gradients from multiple branches add” point.

  2. Product node. At $u = a \cdot b$ the local gradient with respect to one operand is the other operand’s value, frozen on the forward pass: $\partial u/\partial a = b = 3$ and $\partial u/\partial b = a = 2$. That is why the downstream gradients at $a$ and $b$ come out as the upstream gradient times the local one: $1 \times 3 = 3$ and $1 \times 2 = 2$. The RNN’s linear map is the same rule in matrix form: the local gradient of $W x$ with respect to $x$ is the matrix $W$ itself.

Training an RNN means computing the gradient of the loss with respect to the shared weights $W_x, W_h, W_o$ (and biases). We do this by unrolling the network into a deep feed-forward graph (one cell per timestep), and applying backpropagation to the unrolled graph. Because the same weights reappear at every step, their gradients are summed across all the places they occur. This is called backpropagation through time (BPTT); gradient flow is the same chain rule as in any computation graph, just applied along the temporal dimension.

Truncated BPTT: training on very long sequences

Unrolling is clean, but it hides a practical problem for very long sequences. A full BPTT pass needs the entire unrolled graph stored, because the backward pass must walk back through all $T$ steps. Concretely, we must keep every hidden state $h_1, \dots, h_T$ (and every pre-activation) in memory, and the backward pass is a chain of $T$ matrix products. Those are two costs that both grow with sequence length:

  • Memory. Storing all $T$ hidden states costs $\mathcal{O}(T \cdot d)$. With a large hidden size $d$ and a sequence of thousands of steps, the unrolled graph will not fit on a GPU.
  • Time. The backward pass costs $\mathcal{O}(T \cdot d^2)$, one matrix product per step.

For a short sequence we simply accumulate the gradient over all steps and do one update. For a very long sequence that is infeasible, so we truncate the backpropagation and update the weights in pieces. The long sequence is processed in chunks of $K$ steps, and the weights are updated once per chunk:

  1. Run the forward pass over $K$ steps, carrying the hidden state from the previous chunk into this one. The carried state still encodes the whole history, so the network is not made memoryless.
  2. Compute the loss for those $K$ steps.
  3. Backpropagate through only those $K$ steps (not the whole history) and update the weights.
  4. Detach the hidden state at the chunk boundary: the state is passed forward as a value, but the gradient is not allowed to flow through it back into earlier chunks.

This is truncated backpropagation through time (TBPTT), and the detach is the crucial step. In PyTorch it is literally h = h.detach(): tell the autograd graph that the incoming hidden state is a constant, not a function of earlier steps. Only $K$ hidden states need to be kept at a time, so memory is bounded by the chunk size rather than the whole sequence.

The forward pass still uses the entire history (through the carried state), so the network can remember long-range information. But the gradient is cut off after $K$ steps, so it can only learn dependencies up to $K$ steps apart. The gradient is an approximation of the true gradient, which is a form of bias. Choosing $K$ is an engineering trade-off: too small and the network cannot pick up medium-range patterns; too large and you lose the memory and time savings. Typical chunk lengths are a few tens to a few hundred steps.

Gradient with respect to the weights themselves

The trainable parameters in RNN are $W_h$, $W_x$, and $W_o$. Each is shared across every timestep, so its gradient is a sum over the places it is used. In this section we focus on $W_h$.

For the last timestep, the loss reaches $W_h$ through the final hidden state $h_T$, and $h_T$ connects to $W_h$ in two ways: directly, through the term $W_h h_{T-1}$ inside $z_T$, and through $h_{T-1}$, which is where the recurrence continues back through time. The chain rule splits the gradient along those two routes:

$$ \begin{aligned} \frac{\partial L}{\partial W_h} &= \frac{\partial L}{\partial h_T} \cdot \frac{\partial h_T}{\partial W_h} \\\\ &\quad + \frac{\partial L}{\partial h_T} \cdot \frac{\partial h_T}{\partial h_{T-1}} \end{aligned} $$

The first term is the direct route, the contribution of $W_h$ within a single step. The second is the recurrent route, the path that keeps going back in time, and it is where the interesting behaviour lives. Expand it. Since $h_T = \tanh(W_h h_{T-1} + W_x x_T + b_h)$,

$$ \begin{aligned} \frac{\partial h_T}{\partial h_{T-1}} &= \frac{\partial}{\partial h_{T-1}} \tanh(W_h h_{T-1} + W_x x_T + b_h) \\\\ &= \mathrm{diag}(1 - h_T^2) \cdot W_h \end{aligned} $$

where $\mathrm{diag}(1 - h_T^2)$ is the elementwise derivative of $\tanh$ at the pre-activation. With the column-vector convention, this step flows backward through a transpose, so the gradient sent to the previous hidden state is

$$ \begin{aligned} \frac{\partial L}{\partial h_{T-1}} &= W_h^{\mathsf{T}} \cdot \mathrm{diag}(1 - h_T^2) \\\\ &\quad \cdot \frac{\partial L}{\partial h_T} \end{aligned} $$

One step back, one factor of $W_h^{\mathsf{T}}$. That is the key observation: every step back in time multiplies the gradient by another $W_h^{\mathsf{T}}$, so the gradient carries as many $W_h^{\mathsf{T}}$ factors as there are steps back. Write a single backward step as $M_j = W_h^{\mathsf{T}} \cdot \mathrm{diag}(1 - h_j^2)$, and go back three timesteps:

$$ \begin{aligned} \frac{\partial L}{\partial h_{T-1}} &= M_T \frac{\partial L}{\partial h_T}, \\\\ \frac{\partial L}{\partial h_{T-2}} &= M_{T-1} \frac{\partial L}{\partial h_{T-1}}, \\\\ \frac{\partial L}{\partial h_{T-3}} &= M_{T-2} \frac{\partial L}{\partial h_{T-2}} \end{aligned} $$

Unroll the recurrences. The gradient at $h_{T-3}$ has been multiplied by three factors of $W_h^{\mathsf{T}}$, one per step:

$$ \begin{aligned} \frac{\partial L}{\partial h_{T-3}} &= M_{T-2} \cdot M_{T-1} \cdot M_T \\\\ &\quad \cdot \frac{\partial L}{\partial h_T} \end{aligned} $$

So the further back a dependency lies, the more $W_h^{\mathsf{T}}$ factors appear, in exactly the way the forward pass chains copies of $W_h$. This repeated multiplication is the heart of the vanishing and exploding gradient problem.

At intermediate steps $h_t$ is used in two places. It is projected to the output at timestep $t$, $o_t = W_o h_t + b_o$, and it feeds the next cell through $z_{t+1} = W_h h_t + W_x x_{t+1} + b_h$. The loss therefore reaches $h_t$ along two routes, and the chain rule turns that fork into a sum of two terms:

$$ \begin{aligned} \frac{\partial L}{\partial h_t} &= \frac{\partial L}{\partial o_t} \frac{\partial o_t}{\partial h_t} \\\\ &\quad + \frac{\partial L}{\partial z_{t+1}} \frac{\partial z_{t+1}}{\partial h_t} \end{aligned} $$

Each term is an ordinary chain-rule factor: the gradient already flowing back to that node, times the local gradient of the edge. The two local gradients come straight from the definitions:

  • From $o_t = W_o h_t + b_o$, differentiating with respect to $h_t$ gives $\partial o_t / \partial h_t = W_o$.
  • From $z_{t+1} = W_h h_t + W_x x_{t+1} + b_h$, differentiating gives $\partial z_{t+1} / \partial h_t = W_h$.

A vector matrix multiply $q = W p$ backpropagates through the transpose, so the gradient with respect to $p$ is $W^{\mathsf{T}} \partial L/\partial q$. Applying that to both routes gives the sum:

$$ \begin{aligned} \frac{\partial L}{\partial h_t} &= W_o^{\mathsf{T}} \frac{\partial L}{\partial o_t} \\\\ &\quad + W_h^{\mathsf{T}} \frac{\partial L}{\partial z_{t+1}} \end{aligned} $$

The first term is the gradient coming back from the output at step $t$; the second is the gradient coming back from the next cell, and it is the one that keeps recursing further back in time.

The vanishing and exploding gradient problem

The same unrolling that makes the gradient computable also reveals the failure mode. Look at the term that carries a gradient from a step $k$ back to a later step $t$: it is a product of Jacobians, one per step:

$$ \begin{aligned} \frac{\partial L}{\partial h_k} &= \frac{\partial L}{\partial h_T} \prod_{j=k+1}^{T} \\\\ &\qquad \left[ \mathrm{diag}(1 - h_j^2) \cdot W_h \right] \end{aligned} $$

The backward pass runs this chain in reverse. From the single-step rule, each step back multiplies the gradient by $W_h^{\mathsf{T}}$, with a $\mathrm{diag}(1 - h_j^2)$ factor in between whose magnitude is at most $1$. So the gradient from $k$ steps back carries $T - k$ copies of $W_h^{\mathsf{T}}$, and the whole product is bounded by the spectral norm of $W_h^{\mathsf{T}}$ raised to that power:

$$ \|W_h^{\mathsf{T}}\|_2^{T-k} $$

Stability therefore hinges on the spectral norm of $W_h^{\mathsf{T}}$:

  • If $\|W_h^{\mathsf{T}}\|_2 < 1$, repeated multiplication shrinks the product geometrically, so gradients vanish and early inputs are effectively forgotten. Long-range dependencies are not learned.
  • If $\|W_h^{\mathsf{T}}\|_2 > 1$, repeated multiplication grows the product geometrically, so gradients explode and training diverges (inf/NaN losses, steep “walls” in the loss surface).

To see the decay concretely, shrink to a single hidden unit so that $W_h$ is just a scalar $w$. Each step back multiplies the gradient by $(1 - h_t^2) \cdot w$, so the gradient arriving from $n$ steps back is scaled by $\prod_j (1 - h_j^2) \cdot w$. Suppose the activations have settled so the $\tanh$ derivative is $1 - h^2 = 0.25$ at every step, and take $w = 0.999$. A single step then multiplies the gradient by about $0.25 \times 0.999 \approx 0.25$, and travelling back $n$ steps carries a factor of about $0.25^n$:

steps back $n$ gradient factor $0.25^n$
1 $0.25$
5 $0.25^5 \approx 9.8\times10^{-4}$
10 $0.25^{10} \approx 9.5\times10^{-7}$
20 $0.25^{20} \approx 9.1\times10^{-13}$

Even in the friendliest case, where every $\tanh$ derivative is exactly $1$ so the per-step factor is just $w = 0.999$, repeated multiplication still decays: $0.999^{1000} \approx 0.368$ and $0.999^{5000} \approx 0.0067$. Real activations rarely sit exactly at zero, so the $\tanh$ term makes the decay far faster. That combination is why vanishing gradients is the common practical failure, and why a plain RNN struggles to learn long-range dependencies.

There is an asymmetry worth noticing: during the forward pass each step squashes its activations through $\tanh$, so values stay bounded. But the backward pass is a purely linear chain of $W_h^{\mathsf{T}}$, and nothing constrains those derivatives from blowing up. The gradient path is where stability is lost.

Fixes

The two failure modes are not treated alike. Exploding gradients have a simple fix; vanishing gradients have no clean fix in a plain RNN.

Exploding gradients. Handled by gradient clipping, which caps the norm of the gradient before an update. The backward pass is a chain of $W_h^{\mathsf{T}}$ multiplications, so a single step can produce a gradient far larger than any sensible update. Clipping bounds that at the update step without touching the gradient’s direction. Concatenate all the parameter gradients into one vector and compute the global $\ell_2$ norm,

$$ \|g\| = \sqrt{\sum_i \|g_i\|_2^2} $$

then rescale the whole gradient when that norm exceeds a threshold $c$ (typically $1$ for transformers, $1$ to $5$ for RNNs), and leave it unchanged otherwise:

$$ g \leftarrow g \cdot \min\left(\frac{c}{\|g\|}, 1\right) $$

The min picks the smaller of the two, and that is what does the clipping. Two cases:

  • If $\|g\| > c$, then $c/\|g\| < 1$, so the scale is $c/\|g\|$ and $g \leftarrow c \cdot g/\|g\|$. Since $g/\|g\|$ is a unit vector, the new gradient has norm exactly $c$ with its direction unchanged: it is clipped to the cap.
  • If $\|g\| \le c$, then $c/\|g\| \ge 1$, so the scale is $1$ and the gradient is left as it is.
$\|g\|$ $c/\|g\|$ $\min(c/\|g\|, 1)$ new gradient (with $c = 5$)
$100$ (exploded) $0.05$ $0.05$ norm clipped to $5$
$3$ (fine) $1.67$ $1$ unchanged

So the 1 in min acts as a clamp: the scale never exceeds $1$, so the gradient is only ever shrunk, never amplified. This is exactly what torch.nn.utils.clip_grad_norm_ does in PyTorch.

Vanishing gradients. A plain RNN has no clean fix. The gradient is a product of as many Jacobians as there are steps back, and each $\tanh$ step contributes a factor at most $1$. Whether that product collapses or grows over depth depends on the recurrent weight’s spectral norm: when it stays at or below $1$, the product collapses and the gradient is effectively zero after enough steps, so the early part of the sequence never reaches the weight updates. That is a fundamental limit of the plain recurrent cell.

Conclusion

The Transformer/attention architecture has become the default for most language and many sequence tasks, largely because it can be parallelized across the sequence and handles very long contexts well. But RNNs are still used where you want streaming, online, or low-latency inference. You don’t need to see the whole sequence to produce an output, and a fixed-size state is cheap. More importantly, the concepts they introduced (the hidden state as memory, backpropagation through time, the gradient pathology, and the gating that later architectures use to tame it) are foundational and still recur in modern designs. Understanding the recurrent cell and its gradients remains one of the best ways to build intuition for how sequence models are trained.

The gated descendants LSTM and GRU are still common for time-series and streaming sequence tasks, and recurrence remains central to streaming speech recognition, where RNN-T models use a recurrent prediction network and run online. A newer wave of architectures returns to recurrence to escape the quadratic cost of self-attention: RWKV can be trained like a transformer and run like an RNN, giving constant-memory linear-time inference, and structured state-space models such as Mamba are computed as a recurrence and scale linearly in sequence length.

References