3.5.4Sequence Models

Long Short-Term Memory (LSTM) cells

2,823 words13 min readdifficulty · medium4 backlinks

The Vanishing Gradient Problem (Why We Need LSTMs)

In a standard RNN, hidden state ht=tanh(Whhht1+Wxhxt+bh)h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b_h). During backpropagation through time (BPTT), we compute:

Lhtk=Lhti=1khti+1hti\frac{\partial L}{\partial h_{t-k}} = \frac{\partial L}{\partial h_t} \prod_{i=1}^{k} \frac{\partial h_{t-i+1}}{\partial h_{t-i}}

Why this step? The chain rule forces us to multiply Jacobians across all time steps. Each Jacobian hti+1hti\frac{\partial h_{t-i+1}}{\partial h_{t-i}} contains WhhW_{hh} and the derivative of tanh\tanh, which is 1\leq 1.

If Whh<1||W_{hh}|| < 1, the product i=1kWhh\prod_{i=1}^{k} W_{hh} shrinks exponentially as kk grows (vanishing gradient). If Whh>1||W_{hh}|| > 1, it explodes. Either way, learning long-term dependencies becomes impossible.

The LSTM fix: The cell state CtC_t 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 xtx_t (current input vector)
  • Previous hidden state ht1h_{t-1}
  • Previous cell state Ct1C_{t-1}
  • Three gates: forget, input, output
  • Outputs: new cell state CtC_t and hidden state hth_t

Step 1: Forget Gate (What to Discard)

ft=σ(Wf[ht1,xt]+bf)f_t = \sigma(W_f \cdot [h_{t-1}, x_t] + b_f)

What: A vector in [0,1]nc[0, 1]^{n_c} where ncn_c is cell state dimension.

Why sigmoid? We want values between 0 (completely forget) and 1 (completely remember). Sigmoid σ(z)=11+ez\sigma(z) = \frac{1}{1 + e^{-z}} outputs this range.

How it works: ftf_t is element-wise multiplied with Ct1C_{t-1}. If ft[i]=0f_t[i] = 0, dimension ii of the cell state is erased. If ft[i]=1f_t[i] = 1, it's preserved.

Notation: [ht1,xt][h_{t-1}, x_t] means concatenating the two vectors: if ht1Rnhh_{t-1} \in \mathbb{R}^{n_h} and xtRnxx_t \in \mathbb{R}^{n_x}, then [ht1,xt]Rnh+nx[h_{t-1}, x_t] \in \mathbb{R}^{n_h + n_x}. The weight matrix WfRnc×(nh+nx)W_f \in \mathbb{R}^{n_c \times (n_h + n_x)}.

Step 2: Input Gate (What New Info to Store)

it=σ(Wi[ht1,xt]+bi)i_t = \sigma(W_i \cdot [h_{t-1}, x_t] + b_i) C~t=tanh(WC[ht1,xt]+bC)\tilde{C}_t = \tanh(W_C \cdot [h_{t-1}, x_t] + b_C)

What: iti_t is a gate vector in [0,1]nc[0, 1]^{n_c}; C~t\tilde{C}_t is a candidate cell state in [1,1]nc[-1, 1]^{n_c}.

Why two parts? We separate what to add (C~t\tilde{C}_t) from how much to add (iti_t). The candidate C~t\tilde{C}_t is computed using tanh\tanh (outputs [1,1][-1,1]) because cell states need signed values to represent both positive and negative information.

Why this step? Without the gate iti_t, 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)

Ct=ftCt1+itC~tC_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_t

Notation: \odot is element-wise (Hadamard) product.

Derivation from scratch:

  1. Start with old cell state Ct1C_{t-1}
  2. Multiply by forget gate: ftCt1f_t \odot C_{t-1} (keeps relevant memories)
  3. Compute what to add: itC~ti_t \odot \tilde{C}_t (new relevant info)
  4. Add them: Ct=ftCt1+itC~tC_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_t

Why this is brilliant: This update is additive, not multiplicative! During backpropagation:

CtCt1=ft\frac{\partial C_t}{\partial C_{t-1}} = f_t

The gradient flows through ftf_t without repeated matrix multiplications. If ft1f_t \approx 1 (forget gate open), gradients flow unchanged. This is the gradient highway that solves vanishing gradients.

Step 4: Output Gate (What to Expose)

