GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Module 12

Module 12

Jump to bottom
Anurag Prasad edited this page Nov 9, 2026 · 9 revisions

Module 12 — Recurrent Neural Networks, LSTM and GRU

⬅️ Module 11 · 🗺️ Curriculum · 🏠 Home · Module 13 ➡️

Level: Intermediate · Prerequisites: Modules 02, 07, 08 · Time: about 8–9 hours

On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading


Overview and learning goals

Sequences — text, speech, time series, DNA — have variable length and order-dependent meaning. Recurrent neural networks (RNNs) process one element at a time while carrying a hidden state that summarises the past, sharing the same parameters across time. Their training difficulties (vanishing/exploding gradients) motivated gated cells — LSTM and GRU — whose ideas persist in modern architectures.

After this module you should be able to:

  • write the RNN equations, unroll them and classify sequence tasks (many-to-one, etc.);
  • derive backpropagation through time (BPTT) and explain vanishing/exploding gradients and clipping;
  • write LSTM and GRU equations and explain why the cell state helps;
  • compare unidirectional, bidirectional and stacked RNNs.

Beginner: the big picture

An RNN reads a sentence word by word, updating a "memory" vector after each word. The same update rule is applied at every step, so one model handles any length. A plain RNN's memory fades quickly; gated variants learn what to keep and what to forget.

flowchart LR
    x1["x1"] --> R1["RNN cell"] --> h1["h1"] --> R2["RNN cell"] --> h2["h2"] --> R3["RNN cell"] --> h3["h3"]
    x2["x2"] --> R2
    x3["x3"] --> R3
    h0["h0"] --> R1
    h1 --> y1["y1"]
    h2 --> y2["y2"]
    h3 --> y3["y3"]
Loading

Figure 12.1 — Unrolled RNN: the same cell (shared weights) is applied at each time step. Original diagram.

Core concepts and derivations

Sequential data and parameter sharing

Sequence models must handle variable length, order, and long-range dependence; sharing $W$ across time gives translation of position (like conv sharing across space) and a fixed parameter count.

Vanilla RNN and the unrolled graph

$$\mathbf{h}_t=\tanh\bigl(W_{hh}\mathbf{h}_{t-1}+W_{xh}\mathbf{x}_t+\mathbf{b}_h\bigr),\qquad \hat{\mathbf{y}}_t=W_{hy}\mathbf{h}_t+\mathbf{b}_y .$$

Task patterns: many-to-one (sentiment: use $\mathbf{h}_T$), one-to-many (image captioning: generate from one vector), many-to-many aligned (tagging) and many-to-many unaligned (translation, Module 13).

Character-level language modelling and teacher forcing

Predict the next character: $P(c_{t+1}\mid c_{\le t})=\mathrm{softmax}(W_{hy}\mathbf{h}_t)$, loss $\sum_t-\ln P(c_{t+1})$. In training with teacher forcing, the true previous token is fed as input; at inference the model's own samples are fed back, causing exposure bias (a train/test mismatch).

Backpropagation through time and truncation

Unroll and apply the chain rule. The gradient of the loss at step $t$ with respect to an earlier state $\mathbf{h}_k$:

