11 Memory Whiskers & Attention
RNNs, LSTMs, and the Transformers
🐾 Evergreen Chapter: Core mathematics and theory do not expire. Last verified: 2026-02-24
Prerequisites: Chapter 8-10 Technical Keywords: Recurrent Neural Networks (RNNs), Sequence Modeling, Hidden State, LSTM (Long Short-Term Memory), GRU, Sequence-to-Sequence, Attention Mechanism, Self-Attention, Transformers
Pixel is a very smart kitten now. He can look at a single, frozen image and recognize a toy (Chapter 9: CNNs). He can look at a single word and understand its mathematical meaning (Chapter 10: Embeddings).
But the world is not a series of disconnected, frozen moments. It is a flowing stream of time.
If you say to Pixel: “The human opened the shiny tin can, so I knew I was getting…” Pixel instantly knows the next word is “Food.”
How? Because he remembers the words “tin can” from three seconds ago.
Our previous brains (Fully Connected Networks and CNNs) have terrible amnesia. They process input x_1, spit out an answer, completely wipe their memory, and then look at input x_2. If you feed a CNN the frames of a movie one by one, it has no idea what happened in the previous scene.
To understand language, music, or video, Pixel needs a network that can carry a thought across time. He needs a Recurrent Neural Network (RNN).
11.1 Recurrent Neural Networks (RNNs): The Loop of Thought
An RNN is just a standard neural network (Chapter 8) with one massive, reality-bending twist: it feeds its own output back into itself.
Imagine a line of kittens, one for every second in time.
- At time t=1, Kitten 1 hears the word “The”. He calculates his internal thought (the Hidden State, h_1).
- At time t=2, Kitten 2 hears the word “human”. But Kitten 2 also receives the thought (h_1) from Kitten 1. He combines the new word with the old thought to create h_2.
- At time t=3, Kitten 3 hears the word “opened”. He combines it with h_2 to create h_3.
h_t = \text{Activation}(W_x \cdot x_t + W_h \cdot h_{t-1} + b)
The matrix W_h is the “Memory Weight.” It decides how much of the past thought to keep, and how to mix it with the present.
Because the hidden state is constantly updated and passed forward, the final kitten at the end of the sentence possesses a single, dense vector (h_T) that contains the mathematical summary of the entire sentence.
Analogy
Reading a book. You don’t read page 50 as a blank slate. You read page 50 while holding the context of pages 1-49 in your head (the Hidden State).
11.2 The Catastrophic Amnesia of Vanilla RNNs
RNNs sound perfect. But in practice, they are a disaster.
Let’s say the sentence is a whole paragraph: “I grew up in France… [100 words later] … so I speak fluent ____.”
By the time the RNN reaches the end of the paragraph, the mathematical signal from the word “France” has been multiplied by the memory weight (W_h) a hundred times.
Remember Chapter 8? If you multiply a decimal by itself 100 times, it vanishes to zero (The Vanishing Gradient Problem). The network completely forgets “France” and has no idea what language to predict. In practice, how far back a vanilla RNN retains context depends on the sequence, weights, and optimization—without gating, long-range dependencies often fade rapidly.
11.3 LSTMs & GRUs: The Memory Vaults
To fix this amnesia, researchers in 1997 invented the Long Short-Term Memory (LSTM) network.
Instead of just forcing the kittens to blindly mix the past with the present, an LSTM gives each kitten a complex control panel with three Gates (small neural networks that act like valves):
- The Forget Gate: “Looking at this new word, what old memories should I instantly delete?” (e.g., If the sentence ends with a period, forget the previous grammar rules).
- The Input Gate: “Which parts of this brand new word are actually important enough to save?”
- The Output Gate: “Of all the memories I have stored, which ones should I broadcast to the next kitten?”
By using these gates, an LSTM can trap a memory (like the word “France”) inside a protected mathematical vault (the Cell State) and carry it completely untouched across 100 words until it is needed.
A GRU (Gated Recurrent Unit) is just a slightly simpler, faster version of an LSTM that combines the gates.
Rosetta Stone
| Kitten World | Math/Concept | Python (PyTorch) |
|---|---|---|
| “The flowing thought” | Hidden State (h_t) | output, h_n = rnn(x) |
| “The memory vault” | LSTM / Cell State (c_t) | nn.LSTM(input_size, hidden_size) |
| “The valves” | Forget / Input / Output Gates | torch.sigmoid(torch.cat([h, x], dim=-1) @ W_f.T + b_f) |
11.4 The Problem with Reading Left-to-Right
LSTMs ruled the world of translation (Google Translate) for a decade. But they still had a massive bottleneck.
Imagine translating a 20-word sentence from English to Japanese. The English LSTM has to read the words one by one, step by step, cramming the entire meaning of the sentence into a single vector at the very end (h_{20}). Then, the Japanese LSTM takes that single vector and tries to unpack it to generate Japanese words.
This is incredibly slow (you can’t parallelize it, because word 2 must wait for word 1). And worse, trying to squeeze a whole paragraph into one vector is like trying to squeeze a whole living room into a single pixel. Information is lost.
In 2017, researchers at Google published “Attention Is All You Need.” Transformers built around the Attention mechanism largely displaced LSTMs across mainstream NLP workloads, primarily because they can be trained efficiently in parallel at massive scale.
11.5 The Attention Mechanism: Looking at the Whole Room
Instead of reading left-to-right and cramming memories into a vault, the Attention Mechanism allows the network to look at every single word in the sentence simultaneously.
When Pixel is translating the word “bank,” he needs to know if it’s a river bank or a money bank.
With Attention, Pixel (standing on the word “bank”) shoots out mathematical “queries” to every other word in the sentence.
- Does “river” have a strong connection to “bank”? Yes! (High attention score).
- Does “the” have a strong connection? No. (Low attention score).
Instead of relying on a compressed hidden state, Pixel dynamically reaches across the entire sentence and pulls exactly the context he needs, ignoring the distance. The word “France” could be 1,000 words away, and the Attention Mechanism can link to it directly in a single mathematical step.
\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V
(Don’t panic! Q is the Query [what Pixel is looking for], K is the Key [what other words offer], and V is the Value [the actual meaning of the words]. This is just Matrix Multiplication from Chapter 1!)
11.6 The Transformer: Engine Behind Modern Chat Assistants
When you take the Attention Mechanism, run it dozens of times in parallel (Multi-Head Attention), and completely throw away the slow, left-to-right RNN architecture, you get a Transformer (Vaswani et al., 2017).
A Transformer processes the entire sentence at once. Because it doesn’t have to wait for step 1 to finish before doing step 2, you can train it on massive GPUs (Parallel Computing) on the entire internet at once.
Famous Transformer Architectures:
- Encoder-Only (BERT): Great at reading a whole sentence and understanding the context. (Used for search engines and sentiment analysis).
- Decoder-Only (GPT): Great at looking at the past words and predicting the exact next word. (Commonly used in chat assistants such as ChatGPT).
- Encoder-Decoder (BART / T5): Great at reading a sentence and generating a completely new sentence. (Used for translation and summarization).
Micro-notebook (optional): micro-notebooks/phase03_ch11_attention_heatmap.ipynb
Time: ~20 minutes. Goal: visualize self-attention weights and confirm Q/K/V shape relationships.
11.7 Removing the Training Wheels
The Real Engineering
We used memory vaults and looking at the whole room to explain RNNs and Attention. In practice, LSTMs use parameterized gating mechanisms (sigmoid/tanh) to control information flow and mitigate vanishing gradients in the hidden state. The Attention Mechanism computes softmax(QK^T / sqrt(d)) * V. It entirely abandons sequential processing, allowing the GPU to compute the relationships between all tokens in a sequence simultaneously using highly optimized parallel matrix multiplications.
11.8 Paws and Reflect: Chapter Quiz
Work through these conceptually before checking the answers.
You feed a 100-word sentence into a Vanilla RNN. Why does it struggle to remember the first word by the time it reaches the 100th word?
An LSTM has a “Forget Gate.” Why would a neural network ever want to purposefully forget information?
What is the main architectural difference that makes a Transformer so much faster to train than an LSTM?
In the Attention equation, if the Query (Q) for the word “apple” has a very high dot product (Chapter 1) with the Key (K) for the word “tree”, what happens to the Value (V)?
Reveal answers
- Because of the Vanishing Gradient problem. The hidden state is multiplied by the weight matrix 100 times. The signal of the first word shrinks to nearly zero.
- To clear the memory for new context. If the sentence ends and a new paragraph begins on a completely different topic, the old grammar and subject data will just confuse the network. It needs to flush the vault.
- The LSTM must process sequentially (word 1, then word 2, then word 3). The Transformer processes the entire sequence simultaneously in parallel.
- If that dot product is much larger than competing keys, softmax turns it into a high attention weight (like 0.90)—because softmax normalizes relative to all keys (two equally large keys split the probability evenly). When “tree” dominates, the network pulls most of the “tree” Value into the representation of “apple,” heavily linking the two concepts together.
11.9 Chapter 11 Summary
You’ve learned how AI processes time and language:
- RNNs: Neural networks with loops that pass a “Hidden State” forward through time.
- The Amnesia Problem: Vanilla RNNs forget long-term context because of vanishing gradients.
- LSTMs / GRUs: Advanced RNNs with mathematical “Gates” that can trap and protect memories over long sequences.
- The Attention Mechanism: Allowing the network to dynamically look at every word in a sentence simultaneously and calculate exactly which words are relevant to each other.
- Transformers: The parallel-processing architecture built entirely on Attention that replaced RNNs and powers modern Large Language Models (LLMs) like GPT and BERT.
Pixel has a brain. He has eyes. He understands concepts. He has a memory.
He is no longer just a toy classifier. He is a massive, multi-layered intelligence. But how do we take this massive intelligence and scale it up to the size of a Frontier AI? How does a kitten become a 100-billion-parameter lion?
We need to understand the modern architecture of Large Language Models. 🐈🦁
AI Safety Thread: Chapter 11
The Hallucination Problem: A Transformer (like GPT) does not “know” facts in the way a database does. It is primarily optimized to predict the next token based on prior context and attention patterns.
If you ask it for the biography of a real person, and that person isn’t well-represented in its training data, the Attention Mechanism can link together highly probable, grammatically correct words that are factually wrong. This is a Hallucination. The model isn’t intentionally lying; it is continuing a probabilistic autocomplete process. Deploying an LLM as a “search engine” without safeguards is a major risk.