Basic RNN (LSTM)
Train an LSTM model for time series prediction using DeepSpeed with ZeRO-2 optimization.
Overview
This example demonstrates:
- LSTM architecture with proper initialization
- ZeRO-2 memory optimization
- Gradient clipping for RNN stability
- Validation set and early stopping
- Optional W&B experiment tracking
Task: Multi-frequency sine wave prediction
Understanding Sequential Data
Why Sequential Data is Different
Traditional feedforward neural networks assume that all inputs are independent. However, many real-world data types have inherent temporal or sequential dependencies:
| Data Type | Sequential Nature |
|---|---|
| Text | Words depend on previous words for meaning |
| Speech | Phonemes flow continuously in time |
| Stock Prices | Today's price relates to yesterday's |
| Weather | Temperature patterns follow temporal cycles |
| Music | Notes form melodies through time |
| Video | Frames are temporally correlated |
The key insight is that the order matters. The sentence "dog bites man" has a completely different meaning from "man bites dog" even though they contain the same words.
The Time Dimension
Sequential data introduces a time index to our data:
Where:
- is the observation at time step
- is the total sequence length
- Each can be a scalar, vector, or even a matrix
For example, in a sentence:
- = "The"
- = "cat"
- = "sat"
- ...
Why Standard Neural Networks Fail
A feedforward network processes inputs independently:
Problems:
- No memory - Each input processed in isolation
- Fixed input size - Cannot handle variable-length sequences
- No parameter sharing - Learns separate patterns for each position
Markov Chains: The Foundation
What is a Markov Chain?
A Markov chain is a mathematical model for sequences where the probability of the next state depends only on the current state, not on the history of how we got there.
The Markov Property (Memoryless):
This is called the first-order Markov assumption - the future depends only on the present, not the past.
Markov Chain Diagram
Transition Matrix
The dynamics of a Markov chain are captured by a transition matrix :
Where is the probability of transitioning from state to state .
Properties:
- All entries are non-negative:
- Rows sum to 1:
Higher-Order Markov Models
Real sequences often have longer dependencies. An -th order Markov model considers the last states:
Example: In language modeling:
- 1st order: P("sat" | "cat")
- 2nd order: P("sat" | "the", "cat")
- 3rd order: P("sat" | "the", "cat", "happily")
From Markov Chains to RNNs
RNNs extend Markov chains by:
- Learning the transition function (not just storing probabilities)
- Maintaining a continuous hidden state instead of discrete states
- Theoretically capturing infinite-order dependencies through the hidden state
| Aspect | Markov Chain | RNN |
|---|---|---|
| State | Discrete | Continuous vector |
| Transitions | Fixed probabilities | Learned function |
| Memory | Limited to order | Theoretically unlimited |
| Parameters | $O( | S |
Recurrent Neural Network Architecture
The Core Idea
An RNN introduces a hidden state that acts as memory, carrying information from previous time steps:
The hidden state is updated at each time step based on:
- The previous hidden state
- The current input
RNN: Folded vs Unfolded Representation
RNNs can be visualized in two equivalent ways:
Folded (Compact) View
The folded view shows the RNN as a single unit with a self-loop, resembling a Markov chain:
This compact representation emphasizes:
- The recurrent connection (self-loop)
- Parameter sharing - same weights at every time step
- The Markov-like structure
Unfolded (Expanded) View
Unfolding the RNN through time reveals its structure as a deep network:
Key Insight: The same weights are used at every time step. This is called weight tying or parameter sharing.
Mathematical Formulation
Vanilla RNN Equations
Hidden State Update:
Output:
Where:
- — input vector at time
- — hidden state at time
- — output at time
- — input-to-hidden weights
- — hidden-to-hidden weights (recurrent)
- — hidden-to-output weights
- — bias vectors
Complete RNN Data Flow
Why Weight Sharing Matters
Using the same weights at every time step provides several benefits:
- Generalization - Patterns learned at one position apply everywhere
- Variable-length sequences - Same model handles any sequence length
- Parameter efficiency - Number of parameters independent of sequence length
- Translation invariance - Recognizes patterns regardless of their position in the sequence
Forward Propagation Through Time (FPTT)
The Forward Pass
Forward propagation in an RNN processes the sequence from to :
Algorithm
Forward Propagation Through Time:
Step-by-Step Example
Let's trace through with concrete values:
Setup:
- Input dimension:
- Hidden dimension:
- Sequence: ,
Weights (simplified):
Time step 1:
Time step 2: