Long Short-Term Memory (LSTM) cells
The Vanishing Gradient Problem (Why We Need LSTMs)
In a standard RNN, hidden state . During backpropagation through time (BPTT), we compute:
Why this step? The chain rule forces us to multiply Jacobians across all time steps. Each Jacobian contains and the derivative of , which is .
If , the product shrinks exponentially as grows (vanishing gradient). If , it explodes. Either way, learning long-term dependencies becomes impossible.
The LSTM fix: The cell state flows through time with additive updates, not multiplicative ones. This creates gradient highways that preserve information.
LSTM Architecture: The Four Gates Derivation
An LSTM has:
- Input (current input vector)
- Previous hidden state
- Previous cell state
- Three gates: forget, input, output
- Outputs: new cell state and hidden state
Step 1: Forget Gate (What to Discard)
What: A vector in where is cell state dimension.
Why sigmoid? We want values between 0 (completely forget) and 1 (completely remember). Sigmoid outputs this range.
How it works: is element-wise multiplied with . If , dimension of the cell state is erased. If , it's preserved.
Notation: means concatenating the two vectors: if and , then . The weight matrix .
Step 2: Input Gate (What New Info to Store)
What: is a gate vector in ; is a candidate cell state in .
Why two parts? We separate what to add () from how much to add (). The candidate is computed using (outputs ) because cell states need signed values to represent both positive and negative information.
Why this step? Without the gate , we'd always add the full candidate. The gate lets the network learn when new information is relevant (gate open) vs. when to ignore it (gate closed).
Step 3: Update Cell State (Combine Forget + Input)
Notation: is element-wise (Hadamard) product.
Derivation from scratch:
- Start with old cell state
- Multiply by forget gate: (keeps relevant memories)
- Compute what to add: (new relevant info)
- Add them:
Why this is brilliant: This update is additive, not multiplicative! During backpropagation:
The gradient flows through without repeated matrix multiplications. If (forget gate open), gradients flow unchanged. This is the gradient highway that solves vanishing gradients.
Step 4: Output Gate (What to Expose)
What: controls which parts of the cell state to expose as the hidden state .
Why ? Cell states can grow large over time. squashes to for stability.
Why not just ? The cell state is the internal memory (can be large, unbounded). The hidden state is the external representation we pass to the next layer—we want it controlled and squashed.
Why this step? The output gate lets the network decide: "I have this memory, but do I want to expose it now?" For example, storing grammatical gender but only outputing it when generating a pronoun.
Complete LSTM Forward Pass
Given inputs , initialize , . For to :
Parameter count: If = input dim, = hidden dim, = cell dim (usually ):
- Each gate has weight matrix and bias
- 4 sets of parameters (forget, input, candidate, output)
- Total: parameters
Comparison to vanilla RNN:
- RNN: gradient multiplies by at each step → exponential decay
- LSTM: gradient multiplies by (values near 1) → linear flow, no exponential decay
The cell state acts as a gradient superhighway—if forget gates stay open (), gradients flow back hundreds of steps with minimal degradation.
Why LSTMs help: The word "not" appears early but affects "bad" later. An RNN might forget "not" by the time it sees "bad".
LSTM behavior:
- When processing "not", input gate opens, storing negation in
- Forget gate stays high through "was" (don't forget negation)
- When "bad" arrives, the cell state still contains "negation", so the network outputs positive
Numerical walkthrough (simplified, 1D):
- ("not"): , → (store negation)
- ("bad"): , (negation preserved)
- Output gate uses to predict positive sentiment
Why this step? The additive update means directly depends on with minimal information loss, unlike RNN's which can erase .
Sequence:
LSTM solution:
- Learn such that when and
- Learn always (never forget)
- Cell state:
- When seeing"]", learn to decrement
Why this works:
The cell state is literally counting! The additive update enables this. A vanilla RNN with can't maintain an exact count because bounds values to .
Why it feels right: The name "forget gate" sounds like a switch.
The fix: Gates are continuous multipliers. means every dimension of gets scaled by 0.6—it's partial forgetting, not random erasure. The network learns smooth interpolations, not hard decisions. This continuity is why LSTMs can be trained with gradient descent.
Steel-man: This confusion arises because we want interpretability, and binary decisions are easier to reason about. But soft gates give the network flexibility to learn nuanced timing.
Why it feels right: Both carry information forward time.
The fix:
- is the unfiltered long-term memory (can be large, unrestricted)
- is the filtered output (bounded, task-relevant)
Example: When reading "John went to the store. He bought milk", the cell state might store [John, male, past-tense, store-context]. But when generating the next word after "He", the hidden state only exposes [male] (controlled by output gate) because that's what's needed for pronoun consistency.
Why this design? Separating storage () from exposure () lets the network keep rich internal state without forcing every detail into the output.
Why it feels right: We said LSTMs solve vanishing gradients and preserve long-term dependencies.
The fix: LSTMs can learn long dependencies if the data supports it, but they don't memorize perfectly. The forget gate is learned—if the training data doesn't require long-term memory, the network learns to forget. Also, cell states can still saturate or suffer from gradient issues with extremely long sequences (100k+ steps).
Practical limit: LSTMs handle dependencies of ~100-200 steps well. For longer, use attention mechanisms or Transformers.
Backpropagation Through Time in LSTMs
The key advantage: gradients flow through the cell state path with minimal degradation.
Gradient flow equation:
Why this matters: If forget gates average , after 100 steps:
Still small, but much better than vanilla RNN where:
Why this step? The forget gate values are learned, not fixed. The network can keep close to 1 for important memories, making much larger in practice.
Recall Explain LSTMs to a 12-Year-Old
Imagine your brain is trying to remember a story. A normal memory (like an RNN) is like telling the story over and over—each time, details get fuzy and you forget the beginning.
An LSTM is like having a notebook with smart sticky notes:
- The cell state () is your notebook where you write important facts
- The forget gate is a smart eraser—it only erases stuff you don't need anymore
- The input gate is a filter—it decides if new info is important enough to write down
- The output gate is a privacy filter—you have the memory, but you only share what's relevant right now
So if the story is "The wizard, who wore a purple hat, cast a spell", the LSTM:
- Writes "wizard, purple hat" in the notebook (input gate lets it in)
- Keeps "wizard" the whole time (forget gate says "don't erase")
- When the story asks "Who cast the spell?", the output gate shows "wizard" from the notebook
The notebook (cell state) has a straight path through time—info can flow back without getting corrupted. That's why LSTMs remember better than regular RNNs!
Order: FIO-C-O, where C (cell state) is the result of combining F and I, and O comes last.
Connections
- 3.5.01-Recurrent-Neural-Networks-(RNN)-basics: LSTMs extend RNNs with gated memory
- 3.5.02-Backpropagation-Through-Time-(BPTT): Why vanilla BPTT fails, LSTMs fix it
- 3.5.03-Vanishing-and-Exploding-Gradientsin-RNNs: The core problem LSTMs solve
- 3.5.05-Gated-Recurrent-Units-(GRU): Simplified alternative with2 gates instead of 3
- 3.5.06-Bidirectional-RNNs: LSTMs can be made bidirectional
- 3.6.01-Attention-Mechanisms: Modern alternative that handles even longer dependencies
- 4.2.01-Transformers: Replaced LSTMs for many NLP tasks
#flashcards/ai-ml
What problem do LSTMs solve that vanilla RNNs cannot? :: Vanishing gradients during long sequences—gradients shrink exponentially in RNNs but flow additively through LSTM cell states, preserving long-term dependencies.
What are the 3 gates in an LSTM?
Write the LSTM cell state update equation.
Why does the LSTM cell state use addition instead of multiplication?
What's the difference between cell state and hidden state ?
Why do LSTM gates use sigmoid activation?
How many parameter matrices does a standard LSTM have?
What happens if an LSTM's forget gate is always 1?
Why use for candidate cell state but sigmoid for gates?
What's the gradient flow advantage of LSTM over RNN?
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Dekho, LSTM ka core idea samajhna hai toh pehle problem samjho: simple RNN mein jab hum lambi sequence process karte hain aur backpropagation karte hain, toh gradients har time step pe multiply hote jaate hain. Agar yeh values 1 se choti hain toh gradient exponentially shrink ho jaata hai (vanishing gradient) aur network purani information bhool jaata hai. Matlab agar aapko sentence ke shuruaat ka context yaad rakhna hai toh RNN struggle karta hai. LSTM iss problem ko solve karta hai ek "cell state" introduce karke jo ek conveyor belt ki tarah time ke through smoothly bahta hai, aur teen smart gates (forget, input, output) decide karte hain ki kaunsi information rakhni hai, kaunsi hataani hai, aur kya output karna hai.
Ab yeh kyun kaam karta hai, yeh sabse important baat hai. Cell state ka update additive hai, multiplicative nahi — yaani . Iss additive nature ki wajah se backpropagation mein gradient ban jaata hai, jo ek "gradient highway" create karta hai. Agar forget gate open hai (yaani ), toh gradient bina shrink hue bahta rehta hai, aur purani information zinda rehti hai. Gates sigmoid use karte hain kyunki hume 0 se 1 ke beech values chahiye — 0 matlab poori tarah bhool jao, 1 matlab poori tarah yaad rakho.
Yeh matter isliye karta hai kyunki real world mein bahut saari cheezein sequences hain — language translation, speech recognition, stock prediction, text generation — jahan long-term context zaroori hota hai. LSTM ne yehi long-term dependency problem practically solve karke deep learning ki sequence modeling ki duniya kholi. Aaj ke bade models ke concepts bhi isi intuition pe khade hain, toh yeh gate aur cell state ka mechanism ache se samajhna aapke liye foundation ka kaam karega.