Recurrent Neural Networks
The Problem with Sequences
CNNs transformed computer vision. But they have a fundamental limitation: they assume fixed-size inputs. What about:- Text: “The cat sat on the mat” (6 words)
- Time series: Stock prices over months (varying length)
- Audio: Speech of different durations
- Video: Frames over time
The Core Insight: Sequences have temporal dependencies. The word “sat” depends on knowing “cat” came before it. Today’s stock price depends on yesterday’s. We need networks that can remember.The fundamental difference between a CNN and an RNN: a CNN asks “what is here?”, while an RNN asks “what just happened, and what does that mean for what comes next?” CNNs are spatial; RNNs are temporal.
From Feedforward to Recurrent
The Feedforward Limitation
The Recurrent Solution
An RNN maintains a hidden state that carries information across time steps: Think of the hidden state as a person’s “running mental summary” while reading a book. After each sentence (), the reader updates their understanding () based on what they just read and what they already knew (). They cannot go back and re-read (that would be an attention mechanism), so their current understanding must compress everything important from the entire story so far into a fixed-size mental state.The RNN Equations
Mathematical Formulation
At each time step : Where:- is the input at time
- is the hidden state
- is the output
- transforms input to hidden
- transforms previous hidden to current
- transforms hidden to output
RNN Architectures
Many-to-One (Sequence Classification)
Use the final hidden state to classify the entire sequence:One-to-Many (Sequence Generation)
Generate a sequence from a single input:Many-to-Many (Sequence-to-Sequence)
Transform one sequence into another:Backpropagation Through Time (BPTT)
The Challenge of Temporal Gradients
RNNs are trained using BPTT - unrolling the network through time and applying backpropagation:The Vanishing/Exploding Gradient Problem
Why Gradients Vanish
The gradient through time involves products of the recurrent weight matrix: Mathematical intuition: This product is the crux of the problem. The tanh derivative peaks at 0.25 (since and its maximum is 1 at , but typical values during training are 0.1-0.25). Multiply that by at each step. If the largest singular value of (which is almost always the case), the product shrinks exponentially: . That is effectively zero — the network cannot learn from information 50 steps ago because the gradient signal has been annihilated. Conversely, if the singular values exceed 1, the product explodes exponentially. This is why vanilla RNNs are caught in a double bind: they need large weights to maintain gradients, but large weights cause explosions. The only stable regime is the knife-edge where singular values equal exactly 1 — which is unrealistic to maintain during training.The Impact on Learning
Solutions to Vanishing Gradients
Bidirectional RNNs
Why Look Both Ways?
In many tasks, future context is as important as past context:- “The bank of the river” vs “I went to the bank”
- In translation, the end of a sentence can clarify the beginning
Deep RNNs
Stacking RNN Layers
Practical Example: Character-Level Language Model
RNN Applications
Exercises
Exercise 1: Implement RNN from Scratch
Exercise 1: Implement RNN from Scratch
Implement a complete RNN without using Verify it gives similar results to
nn.RNN:nn.RNN.Exercise 2: Adding Problem
Exercise 2: Adding Problem
Implement the adding problem to test long-range dependencies:
- Input: Two sequences - numbers and a mask
- Output: Sum of numbers where mask is 1
- Example: Numbers [0.3, 0.1, 0.8, 0.2], Mask [1, 0, 0, 1] → Output: 0.5
Exercise 3: Name Classification
Exercise 3: Name Classification
Build a model to classify names by nationality:
- Input: Character sequence (name)
- Output: Nationality (English, French, German, etc.)
Exercise 4: Sequence-to-Sequence
Exercise 4: Sequence-to-Sequence
Build a simple date format converter:
- Input: “January 15, 2023”
- Output: “2023-01-15”
Training Pitfalls and Debugging Hints
Key Takeaways
What’s Next
Module 9: LSTMs & GRUs
Solve the vanishing gradient problem with gated architectures — learn how LSTM and GRU cells maintain long-term memory through gates.
Interview Deep-Dive
Why do vanilla RNNs fail on long sequences? Explain the vanishing gradient problem in the temporal context.
Why do vanilla RNNs fail on long sequences? Explain the vanishing gradient problem in the temporal context.
Strong Answer:
- In an RNN, the hidden state update is . During BPTT, the gradient of loss with respect to early hidden states requires multiplying the Jacobian across all time steps: .
- Each Jacobian includes . The tanh derivative is at most 1 and typically 0.1-0.5. The product of such terms approaches zero exponentially. After 50 time steps, gradients can be or smaller.
- The consequence is selective amnesia: the RNN can learn short-range patterns (2-5 steps) but cannot learn dependencies from 20+ steps ago. This is fundamentally different from the vanishing gradient in feedforward networks because the SAME weight matrix is applied at every step, making the problem a function of the spectral radius of .
- If the largest singular value of is less than 1, gradients vanish. If greater than 1, they explode. There is no stable middle ground for vanilla RNNs, which is why gated architectures (LSTM, GRU) were necessary.
Explain BPTT and truncated BPTT. What are the trade-offs of truncation length?
Explain BPTT and truncated BPTT. What are the trade-offs of truncation length?
Strong Answer:
- BPTT unrolls the RNN through time and applies standard backpropagation to the resulting feedforward graph. An RNN processing length is equivalent to a -layer feedforward network with shared weights. Gradients are computed backward through all steps.
- Full BPTT has two problems: memory grows linearly with (all activations cached), and gradients vanish or explode through hundreds of multiplications.
- Truncated BPTT limits backpropagation to a window of steps. Every steps, the hidden state is detached from the computation graph. Gradients only flow backward through the most recent steps.
- Trade-off: the model can only LEARN dependencies up to steps long. A truncation of 35 means a 50-step dependency is invisible to the optimizer. However, the model can still USE long-range information already encoded in the hidden state — it just cannot learn to encode it better. The practical sweet spot is for language modeling, balancing dependency learning against memory and stability.
When would you still choose an RNN/LSTM over a transformer today? Are there cases where recurrence is genuinely better?
When would you still choose an RNN/LSTM over a transformer today? Are there cases where recurrence is genuinely better?
Strong Answer:
- Real-time streaming inference: RNNs process one token at a time with constant memory ( per step), making them ideal for streaming audio transcription, real-time sensor processing, or any setting where you receive data one sample at a time and need immediate outputs. Transformers require buffering the entire context window before processing.
- Extremely long sequences with limited compute: for sequences of 100,000+ steps (e.g., long-duration biosignals, multi-day time series), transformers’ attention becomes prohibitive. RNNs process these in time with fixed memory, though they sacrifice long-range dependency quality.
- Edge deployment with tight memory constraints: an LSTM cell has fixed-size state regardless of sequence length, making memory consumption predictable and small. A transformer’s KV-cache grows linearly with sequence length.
- State Space Models (SSMs) like Mamba represent a modern compromise: they have RNN-like inference with transformer-like training parallelism, and they match transformer quality on many benchmarks. SSMs are increasingly the right answer for the “when would you use recurrence” question — they inherit the efficiency of RNNs without the gradient flow problems.