30 Mins

3. Recurrent Neural Networks (RNNs) & LSTMs

Sequence Modeling and RNN Architectures

Recurrent Neural Networks (RNNs) are designed to handle sequential data where the current output depends not only on the current input but also on previous computations. This is achieved through a hidden state vector that acts as the network's memory, updated at each timestep as the model processes input tokens sequentially.

Mathematically, the update rule for a vanilla RNN is $h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b)$. By maintaining this internal state, the network can theoretically capture temporal dependencies. However, in practice, vanilla RNNs struggle with long-term dependencies due to the vanishing gradient problem during backpropagation through time (BPTT), where gradients shrink exponentially as they are propagated back through many layers of the chain rule.

Operator Note: Always initialize hidden states to zero if you lack a prior context, but be aware that different initialization schemes can significantly impact convergence in deeper RNN architectures.
Python 3
import torch
import torch.nn as nn

# Mock RNN setup for sequence processing
input_size, hidden_size, seq_len = 10, 20, 5
rnn = nn.RNN(input_size, hidden_size, batch_first=True)

# Simulate input sequence (batch, seq_len, features)
x = torch.randn(1, seq_len, input_size)
h0 = torch.zeros(1, 1, hidden_size)

# Forward pass
out, hn = rnn(x, h0)
print(f'Output shape: {out.shape}') # (1, 5, 20)

The Mechanics of LSTMs: Gating Mechanisms

Long Short-Term Memory (LSTM) networks address the vanishing gradient problem by introducing a 'cell state' that acts as an information highway, supplemented by specific gates: forget, input, and output. The forget gate determines what information to discard, the input gate determines what new information to add, and the output gate determines the final hidden state.

By using the logistic sigmoid activation for gates, these units can either 'close' or 'open' pathways for gradient flow. During backpropagation, the additive nature of the cell state updates allows gradients to flow much more effectively over long sequences compared to the multiplicative updates found in standard RNNs.

Operator Note: LSTMs have significantly higher parameter counts than vanilla RNNs, requiring more memory. Always monitor GPU utilization when scaling the hidden dimension.
Python 3
import torch
import torch.nn as nn

# LSTM cell definition
lstm = nn.LSTM(input_size=10, hidden_size=20, batch_first=True)

# Inputs: batch, sequence length, feature size
input_seq = torch.randn(2, 5, 10)

# LSTM returns (output, (h_n, c_n))
output, (h_n, c_n) = lstm(input_seq)
print(f'Final hidden state: {h_n.shape}')

GRU: The Simplified Alternative

Gated Recurrent Units (GRUs) simplify the complex LSTM architecture by merging the forget and input gates into a single 'update gate' and omitting the separate cell state. This results in fewer parameters and faster training times while maintaining the ability to capture long-term dependencies.

The GRU mechanism uses two gates: a reset gate and an update gate. The update gate controls how much of the previous state is preserved, while the reset gate determines how much of the past state should be ignored when computing the candidate activation. This architecture is often preferred in scenarios where computational efficiency is critical and performance requirements are similar to LSTMs.

Operator Note: Empirical studies suggest that GRUs often perform identically to LSTMs on small to medium datasets, making them a great starting point for model architecture selection.
Python 3
import torch.nn as nn

# GRU is a more memory-efficient alternative to LSTM
gru = nn.GRU(input_size=10, hidden_size=20, batch_first=True)

# GRU only returns (output, h_n)
output, hn = gru(torch.randn(2, 5, 10))
print(f'Hidden state size: {hn.shape}')

Knowledge Check

Ready to test your understanding of 3. Recurrent Neural Networks (RNNs) & LSTMs?

Back