$$\frac{\partial L_t}{\partial\mathbf{h}_k}=\frac{\partial L_t}{\partial\mathbf{h}_t}\prod_{i=k+1}^{t}\frac{\partial\mathbf{h}_i}{\partial\mathbf{h}_{i-1}},\qquad \frac{\partial\mathbf{h}_i}{\partial\mathbf{h}_{i-1}}=\mathrm{diag}\bigl(\phi'(\mathbf{z}_i)\bigr)W_{hh}.$$

Parameter gradients sum contributions over all time steps. Truncated BPTT backpropagates only $K$ steps (carrying the state forward) to bound memory/compute.

Vanishing and exploding gradients, clipping

With $\lVert\mathrm{diag}(\phi')\rVert\le\gamma$ (1 for tanh, $\frac14$ for sigmoid), the product is bounded by $(\gamma\sigma_{\max}(W_{hh}))^{t-k}$: exponentially small if $\gamma\sigma_{\max}<1$ (vanishing → cannot learn long dependencies) and potentially exponentially large if $\sigma_{\max}$ is large (exploding). Bengio et al. (1994) showed this is intrinsic; Pascanu et al. (2013) give the spectral analysis. Gradient-norm clipping fixes explosion; vanishing needs architectural changes.

Gradient scale through a linear RNN for different spectral radii

Figure 12.2 — $\lVert W^t\rVert_2$ for random orthogonal $W$ scaled to spectral radius $0.9$, $1.0$, $1.1$ (log scale): exponential decay or growth within 50 steps. Original figure (figures/make_figs_2.py).

Bidirectional and stacked RNNs

A bidirectional RNN runs a forward and a backward pass and concatenates states, giving each position both past and future context (not usable for online generation). Stacked (deep) RNNs feed one layer's states to the next.

LSTM

The LSTM (Hochreiter & Schmidhuber 1997; forget gate by Gers et al. 2000) keeps a cell state $\mathbf{c}_t$ with additive updates:

$$\begin{aligned} \mathbf{f}_t&=\sigma(W_f[\mathbf{h}_{t-1},\mathbf{x}_t]+\mathbf{b}_f), &\mathbf{i}_t&=\sigma(W_i[\mathbf{h}_{t-1},\mathbf{x}_t]+\mathbf{b}_i), &\mathbf{o}_t&=\sigma(W_o[\mathbf{h}_{t-1},\mathbf{x}_t]+\mathbf{b}_o),\\\ \tilde{\mathbf{c}}_t&=\tanh(W_c[\mathbf{h}_{t-1},\mathbf{x}_t]+\mathbf{b}_c), &\mathbf{c}_t&=\mathbf{f}_t\odot\mathbf{c}_{t-1}+\mathbf{i}_t\odot\tilde{\mathbf{c}}_t, &\mathbf{h}_t&=\mathbf{o}_t\odot\tanh(\mathbf{c}_t). \end{aligned}$$

Since $\partial\mathbf{c}_t/\partial\mathbf{c}_{t-1}\approx\mathrm{diag}(\mathbf{f}_t)$ (plus indirect terms), gradients flow along the cell state multiplied only by forget gates — near 1 when the network wants to remember — avoiding repeated multiplication by $W_{hh}$ and $\phi'$. Initialising forget-gate biases to 1 helps.

GRU and comparison with LSTM

GRU (Cho et al. 2014) merges cell and hidden state with update gate $\mathbf{z}_t$ and reset gate $\mathbf{r}_t$:

$$\mathbf{z}_t=\sigma(W_z[\mathbf{h}_{t-1},\mathbf{x}_t]),\ \ \mathbf{r}_t=\sigma(W_r[\mathbf{h}_{t-1},\mathbf{x}_t]),\ \ \tilde{\mathbf{h}}_t=\tanh(W[\mathbf{r}_t\odot\mathbf{h}_{t-1},\mathbf{x}_t]),\ \ \mathbf{h}_t=(1-\mathbf{z}_t)\odot\mathbf{h}_{t-1}+\mathbf{z}_t\odot\tilde{\mathbf{h}}_t .$$

The interpolation $(1-\mathbf{z})\mathbf{h}_{t-1}+\dots$ is the same additive-memory idea with fewer parameters (3 weight blocks vs 4). Performance is usually comparable; neither dominates.

Worked example

Scalar RNN: $h_t=\tanh(0.5h_{t-1}+x_t)$, $h_0=0$, inputs $x=(1,0.5)$: $h_1=\tanh(1)=0.762$, $h_2=\tanh(0.5\cdot0.762+0.5)=\tanh(0.881)=0.707$. The Jacobian $\partial h_2/\partial h_1=(1-h_2^2)\cdot0.5=0.25$: a signal from step 1 is already quartered after one step.

Parameters ($d_x=128$, $d_h=256$): vanilla $256(384)+256=98{,}560$; LSTM $4\times98{,}560=394{,}240$; GRU $3\times98{,}560=295{,}680$.

Implementation

import numpy as np

def rnn_forward(X, Wxh, Whh, b, h0):
    h, H = h0, []
    for x in X:                                 # X: (T, d_x)
        h = np.tanh(Wxh @ x + Whh @ h + b); H.append(h)
    return np.array(H)

def clip_by_global_norm(grads, c):
    n = np.sqrt(sum((g ** 2).sum() for g in grads)); s = min(1.0, c / (n + 1e-12))
    return [g * s for g in grads]
import torch.nn as nn
lstm = nn.LSTM(input_size=128, hidden_size=256, num_layers=2, bidirectional=True, batch_first=True, dropout=0.2)
out, (h, c) = lstm(x)                           # out: (B, T, 512)
# training: loss.backward(); nn.utils.clip_grad_norm_(lstm.parameters(), 1.0); opt.step()

Advanced topics

  • Orthogonal/unitary RNNs, IRNN, IndRNN and state-space models (S4, Mamba) revisit linear recurrences with long memory and parallel training.
  • Linear attention / RWKV / xLSTM connect recurrence and attention.
  • Seq2seq and attention relieve the fixed-size bottleneck (Module 13); Transformers replace recurrence altogether (Module 14).
  • Scheduled sampling and sequence-level training reduce exposure bias.
  • Regularisation: variational (locked) dropout, zoneout, weight-tying; layer-norm LSTM.
  • Parallelism: RNNs are sequential in time ($O(T)$ depth), limiting GPU utilisation — a main reason Transformers won.

Pitfalls and best practices

  • Not clipping gradients; not shuffling sequences/batches correctly; leaking hidden state across unrelated sequences.
  • Padding without masking/packing so the model reads pad tokens.
  • Using bidirectional RNNs for causal generation.
  • Forgetting to detach the carried state between truncated-BPTT chunks (graph grows forever).

Conceptual questions and answers

Q1. Why do RNNs share weights across time?

Show answer

Same dynamics at every step, any sequence length, far fewer parameters, and better generalisation across positions.

Q2. Derive why gradients vanish in a vanilla RNN.

Show answer

$\partial\mathbf{h}_t/\partial\mathbf{h}_k=\prod_{i}\mathrm{diag}(\phi'_i)W_{hh}$; its norm is at most $(\gamma\sigma_{\max}(W_{hh}))^{t-k}$ which decays exponentially if $\gamma\sigma_{\max}<1$.

Q3. Why does clipping help only with exploding gradients?

Show answer

It caps large norms but cannot restore signal that has already shrunk toward zero.

Q4. How does the LSTM cell state mitigate vanishing gradients?

Show answer

Memory is updated additively and $\partial\mathbf{c}_t/\partial\mathbf{c}_{t-1}\approx\mathbf{f}_t$; with forget gates near 1 gradients flow almost unattenuated over many steps.

Q5. Compare GRU and LSTM.

Show answer

GRU has two gates and no separate cell state (≈25% fewer parameters); LSTM has three gates plus a cell state and sometimes better on long dependencies. Empirically close.

Q6. What is teacher forcing and its drawback?

Show answer

Feeding ground truth tokens as inputs during training speeds learning but causes exposure bias, since at test time the model consumes its own, possibly erroneous, predictions.

Q7. When can you use a bidirectional RNN?

Show answer

When the whole sequence is available (tagging, classification, encoders), not for left-to-right generation.

Q8. What does truncated BPTT trade off?

Show answer

Memory and compute are bounded, but gradients cannot capture dependencies longer than the truncation length.

Sources and further reading

  • Elman, J. L. (1990). Finding structure in time. Cognitive Science, 14(2).
  • Bengio, Y., Simard, P., & Frasconi, P. (1994). Learning long-term dependencies with gradient descent is difficult. IEEE Trans. Neural Networks, 5(2).
  • Hochreiter, S., & Schmidhuber, J. (1997). Long short-term memory. Neural Computation, 9(8).
  • Gers, F. A., Schmidhuber, J., & Cummins, F. (2000). Learning to forget: continual prediction with LSTM. Neural Computation, 12(10).
  • Cho, K., et al. (2014). Learning phrase representations using RNN encoder–decoder for statistical machine translation. EMNLP. arXiv:1406.1078.
  • Schuster, M., & Paliwal, K. K. (1997). Bidirectional recurrent neural networks. IEEE Trans. Signal Processing, 45(11).
  • Pascanu, R., Mikolov, T., & Bengio, Y. (2013). On the difficulty of training recurrent neural networks. ICML.
  • Karpathy, A. (2015). The unreasonable effectiveness of recurrent neural networks (blog post).
  • Gu, A., & Dao, T. (2023). Mamba: linear-time sequence modeling with selective state spaces. arXiv:2312.00752.

⬅️ Module 11 · 🗺️ Curriculum · 🏠 Home · Module 13 ➡️

🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing

🎓 Deep Learning Hub

🏠 Home · 🗺️ Curriculum · 🧭 Learning paths

❓ Question bank · 📖 Glossary · 📚 References

Jump to module:

01 02 03 04 05 06 07 08 09 10 11 12

13 14 15 16 17 18 19 20 21 22 23 24

Part 1 · Mathematical foundations
  • 01 · Linear algebra & tensors
    Core · Advanced · Q&A
  • 02 · Calculus & autodiff
    Core · Advanced · Q&A
  • 03 · Probability & information theory
    Core · Advanced · Q&A
Part 2 · Neural network fundamentals
  • 04 · Neurons & perceptrons
    Core · Advanced · Q&A
  • 05 · Activations & expressivity
    Core · Advanced · Q&A
  • 06 · Losses & gradient descent
    Core · Advanced · Q&A
  • 07 · MLPs & backpropagation
    Core · Advanced · Q&A
Part 3 · Training deep networks
  • 08 · Optimization & loss landscapes
    Core · Advanced · Q&A
  • 09 · Initialization & normalization
    Core · Advanced · Q&A
  • 10 · Regularization & generalization
    Core · Advanced · Q&A
Part 4 · Core architectures
  • 11 · Convolutional networks
    Core · Advanced · Q&A
  • 12 · RNN, LSTM & GRU
    Core · Advanced · Q&A
  • 13 · Seq2seq & attention
    Core · Advanced · Q&A
  • 14 · Transformers
    Core · Advanced · Q&A
  • 15 · Positional encoding & attention variants
    Core · Advanced · Q&A
Part 5 · Representation and generative learning
  • 16 · Autoencoders
    Core · Advanced · Q&A
  • 17 · Self-supervised & contrastive
    Core · Advanced · Q&A
  • 18 · Variational autoencoders
    Core · Advanced · Q&A
  • 19 · GANs
    Core · Advanced · Q&A
  • 20 · Diffusion models
    Core · Advanced · Q&A
Part 6 · Specialised, modern and responsible deep learning
  • 21 · Graph neural networks
    Core · Advanced · Q&A
  • 22 · Transfer & foundation models
    Core · Advanced · Q&A
  • 23 · LLMs & multimodal
    Core · Advanced · Q&A
  • 24 · Evaluation, robustness & efficiency
    Core · Advanced · Q&A
Reference and meta
  • Math notation cheat sheet
  • Cross-module concept map
  • Figures and attribution
  • Implementation and research standards
  • Notebook roadmap
  • Source coverage
  • Contributing
  • Changelog

Clone this wiki locally

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.