ot=σ(Wo[ht1,xt]+bo)o_t = \sigma(W_o \cdot [h_{t-1}, x_t] + b_o) ht=ottanh(Ct)h_t = o_t \odot \tanh(C_t)

What: oto_t controls which parts of the cell state to expose as the hidden state hth_t.

Why tanh(Ct)\tanh(C_t)? Cell states can grow large over time. tanh\tanh squashes to [1,1][-1, 1] for stability.

Why not just ht=Cth_t = C_t? 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 x1,x2,,xTx_1, x_2, \ldots, x_T, initialize h0=0h_0 = 0, C0=0C_0 = 0. For t=1t = 1 to TT:

ft=σ(Wf[ht1,xt]+bf)it=σ(Wi[ht1,xt]+bi)C~t=tanh(WC[ht1,xt]+bC)Ct=ftCt1+itC~tot=σ(Wo[ht1,xt]+bo)ht=ottanh(Ct)\begin{align} f_t &= \sigma(W_f [h_{t-1}, x_t] + b_f) \tag{forget gate} \\ i_t &= \sigma(W_i [h_{t-1}, x_t] + b_i) \tag{input gate} \\ \tilde{C}_t &= \tanh(W_C [h_{t-1}, x_t] + b_C) \tag{candidate} \\ C_t &= f_t \odot C_{t-1} + i_t \odot \tilde{C}_t \tag{cell update} \\ o_t &= \sigma(W_o [h_{t-1}, x_t] + b_o) \tag{output gate} \\ h_t &= o_t \odot \tanh(C_t) \tag{hidden state} \end{align}

Parameter count: If nxn_x = input dim, nhn_h = hidden dim, ncn_c = cell dim (usually nc=nhn_c = n_h):

  • Each gate has weight matrix Rnh×(nh+nx)\mathbb{R}^{n_h \times (n_h + n_x)} and bias Rnh\mathbb{R}^{n_h}
  • 4 sets of parameters (forget, input, candidate, output)
  • Total: 4×[nh×(nh+nx)+nh]4 \times [n_h \times (n_h + n_x) + n_h] parameters

Comparison to vanilla RNN:

  • RNN: gradient multiplies by Whhdiag(tanh(ht1))W_{hh} \cdot \text{diag}(\tanh'(h_{t-1})) at each step → exponential decay
  • LSTM: gradient multiplies by ftf_t (values near 1) → linear flow, no exponential decay

The cell state acts as a gradient superhighway—if forget gates stay open (ft1f_t \approx 1), 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 iti_t opens, storing negation in CtC_t
  • Forget gate ftf_t 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):

  1. t=1t=1 ("not"): i1=0.9i_1 = 0.9, C~1=0.8\tilde{C}_1 = 0.8C1=0.72C_1 = 0.72 (store negation)
  2. t=2t=2 ("bad"): f2=0.95f_2 = 0.95, C2=0.95×0.72+=0.68C_2 = 0.95 \times 0.72 + \ldots = 0.68 (negation preserved)
  3. Output gate uses C2C_2 to predict positive sentiment

Why this step? The additive update C2=f2C1+C_2 = f_2 \odot C_1 + \ldots means C2C_2 directly depends on C1C_1 with minimal information loss, unlike RNN's h2=tanh(Wh1+)h_2 = \tanh(W h_1 + \ldots) which can erase h1h_1.

