Day 4:Word Embeddings (`nn.Embedding`), Sequence Models (`RNN`, `LSTM`) & Vanishing Gradients
Battle-tested daily lesson note • 100% runnable code, interview Q&A, test suite & interactive quiz
Week 6 — Day 4: Word Embeddings (nn.Embedding), Sequence Models (RNN, LSTM) & Vanishing Gradients
Mentor's Note (10+ YOE Staff AI Engineer POV): Why do we study
nn.Embedding,RNNs, andLSTMs right before building Transformers in Week 7?
nn.Embedding(vocab_size, embed_dim)is the very first layer of every LLM (GPT-4,Llama-3)! When a token ID like42enters an LLM,nn.Embeddingsimply looks up Row#42in a trainable matrix of shape(vocab_size, embed_dim)!- Why RNNs Failed & Why Transformers Were Invented: Interviewers love asking: "Why couldn't Recurrent Neural Networks (
RNN/LSTM) scale to 100,000-token context windows or train on 10,000 GPUs in parallel?" Today you learn the two mathematical reasons: Sequential Time Dependency () and Vanishing / Exploding Gradients Through Time ()!
Part 1: How nn.Embedding Works Under the Hood
Instead of multiplying a huge one-hot vector [0, 0, ..., 1, ..., 0] (length 100,000) by a matrix, nn.Embedding(num_embeddings=100_000, embedding_dim=768) is an array index lookup table!
- Input: Integer Tensor of Token IDs of shape
(Batch, Seq_Len) - Output: Float Tensor of Dense Vectors of shape
(Batch, Seq_Len, Embedding_Dim)
Part 2: RNN vs LSTM Gates & The Vanishing Gradient Equation
2.1 Vanilla RNN Hidden State Equation
At each time step :
- Problem #1 (No Parallelism Across Time): You cannot compute step until step finishes! GPUs sit idle waiting on sequential loops.
- Problem #2 (Vanishing Gradients in Backpropagation Through Time — BPTT):
To compute how token affects the final token , the Chain Rule multiplies Jacobian matrices together:
- If the largest eigenvalue of is (e.g.,
0.8), then over tokens: $0.8^{100} = 2.0 \times 10^{-10} \approx \mathbf{0.0}$ (Vanishing Gradient — the model forgets the beginning of the sentence!). - If the eigenvalue is (e.g.,
1.2), then $1.2^{100} = 8.2 \times 10^7 \to \mathbf{\text{NaN}}$ (Exploding Gradient!).
- If the largest eigenvalue of is (e.g.,
2.2 How LSTM (Long Short-Term Memory) Partially Helped
LSTM introduced an additive Cell State highway () controlled by 3 Sigmoid gates (Forget Gate , Input Gate , Output Gate ) so gradients could flow through addition (+) instead of repeated matrix multiplication—until Self-Attention (Transformers) eliminated the sequential bottleneck entirely in 2017!
Part 3: Hands-On Lab — nn.Embedding, LSTM & Vanishing Gradient Proof (sequence_models_rnn_lstm.py)
Check out src/sequence_models_rnn_lstm.py (in Tab 2: Codes — click Run in Browser to execute) and run the script and tests:
python week06_deep_learning_and_pytorch_from_scratch/day04_word_embeddings_rnn_lstm_and_vanishing_gradients/src/sequence_models_rnn_lstm.py
python -m unittest discover -s week06_deep_learning_and_pytorch_from_scratch/day04_word_embeddings_rnn_lstm_and_vanishing_gradients/tests -v
In Simple English: Reading a Sentence One Word at a Time (RNN vs LSTM & Memory Fade)
Imagine trying to summarize a 500-page novel by writing a 3-sentence sticky note after reading Page 1, erasing and rewriting that same tiny sticky note after Page 2, and continuing to Page 500:
- By Page 500, you have almost completely forgotten who the villain was on Page 3! That is the Vanishing Gradient Problem: multiplying weights step-by-step ( when ) shrinks early learning signals to zero!
- LSTM adds a separate "long-term notebook" (cell state conveyor belt) with Forget/Keep gates, which helps — but still forces you to read word 1 before word 2 before word 3 slowly. Week 7 Transformers solve both problems at once by letting every word look directly at every other word simultaneously!