Sequence Modeling & Vanilla RNNs: Embeddings, Unrolling & BPTT
How token IDs become learned dense embeddings, how Recurrent Neural Networks reuse shared weights across time steps, and why Backpropagation Through Time (BPTT) causes vanishing and exploding gradients.
Understanding RNNs & BPTT explains the EXACT bottleneck that led to LSTMs, Attention, and modern Transformers!
Token embeddings (nn.Embedding), sequence padding/packing, causal sequence modeling, and gradient clipping for sequential models are foundational skills across NLP, speech, and time-series forecasting.
Even today, lightweight RNNs/GRUs/State-Space Models excel on streaming sensor/IoT/financial time-series where O(1) per-step inference memory matters.
Classic ML interview question: 'Why do Vanilla RNNs struggle with long-range dependencies? Derive the gradient ∂h_T/∂h_1 via BPTT and explain why gradient clipping fixes exploding gradients but NOT vanishing gradients!'
In PyTorch, if your vocabulary has V = 50,000 words and embedding dimension D = 512, what is the shape of nn.Embedding(50000, 512).weight and what does looking up token ID 42 return?
- Explain why nn.Embedding(V, D) is an O(1) row lookup mathematically identical to one-hot × E
- Trace unrolled Vanilla RNN recurrence h_t = tanh(W_xh x_t + W_hh h_{t-1} + b) with shared weights across time
- Match sequence tasks to Many-to-One, Many-to-Many, and One-to-Many topologies
- Prove why BPTT repeatedly multiplies W_hh^T across T steps, causing vanishing or exploding gradients
Reading a sentence is like running a relay race where each word hands a summary notebook (h_t) to the next word. Because the exact same reader (W_xh, W_hh) processes Word 1, Word 2, and Word 500, an RNN can handle sentences of any length! The catch? Every time the notebook gets photocopied (× W_hh + tanh), tiny fading (0.7^30 ≈ 0.00002) washes out the earliest notes!
1. Learned Token Embeddings: Turning Words Into Dense Geometry
Neural networks can't multiply strings like 'king' or 'queen'. One-hot vectors waste 50,000 dimensions and treat 'cat' and 'dog' as 100% orthogonal. nn.Embedding gives every token a compact learned vector where synonyms cluster together!
From Token IDs to (B, T, D)
Given integer token IDs ids of shape and embedding matrix :
- During backpropagation, PyTorch updates only the rows of that appeared in the current mini-batch (sparse row gradients!).
- Weight Tying: Many language models tie the input embedding matrix with the final output classifier head , cutting millions of parameters for free.
2. Unrolling an RNN Across Time & Sequence Topologies
Click through Many-to-One, Many-to-Many, and One-to-Many below to see how the exact same RNN cell adapts to sentiment analysis, NER tagging, and image captioning!
Vanilla RNN Recurrence Equation
At every step :
- Weight Sharing Across Time: Just as CNNs share weights across space, RNNs share the exact same across time, allowing variable-length sequences with fixed parameter count!
RNN Sequence Topology Explorer
Reads every token step-by-step and passes ONLY the final hidden state h_T into a Linear classifier.
3. Backpropagation Through Time (BPTT) & Why Gradients Vanish/Explode
To teach Step 1 ('cat') from a loss at Step 10 ('was'), BPTT multiplies the Jacobian ∂h_k / ∂h_{k-1} backward 9 times in a row — producing a geometric series (W_hh)^9!
The BPTT Product Law
- Because , if the largest singular value , gradients vanish exponentially () — the RNN can ONLY learn short-term patterns!
- If , gradients explode () — easily fixed by Global L2 Gradient Norm Clipping (Ch 9), whereas vanishing gradients require a new architecture (LSTM / GRU in Ch 18!).
h_t = tanh(W_xh · x_t + W_hh · h_{t-1} + b)
Projects the new word/sensor reading at step t into hidden space.
B=16, T=50, D=128, H=256, nn.RNN(128, 256, batch_first=True) reads (16, 50, 128) and outputs all hidden states (16, 50, 256) plus final state (1, 16, 256).Worked Example: Watching BPTT Vanish Across 20 Steps
Suppose scalar W_hh = 0.8 and tanh'(z) = 0.8 at every step. How much of a unit loss gradient at Step 20 reaches Step 1?
per backward step.
Which BPTT failure does Global L2 Gradient Norm Clipping fix, and which one does it NOT fix?
Why does nn.RNN(..., batch_first=True) matter so much in PyTorch?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
When training on a 10,000-word book, unrolling all 10,000 steps would run out of GPU memory. Truncated BPTT detaches the hidden state (h = h.detach()) every K = 64 or 128 steps so forward memory continues while gradients only backpropagate K steps.
|W_hh| below 0.8 and above 1.15 in the Unrolled RNN & BPTT Animator below to see gradients vanish and explode across the 10-word sentence!Unrolled RNN Forward Pass & BPTT Gradient-Decay Animator
Watch a 10-word sentence flow forward (cyan), then watch BPTT backward gradients (crimson) shrink or explode as |W_hh| varies.
(W_xh, W_hh) across variable-length time steps, and BPTT's repeated W_hh^T multiplication causes vanishing/exploding gradients.Token Embeddings in Every LLM
GPT, LLaMA, and Gemini all begin with an nn.Embedding(vocab_size, d_model) lookup table.
Streaming Sensor & IoT Anomaly Detection
O(1) constant memory per time step makes recurrent cells ideal for embedded edge telemetry.
Speech & Time-Series Classification
Many-to-One and Many-to-Many recurrent layers model ordered temporal streams.
import torch
import torch.nn as nn
# 1. From-Scratch Embedding Lookup + Single-Step Vanilla RNN
def embedding_lookup(table: torch.Tensor, ids: torch.Tensor) -> torch.Tensor:
return table[ids] # O(1) row gather: (B, T) -> (B, T, D)
# 2. Idiomatic PyTorch Many-to-One Sentiment RNN (ALWAYS set batch_first=True!)
class SentimentRNN(nn.Module):
def __init__(self, vocab_size: int, emb_dim: int = 128, hidden_dim: int = 256, num_classes: int = 2):
super().__init__()
self.emb = nn.Embedding(vocab_size, emb_dim, padding_idx=0)
self.rnn = nn.RNN(emb_dim, hidden_dim, batch_first=True)
self.head = nn.Linear(hidden_dim, num_classes)
def forward(self, token_ids: torch.Tensor) -> torch.Tensor:
x = self.emb(token_ids) # (B, T, D)
out, h_last = self.rnn(x) # h_last: (1, B, H)
return self.head(h_last[-1]) # (B, num_classes)
batch_first=True on nn.RNN / nn.LSTM / nn.GRU.batch_first=True when feeding (B, T, D) tensors!h = h.detach() between truncated chunks so PyTorch doesn't backprop back to Step 0!nn.RNN(D, H) when batch_first is NOT specified?nn.Embedding(V, D) computed efficiently under the hood?h = h.detach() between consecutive chunks?