Angad Sandhu
Search
Browse
On this page

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 state

Applications:

  • 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 steps

RNN 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 weights

Parameter 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 x

6.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 T

Consequences

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

SolutionHow it helps
Gradient clippingCaps exploding gradients
LSTM/GRUGating mechanisms preserve gradients
Skip connectionsDirect gradient paths
Proper initializationStart in stable regime
Shorter sequencesReduce 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    gate

LSTM 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_t

LSTM 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

GatePurposeWhen high (close to 1)When low (close to 0)
Forget (f)Control memory retentionKeep previous memoryErase previous memory
Input (i)Control new informationAdd new informationIgnore new information
Output (o)Control what to exposeOutput cell stateHide 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_hh

The 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 state

GRU Architecture

         h_{t-1}
            |
     +------+------+
     |             |
  [reset]      [update]
   gate          gate
     |             |
    r_t           z_t
     |             |
   [x]             |
     |             |
  [tanh]           |
     |             |
  h_tilde          |
     |             |
     +----[x]------+
           |       |
         (1-z_t)  z_t
           |       |
           +--[+]--+
              |
             h_t

GRU 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_t

Gate Intuitions

GatePurposeAnalogy to LSTM
Reset (r)Control how much past to use for candidateSimilar to forget gate
Update (z)Interpolate between old and new stateCombines forget + input gates

GRU vs LSTM Comparison

AspectLSTMGRU
ParametersMore (3 gates + cell)Fewer (2 gates)
Training speedSlowerFaster
PerformanceOften similarOften similar
Long sequencesSlightly betterGood
MemoryHigherLower

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

TaskBidirectional?Reason
Sequence classificationYesFull context helps
Named Entity RecognitionYesContext on both sides
Machine translation (encoder)YesFull source context
Language modelingNoCan't see future
Real-time predictionNoFuture not available
Text generationNoAutoregressive

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

  1. Encoder: Processes input sequence, produces context vector
  2. Context vector: Final hidden state (or attention over all states)
  3. 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:

  1. Hidden state as memory: h_t summarizes all information seen up to time t
  2. Parameter sharing: Same weights (W_hh, W_xh) used at every time step
  3. 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_4

Training (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_tilde

How gates address vanishing gradients:

  1. 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!
  2. 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.

  3. 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:

AspectVanilla RNNGRU
Gradient flowMultiplicative (vanishes)Additive path (preserved)
Long-range depsPoorGood
ParametersFewerMore (2 gates)
TrainingUnstableStable

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:

  1. Forward pass: Standard LSTM left-to-right

    • h_f_t sees x_1, x_2, ..., x_t (past context)
  2. Backward pass: Standard LSTM right-to-left

    • h_b_t sees x_T, x_{T-1}, ..., x_t (future context)
  3. 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

Browse the library