A feedforward network sees each input in isolation — it has no memory. An RNN feeds its own output back as input at the next time step, so the hidden state carries information forward through a sequence. Same set of weights applied recursively. That single trick, weight sharing across time, let neural networks model language, speech, and stock prices for two decades, until transformers ate the world.
After this lesson, you will be able to:
See how looping connections give neural networks a form of memory for processing sequences
Understand the vanishing gradient problem — why vanilla RNNs forget things that happened long ago
Follow data through LSTM gates and see how the cell state acts as a long-term memory highway
Explain the role of each LSTM gate (forget, input, output) and why the cell state update avoids the vanishing gradient that plagues vanilla RNNs
The first word of the sequence enters the RNN. Raw text must first be converted to numbers — the word "The" is mapped to an integer index (e.g., 42) from the vocabulary. This index will be converted to a dense vector in the next step.
The word index is looked up in an embedding matrix, producing a dense vector (e.g., 256 dimensions). This embedding captures semantic meaning — similar words have similar vectors. "The" might map to [0.12, -0.34, 0.56, ...]. The embedding is learned during training.
The embedding vector is combined with the initial hidden state (typically zeros) to produce the first hidden state: h0 = tanh(W_xh * x0 + W_hh * h_init + b). This hidden state is the RNN's "memory" — a fixed-size summary of everything processed so far (just one word at this point).
The second word "cat" enters the RNN. It goes through the same embedding lookup, producing another dense vector. The RNN will now combine this new input with its existing memory (h0) to update its understanding of the sequence.
The new hidden state is computed: h1 = tanh(W_xh * x1 + W_hh * h0 + b). The SAME weight matrices W_xh and W_hh are reused at every time step — this weight sharing is what allows the RNN to handle sequences of any length. h1 now encodes information about both "The" and "cat."
Each subsequent word updates the hidden state in the same way: h_t = tanh(W_xh * x_t + W_hh * h_(t-1) + b). The hidden state accumulates information about the entire sequence seen so far. For "The cat sat on the", h4 encodes the full phrase context.
At each time step, an output can be produced: y_t = W_hy * h_t + b_y. For language modeling, this predicts the next word. For classification, typically only the final hidden state is used. For sequence-to-sequence tasks, outputs at every step form the translated or generated sequence.
RNNs are a beautiful idea: give a neural network a loop so it can remember. Even though transformers have taken over most tasks, understanding RNNs gives you deep intuition about sequence processing that carries forward to everything else. Plus, LSTMs are still used in production for real-time and edge applications — this is not just history.
The hidden state h_t is the RNN's memory — a fixed-size vector that summarizes everything the network has seen so far. The same weights are shared across all time steps, so the network can handle sequences of any length.
The number of weights follows from the shapes of the three arrays, so you can size a model before you build it. Open the derivation to count them.
Try it! Write out a simple 3-word sequence. Start with h_0 = [0, 0]. At each step, pick small random weights and compute tanh(W_xh * x_t + W_hh * h_{t-1}). Watch how h changes with each word — that evolving vector IS the RNN's memory.
Try it: Feed a sequence and watch the hidden state evolve at each time stepInteractive
Loading visualization...
Try it: Watch LSTM gates open and close as words flow throughInteractive
Loading visualization...
Step through each word in the sequence and observe the forget, input, and output gate values. Notice how the forget gate stays high when context needs to be preserved and drops when the topic shifts. The cell state line shows how information accumulates over time while the hidden state reveals what the LSTM exposes to downstream layers.
Try this: Observe how recurrent connections create a loop from a layer's output back to its own input. When "unrolled" through time, this loop becomes a very deep chain, which is why gradients can vanish or explode across long sequences.
What Do You Think?
If you unroll an RNN processing a 100-word sentence, how many layers deep is the unrolled network for backpropagation?
When unrolled through time, an RNN processing a 100-step sequence becomes effectively a 100-layer network. Gradients must flow backward through all 100 steps, and this is where the trouble begins.
Training moves W_hh to reduce the total loss, which is the sum of the losses at every step, L = L_1 + L_2 + ... + L_T. Because the same W_hh is used at every step, its gradient collects a contribution from every step. The chain rule through a computation graph is derived in Computational Graphs & Autograd, and its matrix form with Jacobians is derived in Vector & Matrix Calculus: Jacobian, Hessian & Backprop Rules. Here we only add what is new, the time structure.
The plus sign in the last factor marks the immediate derivative: how h_k changes when W_hh changes while h_(k-1) is held fixed. The earlier copies of W_hh are accounted for by the other values of k. First the one-step Jacobian, then the sum.
The product is where the trouble comes from. A product of many matrices can shrink to nothing or grow without limit, and the size of W_hh decides which. The derivation below turns that into an exact bound.
Slide the weight scale across 1 and compare the measured gradient with the predicted line, then switch to the linear RNN to watch it explode and lower the clip threshold to see where clipping would act.
The same product can also grow, and one huge gradient can throw the weights far from where they were. The standard guard is norm clipping: when the length of the gradient passes a threshold c, shrink the whole gradient to length c and keep its direction. It helps with exploding gradients only. Vanishing gradients need a different architecture, which is the LSTM below.
The LSTM solves the vanishing gradient problem with a cell state — a highway that carries information across time steps with minimal interference. The cell state is protected by gates that control what information to add, keep, or remove.
The cell state C_t runs along the top of the LSTM like a conveyor belt. Information can flow along it with only minor linear operations (element-wise multiplication and addition). No matrix multiplication, no tanh — just gating. This is why gradients can flow through the cell state without vanishing.
f_t = sigmoid(W_f * [h_(t-1), x_t] + b_f). The forget gate looks at the previous hidden state and current input, and outputs a value between 0 and 1 for each cell state element. A value near 0 means "forget this information." A value near 1 means "keep it." When processing a new sentence, the forget gate might erase the subject of the previous sentence from the cell state.
i_t = sigmoid(W_i * [h_(t-1), x_t] + b_i) — decides WHICH cells to update. C_tilde = tanh(W_C * [h_(t-1), x_t] + b_C) — computes candidate NEW values. The input gate filters the candidates: only information the gate deems important gets written to the cell state.
C_t = f_t * C_(t-1) + i_t * C_tilde. The old cell state is multiplied by the forget gate (erasing unwanted info), then the new candidate values (filtered by the input gate) are added. This is an element-wise operation, not a matrix multiplication — crucial for gradient flow.
o_t = sigmoid(W_o * [h_(t-1), x_t] + b_o). The cell state contains the full memory, but the output gate decides what part of that memory to expose as the hidden state h_t = o_t * tanh(C_t). The cell state might remember the subject of a sentence, but the output gate reveals it only when it is relevant (e.g., when predicting a verb).
During backpropagation, the gradient through the cell state is: dL/dC_(t-1) = dL/dC_t * f_t. The forget gate f_t is a number between 0 and 1 — typically close to 1 for important information. This means the gradient is multiplied by ~1 at each step, not by a weight matrix. After 100 steps, the gradient is 1^100 = 1, not 0.25^100 = 10^-60.
The Gated Recurrent Unit (GRU) merges the forget and input gates into a single update gate, and merges the cell state and hidden state. The result: fewer parameters, similar performance.
Recurrent connections give neural networks memory. By feeding the hidden state from one time step into the next, RNNs can process sequences of variable length while maintaining context
Vanilla RNNs suffer from vanishing gradients over long sequences. During backpropagation through time, gradients shrink exponentially, making it impossible to learn dependencies more than 10-20 steps apart
LSTMs solve the long-range dependency problem with gated memory. The forget gate, input gate, and output gate control information flow through a cell state that can preserve information across hundreds of time steps
Transformers have largely replaced RNNs for most sequence tasks. Self-attention processes all positions in parallel (vs. RNNs' sequential processing), enabling faster training and better long-range dependency modeling
Why do vanilla RNNs struggle with long-range dependencies?
You now understand how recurrent networks process sequences with memory. Next: LSTM, GRU & Seq2Seq, the gated cells that fix the vanishing gradient, and the encoder-decoder shape built from them.