6.5 Sequential Models (RNNs, LSTMs)
6.5 Sequential Models (RNNs, LSTMs)
Key Concepts
6.5.1 Recurrent Neural Networks (RNNs)
RNNs are designed to process sequential data by maintaining a hidden state that captures information from previous time steps.
Why RNNs for Sequences?
Feedforward networks have fixed input size and no memory:
Feedforward: Each input processed independently
RNN: Current output depends on current input AND previous stateApplications:
- Language modeling (predict next word)
- Machine translation
- Speech recognition
- Time series forecasting
- Sentiment analysis
RNN Architecture
Unrolled RNN through time:
x_t-1 x_t x_t+1
| | |
v v v
[RNN] --> [RNN] --> [RNN] --> ...
| | |
v v v
h_t-1 h_t h_t+1
| | |
v v v
y_t-1 y_t y_t+1
Same weights (W_hh, W_xh, W_hy) shared across all time stepsRNN Equations
At each time step t:
# Hidden state update
h_t = tanh(W_hh @ h_{t-1} + W_xh @ x_t + b_h)
# Output (optional, depends on task)
y_t = W_hy @ h_t + b_y
Where:
- x_t: input at time t
- h_t: hidden state at time t
- y_t: output at time t
- W_hh: hidden-to-hidden weights (recurrent)
- W_xh: input-to-hidden weights
- W_hy: hidden-to-output weightsParameter Sharing
Key insight: Same weights used at every time step
- Enables processing sequences of any length
- Reduces parameters compared to separate weights per position
- Captures patterns regardless of position in sequence
Types of RNN Architectures
One-to-One: One-to-Many: Many-to-One: Many-to-Many:
(Standard NN) (Image caption) (Sentiment) (Translation)
y y y y y y y y y y
| | | | | | | | | |
[H] [H-H-H-H] [H-H-H-H] [H-H-H-H-H-H]
| | | | | | | | | |
x x x x x x x x x x6.5.2 Vanishing and Exploding Gradients in RNNs
The fundamental problem that limits vanilla RNNs.
The Problem
During backpropagation through time (BPTT), gradients are multiplied repeatedly:
dL/dh_0 = dL/dh_T * dh_T/dh_{T-1} * ... * dh_1/dh_0
Each dh_t/dh_{t-1} involves W_hh and tanh derivative
If ||W_hh|| < 1: gradients shrink exponentially (vanishing)
If ||W_hh|| > 1: gradients grow exponentially (exploding)Mathematical View
dh_t/dh_{t-1} = diag(tanh'(z_t)) @ W_hh
Over T steps:
dh_T/dh_0 = product_{t=1}^{T} [diag(tanh'(z_t)) @ W_hh]
Since |tanh'(x)| <= 1, this product tends to vanish for large TConsequences
Vanishing gradients:
- Cannot learn long-range dependencies
- Early time steps receive near-zero gradients
- Model "forgets" distant past
Exploding gradients:
- Training becomes unstable
- Loss becomes NaN
- Weights diverge
Solutions
| Solution | How it helps |
|---|---|
| Gradient clipping | Caps exploding gradients |
| LSTM/GRU | Gating mechanisms preserve gradients |
| Skip connections | Direct gradient paths |
| Proper initialization | Start in stable regime |
| Shorter sequences | Reduce multiplication chain |
6.5.3 Long Short-Term Memory (LSTM)
LSTMs solve the vanishing gradient problem through a gating mechanism and a separate cell state.
Key Innovation: Cell State
Cell state (c_t): Long-term memory highway
- Information flows with minimal transformation
- Gates control what to add/remove
- Gradients flow more easily through addition
c_{t-1} ----[x]----[+]---- c_t
| |
forget input
gate gateLSTM Architecture
c_{t-1}
|
+-----------[x]------------+
| | |
| +------+------+ |
| | | |
| [forget] [input] |
| gate gate |
| | | |
| f_t i_t |
| | | |
| | [tanh] |
| | | |
| | c_tilde |
| | | |
+-----[x]----[+]---[x]-----+
| |
c_t [tanh]
|
+----[x]----+
| | |
[output] h_t
gate
|
o_tLSTM Equations
# Forget gate: what to discard from cell state
f_t = sigmoid(W_f @ [h_{t-1}, x_t] + b_f)
# Input gate: what new information to store
i_t = sigmoid(W_i @ [h_{t-1}, x_t] + b_i)
# Candidate cell state: new information to potentially add
c_tilde_t = tanh(W_c @ [h_{t-1}, x_t] + b_c)
# Cell state update: forget old + add new
c_t = f_t * c_{t-1} + i_t * c_tilde_t
# Output gate: what to output from cell state
o_t = sigmoid(W_o @ [h_{t-1}, x_t] + b_o)
# Hidden state: filtered cell state
h_t = o_t * tanh(c_t)Gate Intuitions
| Gate | Purpose | When high (close to 1) | When low (close to 0) |
|---|---|---|---|
| Forget (f) | Control memory retention | Keep previous memory | Erase previous memory |
| Input (i) | Control new information | Add new information | Ignore new information |
| Output (o) | Control what to expose | Output cell state | Hide cell state |
Why LSTMs Solve Vanishing Gradients
Cell state gradient:
dc_t/dc_{t-1} = f_t (just multiplication by forget gate)
If f_t close to 1, gradient flows unchanged!
No repeated multiplication by W_hhThe additive update (c_t = f_t * c_{t-1} + ...) creates a gradient highway.
6.5.4 Gated Recurrent Unit (GRU)
GRU is a simplified version of LSTM with fewer parameters.
GRU vs LSTM
LSTM: 3 gates (forget, input, output) + cell state
GRU: 2 gates (reset, update) + no separate cell stateGRU Architecture
h_{t-1}
|
+------+------+
| |
[reset] [update]
gate gate
| |
r_t z_t
| |
[x] |
| |
[tanh] |
| |
h_tilde |
| |
+----[x]------+
| |
(1-z_t) z_t
| |
+--[+]--+
|
h_tGRU Equations
# Reset gate: how much past to forget when computing candidate
r_t = sigmoid(W_r @ [h_{t-1}, x_t] + b_r)
# Update gate: how much to update hidden state
z_t = sigmoid(W_z @ [h_{t-1}, x_t] + b_z)
# Candidate hidden state
h_tilde_t = tanh(W_h @ [r_t * h_{t-1}, x_t] + b_h)
# Final hidden state: interpolate between old and new
h_t = (1 - z_t) * h_{t-1} + z_t * h_tilde_tGate Intuitions
| Gate | Purpose | Analogy to LSTM |
|---|---|---|
| Reset (r) | Control how much past to use for candidate | Similar to forget gate |
| Update (z) | Interpolate between old and new state | Combines forget + input gates |
GRU vs LSTM Comparison
| Aspect | LSTM | GRU |
|---|---|---|
| Parameters | More (3 gates + cell) | Fewer (2 gates) |
| Training speed | Slower | Faster |
| Performance | Often similar | Often similar |
| Long sequences | Slightly better | Good |
| Memory | Higher | Lower |
When to use which:
- Default: Try GRU first (simpler, faster)
- Very long sequences: LSTM may be better
- Limited compute: GRU
- Empirically: Often similar performance, try both
6.5.5 Bidirectional RNNs
Process sequences in both directions to capture context from past AND future.
Motivation
"The bank by the river" vs "The bank approved the loan"
Forward only: At "bank", only see "The"
Bidirectional: At "bank", see both "The" and "by the river" / "approved the loan"Architecture
Forward: x_1 --> x_2 --> x_3 --> x_4
| | | |
h_1 --> h_2 --> h_3 --> h_4
Backward: x_1 <-- x_2 <-- x_3 <-- x_4
| | | |
h'_1 <-- h'_2 <-- h'_3 <-- h'_4
Combined: [h_1, h'_1] [h_2, h'_2] [h_3, h'_3] [h_4, h'_4]BiLSTM Equations
# Forward LSTM
h_forward_t, c_forward_t = LSTM_forward(x_t, h_forward_{t-1}, c_forward_{t-1})
# Backward LSTM (processes sequence in reverse)
h_backward_t, c_backward_t = LSTM_backward(x_t, h_backward_{t+1}, c_backward_{t+1})
# Combine (concatenation is most common)
h_t = concat(h_forward_t, h_backward_t) # Shape: 2 * hidden_size
# Alternative combinations:
# h_t = h_forward_t + h_backward_t (sum)
# h_t = h_forward_t * h_backward_t (element-wise product)When to Use Bidirectional
| Task | Bidirectional? | Reason |
|---|---|---|
| Sequence classification | Yes | Full context helps |
| Named Entity Recognition | Yes | Context on both sides |
| Machine translation (encoder) | Yes | Full source context |
| Language modeling | No | Can't see future |
| Real-time prediction | No | Future not available |
| Text generation | No | Autoregressive |
6.5.6 Sequence-to-Sequence (Seq2Seq)
Encoder-decoder architecture for variable-length input to variable-length output.
Architecture
Encoder: Decoder:
x_1 --> x_2 --> x_3 --> x_4 <SOS> --> y_1 --> y_2 --> <EOS>
| | | | | | |
[E] --> [E] --> [E] --> [E] --> [D] --> [D] --> [D]
| ^
context vector |
(final state)---+Components
- Encoder: Processes input sequence, produces context vector
- Context vector: Final hidden state (or attention over all states)
- Decoder: Generates output sequence conditioned on context
Limitations (without attention)
- Context vector is fixed-size bottleneck
- Hard to compress long sequences
- Decoder must extract all information from single vector
Solution: Attention mechanism (covered in 6.6)
Questions & Answers
Q1: How does a Recurrent Neural Network (RNN) work?
Answer:
RNNs process sequential data by maintaining a hidden state that captures information from previous time steps.
Core mechanism:
At each time step t:
h_t = tanh(W_hh @ h_{t-1} + W_xh @ x_t + b)
y_t = W_hy @ h_t (optional output)Key properties:
- Hidden state as memory: h_t summarizes all information seen up to time t
- Parameter sharing: Same weights (W_hh, W_xh) used at every time step
- Sequential processing: Must process one step at a time (not parallelizable)
Unrolled view:
x_1 --> x_2 --> x_3 --> x_4
| | | |
h_0 --> h_1 --> h_2 --> h_3 --> h_4
| | | |
y_1 y_2 y_3 y_4Training (Backpropagation Through Time):
- Unroll network for T time steps
- Compute loss at each output
- Backpropagate gradients through time
- Update shared weights
Limitations:
- Vanishing/exploding gradients for long sequences
- Cannot capture long-range dependencies well
- Sequential nature prevents parallelization
Solutions: LSTM, GRU (gating mechanisms)
Q2: How do GRU cells work, and how do they address the vanishing gradient problem?
Answer:
GRU (Gated Recurrent Unit) uses two gates to control information flow, enabling better gradient propagation.
GRU equations:
# Reset gate: how much past to consider
r_t = sigmoid(W_r @ [h_{t-1}, x_t])
# Update gate: how much to update vs keep
z_t = sigmoid(W_z @ [h_{t-1}, x_t])
# Candidate state
h_tilde = tanh(W_h @ [r_t * h_{t-1}, x_t])
# Final state: interpolation
h_t = (1 - z_t) * h_{t-1} + z_t * h_tildeHow gates address vanishing gradients:
-
Update gate (z_t) creates gradient highway:
h_t = (1 - z_t) * h_{t-1} + z_t * h_tilde Gradient: dh_t/dh_{t-1} = (1 - z_t) + ... When z_t close to 0: gradient flows directly through! -
Additive update instead of multiplicative:
- Vanilla RNN: h_t = tanh(W @ h_{t-1} + ...) -- multiplicative
- GRU: h_t = (1-z) * h_{t-1} + z * h_tilde -- additive component
Additive connections preserve gradients better.
-
Gates learn when to update:
- For irrelevant inputs: z close to 0, keep old state
- For important inputs: z close to 1, update state
- Network learns optimal information flow
Comparison with vanilla RNN:
| Aspect | Vanilla RNN | GRU |
|---|---|---|
| Gradient flow | Multiplicative (vanishes) | Additive path (preserved) |
| Long-range deps | Poor | Good |
| Parameters | Fewer | More (2 gates) |
| Training | Unstable | Stable |
Q3: How does a BiLSTM work?
Answer:
A Bidirectional LSTM (BiLSTM) processes sequences in both forward and backward directions, then combines the results.
Architecture:
Forward LSTM: x_1 --> x_2 --> x_3 --> x_4
| | | |
h_f1 -> h_f2 -> h_f3 -> h_f4
Backward LSTM: x_1 <-- x_2 <-- x_3 <-- x_4
| | | |
h_b1 <- h_b2 <- h_b3 <- h_b4
Combined output at each position:
h_1 = [h_f1; h_b1] (concatenation)
h_2 = [h_f2; h_b2]
...How it works:
-
Forward pass: Standard LSTM left-to-right
- h_f_t sees x_1, x_2, ..., x_t (past context)
-
Backward pass: Standard LSTM right-to-left
- h_b_t sees x_T, x_{T-1}, ..., x_t (future context)
-
Combination: Concatenate (or sum/average) at each position
- Output dimension: 2 * hidden_size (if concatenating)
Why bidirectional helps:
Sentence: "The bank by the river was flooded"
At "bank":
- Forward only: context = "The" (ambiguous)
- Backward adds: context includes "river", "flooded" (clearly river bank!)Implementation:
import torch.nn as nn
bilstm = nn.LSTM(
input_size=embedding_dim,
hidden_size=hidden_dim,
num_layers=2,
bidirectional=True, # Key parameter
batch_first=True
)
# Output shape: (batch, seq_len, 2 * hidden_dim)When to use:
- Sequence labeling (NER, POS tagging)
- Text classification
- Encoder in seq2seq models
- Any task where full sequence is available
When NOT to use:
- Language modeling (can't see future)
- Real-time/streaming applications
- Autoregressive generation