Sequence: x1=[,x2=[,x3=[,x4=[x5=],x_1=[, x_2=[, x_3=[, x_4=[ x_5=], \ldots

LSTM solution:

  • Learn WC,WiW_C, W_i such that C~t=+1\tilde{C}_t = +1 when xt=[x_t = [ and it=1i_t = 1
  • Learn ft=1f_t = 1 always (never forget)
  • Cell state: C1=1,C2=2,C3=3,C4=4,C_1 = 1, C_2 = 2, C_3 = 3, C_4 = 4, \ldots
  • When seeing"]", learn to decrement

Why this works: Ct=1Ct1+1(+1)=Ct1+1C_t = 1 \cdot C_{t-1} + 1 \cdot (+1) = C_{t-1} + 1

The cell state is literally counting! The additive update enables this. A vanilla RNN with ht=tanh(Wht1+)h_t = \tanh(W h_{t-1} + \ldots) can't maintain an exact count because tanh\tanh bounds values to [1,1][-1, 1].

Why it feels right: The name "forget gate" sounds like a switch.

The fix: Gates are continuous multipliers. ft=0.6f_t = 0.6 means every dimension of Ct1C_{t-1} 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:

  • CtC_t is the unfiltered long-term memory (can be large, unrestricted)
  • ht=ottanh(Ct)h_t = o_t \odot \tanh(C_t) 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 (CtC_t) from exposure (hth_t) 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 ftf_t 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: LCtk=LCti=tk+1tfi\frac{\partial L}{\partial C_{t-k}} = \frac{\partial L}{\partial C_t} \prod_{i=t-k+1}^{t} f_i

Why this matters: If forget gates average fi0.9f_i \approx 0.9, after 100 steps: i=11000.9=0.91002.7×105\prod_{i=1}^{100} 0.9 = 0.9^{100} \approx 2.7 \times 10^{-5}

Still small, but much better than vanilla RNN where: i=1100Whhtanh<0.251001060\prod_{i=1}^{100} ||W_{hh}|| \cdot |\tanh'|| < 0.25^{100} \approx 10^{-60}

Why this step? The forget gate values are learned, not fixed. The network can keep ftf_t close to 1 for important memories, making fi\prod f_i 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 (CtC_t) 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:

  1. Writes "wizard, purple hat" in the notebook (input gate lets it in)
  2. Keeps "wizard" the whole time (forget gate says "don't erase")
  3. 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

#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?
Forget gate ftf_t (what to discard), Input gate iti_t (what to add), Output gate oto_t (what to expose). All use sigmoid activation to output [0,1].
Write the LSTM cell state update equation.
Ct=ftCt1+itC~tC_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_t where C~t=tanh(WC[ht1,xt]+bC)\tilde{C}_t = \tanh(W_C [h_{t-1}, x_t] + b_C) is the candidate cell state.
Why does the LSTM cell state use addition instead of multiplication?
Additive updates create a gradient highway—CtCt1=ft\frac{\partial C_t}{\partial C_{t-1}} = f_t flows gradients with minimal decay, unlike RNN's multiplicative WhhW_{hh} chains.
What's the difference between cell state CtC_t and hidden state hth_t?
CtC_t is internal long-term memory (unbounded, flows additively). ht=ottanh(Ct)h_t = o_t \odot \tanh(C_t) is the filtered output (bounded to [-1,1], task-relevant).
Why do LSTM gates use sigmoid activation?
Sigmoid outputs [0,1], perfect for gates—0 = completely block, 1 = completely pass. This enables soft, differentiable decisions for gradient descent.
How many parameter matrices does a standard LSTM have?
4 weight matrices (Wf,Wi,WC,WoW_f, W_i, W_C, W_o) and 4 bias vectors, one set for each gate and the candidate cell state.
What happens if an LSTM's forget gate is always 1?
Perfect memory—Ct=Ct1+itC~tC_t = C_{t-1} + i_t \odot \tilde{C}_t, the cell state accumulates without forgetting. Gradients flow unchanged through all time steps.
Why use tanh\tanh for candidate cell state but sigmoid for gates?
tanh\tanh outputs signed values [-1,1] for representing positive/negative information. Sigmoid [0,1] for gates to control flow intensity.
What's the gradient flow advantage of LSTM over RNN?
RNN: Lhtki=1kWh\frac{\partial L}{\partial h_{t-k}} \propto \prod_{i=1}^k W_{h} (exponential decay). LSTM: LCtki=1kfi\frac{\partial L}{\partial C_{t-k}} \propto \prod_{i=1}^k f_i (values near 1, linear flow).

Concept Map

suffers from

multiplies Jacobians

motivates

introduces

uses additive updates

preserves

has

has

has

erases via sigmoid

scales candidate

adds new info to

filtered by

produces

Standard RNN

Vanishing Gradients

Backprop Through Time

LSTM Cell

Cell State C_t

Gradient Highways

Long-Term Dependencies

Forget Gate f_t

Input Gate i_t

Output Gate

Candidate C_t via tanh

Hidden State h_t

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 Ct=ftCt1+itC~tC_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_t. Iss additive nature ki wajah se backpropagation mein gradient CtCt1=ft\frac{\partial C_t}{\partial C_{t-1}} = f_t ban jaata hai, jo ek "gradient highway" create karta hai. Agar forget gate open hai (yaani ft1f_t \approx 1), 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.

Go deeper — visual, from zero

Test yourself — Sequence Models

Connections