CS 460G · Week 12 → Lecture 3 · Fall 2026

Recurrent Neural Networks

From “a network needs a fixed-size input” to a character-level language model that writes “hello” one letter at a time. Every formula on this page is real LaTeX, rendered in your browser — not a screenshot of an equation.

55 slides4 interactive widgetsAll formulas in LaTeX Prof. Abdullah-Al-Zubaer Imran
First time here? Start with the picture-first version — same lecture, no algebra, one idea per screen. Come back here for the shapes and the formulas.
1
state vector ht
3
weight matrices, shared
O(T)
memory for BPTT
4
characters in the demo vocab
One sentence: an RNN is a function that keeps a running summary of everything it has read so far, and updates that summary one element at a time using the same weights at every step — so the network can accept an input of any length and still produce something on the other side.

0Orientation in 60 seconds

QuestionAnswerWhere
What problem does an RNN solve?Data where order matters and length varies: sentences, audio, video frames.Part 2
What is the actual mechanism?One hidden vector $\mathbf{h}_t$ updated from the previous $\mathbf{h}_{t-1}$ and the current input $\mathbf{x}_t$.Part 3
Why does it not blow up in parameters?The same three matrices are reused at every timestep (weight sharing).Part 4
How is it trained?Forward over the whole sequence, then backward over the whole sequence: BPTT.Part 7
What goes wrong?Long sequences make the backward pass slow, memory-hungry, and prone to vanishing/exploding gradients.Part 7
What comes next?GRU and LSTM — gates that decide what to forget (W13L1).Part 8

1Recap: segmentation, detection, and the numbers that grade them

The first ten slides are revision from W12L2 — convolutional networks applied to images. Two ideas from that half come back later, so they are worth pinning down here: a metric that is not accuracy, and normalisation.

1.1 Segmentation is a partition, not a label

Segmentation takes the whole spatial region $R$ of an image and cuts it into $n$ pieces. The definition on the slide is the mathematical one, and it is worth reading slowly because it says exactly what a segmentation must satisfy:

Definition · slide 3
R = \bigcup_{k=1}^{n} R_k, \qquad R_i \cap R_j = \varnothing \quad (i \neq j)
Q(R_k) = \text{TRUE}

Read it in three pieces: the pieces cover everything (the union is the whole image — no pixel left behind), the pieces do not overlap (every pixel gets exactly one label), and every piece passes a predicate $Q$ — the rule that says “all pixels in this region belong to the same thing”. A segmentation that leaves a pixel unassigned, or gives it two labels, is not a segmentation; it is a bug with a colour map.

Slide 3
Slide 3. The original region $R$ on the left, the segmented version on the right, with $R_1 \ldots R_6$ partitioning the plane. tap to open full size

1.2 U-Net: down, then up, with a shortcut

U-Net is the standard answer to “classify every pixel”. It has two halves: a contracting path (encoder) that repeatedly shrinks the image and extracts coarser features, and an expanding path (decoder) that grows it back to full resolution. The trick that makes the output sharp is the skip connection: at each level, the high-resolution features from the encoder are concatenated straight into the decoder, so the fine detail never has to survive the bottleneck.

Slide 6
Slide 6. The U-Net diagram: contracting path on the left, bottleneck at the bottom, expanding path on the right, grey arrows for skip connections. tap to open full size

1.3 Dice: the metric that survives class imbalance

If 98% of an image is background, a model that predicts “background” everywhere scores 98% accuracy and is useless. Dice ignores the true negatives entirely and only asks about the overlap between prediction $P$ and ground truth $G$:

Dice coefficient · slide 7
\mathrm{Dice}(P,G) \;=\; \frac{|P \cap G|}{\tfrac{1}{2}\big(|P|+|G|\big)} \;=\; \frac{2\,|P \cap G|}{|P|+|G|}
=\; \frac{2\,\mathrm{TP}}{2\,\mathrm{TP}+\mathrm{FP}+\mathrm{FN}}

All three forms are the same number. The first says “intersection over the average size” — which is where the factor 2 comes from. The third is the one you compute from a confusion matrix. It runs from 0 (no overlap) to 1 (perfect), and it equals the F1 score of the positive class — worth remembering, because the slide calls it “intersection over average” and never says F1.

Slide 7
Slide 7. The same formula three ways, with the Venn diagram that defines TP, FP and FN for a segmentation mask. tap to open full size

1.4 Detection: a box plus a class, and three metrics

Object detection outputs a bounding box $(x, y, w, h)$ and a class distribution for every object. On the slide, one branch of the network predicts class scores and another predicts four box coordinates.

The three detection metrics · slide 9
\mathrm{IoU} = \frac{|P \cap G|}{|P \cup G|}
\text{Precision} = \frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FP}}
\text{Recall} = \frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FN}}
\mathrm{AP} = \int_0^1 p(r)\,\mathrm{d}r \;\approx\; \sum_{n} \big(r_{n+1}-r_n\big)\, p_{\text{interp}}(r_{n+1})

IoU is the overlap divided by the union — 1.0 means the boxes coincide exactly, and a prediction is usually counted correct above a threshold such as 0.5. AP is the area under the precision–recall curve; mAP is that area averaged over classes. Note the asymmetry: IoU is used to decide whether a detection counts, while AP is used to summarise the whole ranking.

Slide 8
Slide 8. One network, two heads: 4096 → 1000 class scores on top, 4096 → 4 box coordinates below. tap to open full size

1.5 Normalisation: four letters, one question

All four methods do the same arithmetic — subtract a mean, divide by a standard deviation — and differ only in which set of numbers the mean is taken over:

Batch normalisation · slide 10
\hat{x}^{(k)} = \frac{x^{(k)}-\mu_B^{(k)}}{\sqrt{\big(\sigma_B^{(k)}\big)^2+\epsilon}}, \qquad y^{(k)} = \gamma^{(k)}\hat{x}^{(k)} + \beta^{(k)}
MethodStatistics computed overBest when
Batch normthe mini-batch, per channellarge batches, CNNs
Layer normall features of one samplesequences, small batches
Instance normone sample, one channelstyle transfer
Group normone sample, a group of channelssmall batches, detection

$\gamma$ and $\beta$ are learned, so the network can undo the normalisation if it wants to — that is the part people forget. Normalisation does not remove information; it re-scales it and then learns the scale back.

2Why sequences break everything you just built

A fully connected network takes a vector of fixed size. A CNN takes an image of fixed height and width. Both are fine until the data is a sentence — because the third word of a sentence has no meaning without the two before it, and because not every sentence has the same number of words.

The deck names three properties that make sequence data different:

The three properties · slides 19–23
\underbrace{\text{order matters}}_{\text{dog bites man} \;\neq\; \text{man bites dog}}
\underbrace{\text{temporal relation}}_{\text{frame } t \text{ depends on } t-1}
\underbrace{\text{variable length}}_{|x| \text{ is not fixed}}

Formally, a sequence is a list of vectors $\mathbf{x}^{(1)}, \mathbf{x}^{(2)}, \ldots, \mathbf{x}^{(T)}$ where $T$ changes from example to example. A batch is therefore a set of sequences of different lengths — which is already awkward for any framework that expects a rectangular tensor.

Slide 16
Slide 16. The data model: a sequence of vectors $\mathbf{x}^{(t)}$, a batch of such sequences with different lengths, and a label that can itself be a sequence. tap to open full size

And the failure is not hypothetical. For video captioning the input is $T$ frames — a number that changes with the clip — and the output is a caption whose length also changes. A CNN can encode a frame; it cannot emit a variable-length sentence.

Slide 30
Slide 30. The reason RNNs exist, stated as a limitation: variable-length input, variable-length output, and a CNN that can do neither. tap to open full size
The intuition to keep A feed-forward network is a photograph: everything it will ever see is in the frame at once. An RNN is a reader: it moves along the text, and what it understands at word 9 depends on what it remembers from words 1–8. The memory is the whole trick — and the whole problem, because a memory has to be carried, updated, and eventually back-propagated through.

3The recurrence: one line that does everything

Here is the entire idea of the lecture, in one equation:

The recurrence · slide 35
\mathbf{h}_t = f_W\big(\mathbf{h}_{t-1},\, \mathbf{x}_t\big)

Read it as a sentence: the new state is some function of the previous state and the current input, and the function has parameters $W$. Nothing says what $f_W$ is yet — that is the next section. What matters here is the shape of the dependency: to compute step $t$ you need step $t-1$, and to compute $t-1$ you needed $t-2$. Unroll it and the same cell appears over and over:

h₀ RNN RNN RNN x₁ x₂ x₃ y₁ y₂ y₃ same weights in all 3 cells
Unrolled for $T = 3$. The loop on the right of a textbook RNN diagram is this picture with the cells folded onto each other.

Three consequences fall out immediately, and all three are exam material:

  1. Any length works. You can run the same cell for 3 steps or 300. The number of parameters does not change.
  2. The parameters are shared. There is one $W_{hh}$, one $W_{xh}$, one $W_{hy}$ — not one set per position.
  3. The state is the only channel for the past. Everything the network knows about $\mathbf{x}_1$ must fit inside $\mathbf{h}_1$ and survive every update after that.
The claim students get wrong “An RNN has a memory of the whole sequence.” It has a memory of fixed size — the vector $\mathbf{h}_t$ has $H$ numbers whether the sentence is 3 words or 300. The past is not stored; it is compressed, and compression loses things. That is exactly why GRU and LSTM exist.

4Inside the cell: two matrices in, one matrix out

The general $f_W$ is made concrete with a linear layer and a $\tanh$:

Simple RNN · slides 36 and 38
\mathbf{h}_t = \tanh\!\Big(W_{hh}\,\mathbf{h}_{t-1} + W_{xh}\,\mathbf{x}_t\Big)
\mathbf{y}_t = W_{hy}\,\mathbf{h}_t

Three matrices, three different jobs. The one that surprises people is $W_{hh}$: it multiplies the previous hidden state, so it is the part of the network that decides how much of the past to carry forward. Set it near zero and the network forgets instantly; make it large and the state saturates.

MatrixShapeMultipliesJob
$W_{xh}$$H \times D$input $\mathbf{x}_t$lift a $D$-dim input into the $H$-dim state space
$W_{hh}$$H \times H$previous state $\mathbf{h}_{t-1}$decide how the past carries forward
$W_{hy}$$K \times H$current state $\mathbf{h}_t$read a $K$-dim prediction out of the state

Count the parameters and the reason for weight sharing becomes obvious:

Parameter count
|W| \;=\; \underbrace{H^2}_{W_{hh}} \;+\; \underbrace{HD}_{W_{xh}} \;+\; \underbrace{KH}_{W_{hy}} \;+\; \underbrace{H + K}_{\text{biases}}
\text{unshared, length } T:\quad T\big(H^2 + HD + KH\big)

🧮 Widget 1 — how many parameters does that cost?

Drag the three dimensions. The right-hand column is what a per-timestep (unshared) version would cost.

…

4.1 Why tanh and not sigmoid or ReLU

The slide lists four requirements for the activation: non-linear, easy to compute, differentiable, bounded output. $\tanh$ hits all four, and the bound is the interesting one — it keeps the state from growing without limit as the sequence gets longer.

Tanh and its derivative
\tanh(z) = \frac{e^{z}-e^{-z}}{e^{z}+e^{-z}}
\frac{\mathrm{d}}{\mathrm{d}z}\tanh(z) = 1-\tanh^2(z)

That derivative is the whole story of Part 7. It is largest at $z=0$ (value 1) and vanishes as $|z|$ grows: once a unit is saturated, it stops passing gradient back.

📈 Widget 2 — tanh and the derivative that will haunt the backward pass

Slide the input value. Watch the derivative collapse to zero outside roughly ±3.

…
Slide 37
Slide 37. The four properties the activation has to satisfy, and the tanh curve itself. tap to open full size

5Five topologies, one cell

Because $\mathbf{x}$, $\mathbf{h}$ and $\mathbf{y}$ are independent — you can feed one input or many, read one output or many — the same cell covers every standard task shape. The deck shows four:

one → many image → caption many → one video → action many → many frame → label, every step one → one plain classifier The asymmetry nobody mentions: “many → many” is drawn twice in the deck, and the two pictures are different. On slide 28 the output comes after the input has been read (encoder–decoder). On slide 29 it comes at the same time as each input (per-frame labelling). Same label, two architectures.
Slide 28
Slide 28. Many-to-many, the encoder–decoder reading: a whole video goes in, a caption comes out after the last frame. tap to open full size
Slide 29
Slide 29. Many-to-many, the per-timestep reading: an output at every frame. This one is what the “hello” model below actually does. tap to open full size

6“hello”: a character-level language model

This is the smallest complete RNN in the deck, and it is worth tracing end to end because every part of the machinery appears exactly once.

The data. Train on the string "hello", with vocabulary $V \in \{\texttt{h}, \texttt{e}, \texttt{l}, \texttt{o}\}$ — four symbols, so $D = K = 4$. The task is always the same: given the characters so far, predict the next one.

tinput xttarget ytwhat the model must learn
1heafter "h", the only sensible continuation is e
2elafter "he", l
3llafter "hel", l again
4loafter "hell", o — the same input as step 3, a different target

That last row is the reason this is an RNN problem and not a lookup table. The input l appears at steps 3 and 4 and must produce l in one case and o in the other. A feed-forward network seeing only the current character cannot tell them apart. The hidden state can, because at step 4 it also knows that a l has already happened.

From state to a probability over characters
\mathbf{z}_t = W_{hy}\,\mathbf{h}_t
\hat{y}_{t,k} = \frac{\exp(z_{t,k})}{\sum_{j=1}^{K}\exp(z_{t,j})}, \qquad L_t = -\log \hat{y}_{t,\,c_t}
L = \sum_{t=1}^{T} L_t \quad\text{or}\quad L = \frac{1}{T}\sum_{t=1}^{T} L_t

The softmax turns four raw scores into a probability distribution; the loss is the negative log of the probability assigned to the correct next character. This is exactly the softmax classifier from the earlier lectures, applied once per timestep — and the total loss is those per-step losses added up.

🔤 Widget 3 — unroll a word, one character at a time

Type a word (≤ 8 letters) and step through it. This shows the data flow and tensor shapes — the weights are not trained, so it deliberately does not pretend to predict anything.

…
Slide 46
Slide 46. The full unrolled training graph for “hello”, with the per-step predictions on top and the vocabulary $\{h,e,l,o\}$ at the bottom. tap to open full size

6.1 Training is not sampling

These two loops are constantly confused, and the deck puts them side by side for that reason:

TrainingSampling (test time)
input at step tthe real character from the training stringthe character the model just predicted
what you compareprediction vs the real next characternothing — there is no label
when it stopsafter $T$ stepswhen you decide (a length, or an end token)
error behaviourone bad step does not poison the next, because the truth is fed inone bad step is the next input — errors compound
The trap in the “hello” example With four symbols and one training word, the model can memorise the string perfectly and still be useless. A character-level model is only interesting at the scale where it must generalise across words — which is why the lab uses a real corpus, not one word.

7BPTT: backpropagating through your own history

Because the same weights are used at every step, the gradient of the loss with respect to those weights is a sum over all timesteps:

Backpropagation through time · slide 48
\frac{\partial L}{\partial W} \;=\; \sum_{t=1}^{T} \frac{\partial L_t}{\partial W}

And each of those terms has to travel back through every state between the step where the weight was used and the step where the loss was measured. Applying the chain rule along the chain of states:

Why long sequences hurt
\frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_{t-1}} = \operatorname{diag}\!\big(1-\tanh^2(\cdot)\big)\,W_{hh}
\mathcal{J}_{k \to t} \;=\; \prod_{j=k+1}^{t} \frac{\partial \mathbf{h}_j}{\partial \mathbf{h}_{j-1}}
\frac{\partial L}{\partial W} = \sum_{t}\sum_{k \le t} \frac{\partial L_t}{\partial \mathbf{h}_t}\, \mathcal{J}_{k \to t}\, \frac{\partial \mathbf{h}_k}{\partial W}

where $\mathcal{J}_{k \to t}$ is the product of Jacobians that carries a signal from step $k$ all the way to step $t$. Look at that product. Every extra timestep multiplies the gradient by one more Jacobian. If each factor is slightly below 1, the product decays exponentially — the vanishing gradient. If each is slightly above 1, it explodes. Neither is a bug in the code; both are arithmetic.

📉 Widget 4 — what “long sequence” actually costs

Schematic, not a trained model: assumes each timestep multiplies the gradient by a fixed factor $r$. The point is the exponent, not the exact curve.

…

That is the learning problem. There is also a mechanical problem: to compute the backward pass you must keep every intermediate state from the forward pass alive, so memory grows linearly with sequence length, and the whole sequence must be processed before a single weight update. The slide's own annotation says it plainly — “slow and memory intensive, hardly converge.”

Slide 49
Slide 49. The red double-headed arrow spans the entire sequence: the backward pass touches every step. The annotation in the corner is the verdict. tap to open full size

7.1 Truncated BPTT: cut the graph, keep the state

The fix is not to forget the past — it is to stop differentiating through all of it. Run forward and backward over chunks of length $\tau$ (typically 10–100 steps). Between chunks, the hidden state keeps its value but the computational graph is severed, so no gradient flows across the boundary.

Truncated BPTT
\text{chunks of length } \tau:\qquad \frac{\partial L}{\partial W} \;\approx\; \sum_{\text{chunk}}\ \sum_{t \in \text{chunk}} \frac{\partial L_t}{\partial W}
\mathbf{h}\ \text{is carried across chunks; the gradient is not}
Full BPTTTruncated BPTT
memory$O(T)$ — every state kept$O(\tau)$ — only the current chunk
gradientexact (for the whole sequence)biased: dependencies longer than $\tau$ are invisible to the gradient
statecarriedstill carried — the forward memory survives
cost per stepgrows with $T$constant in $\tau$

The sentence to remember: truncation limits what the model can learn from, not what it can remember. The hidden state still contains information from the beginning of the sequence; the gradient simply stops being able to assign credit that far back.

8Stacking, and what comes next

An RNN layer outputs a sequence of states, so you can feed that sequence straight into another RNN layer. Depth helps empirically, exactly as it does in CNNs — the lower layer learns short-range patterns, the upper layer learns longer-range ones.

Slide 51
Slide 51. Multilayer RNN: the output sequence of layer 1 becomes the input sequence of layer 2. tap to open full size

Next lecture (W13L1) picks up exactly where this one stops: GRU and LSTM. Both are the same recurrence with a gate added, and both exist because of the product of Jacobians in Part 7 — a gate is a learned way of deciding which factors in that product should be near 1 and which should be near 0.

9Cheat sheet

  1. Sequence data = order matters + variable length. Fixed-size nets cannot take it.
  2. $\mathbf{h}_t = f_W(\mathbf{h}_{t-1}, \mathbf{x}_t)$ — one state, updated every step.
  3. Simple RNN: $\mathbf{h}_t = \tanh(W_{hh}\mathbf{h}_{t-1} + W_{xh}\mathbf{x}_t)$, then $\mathbf{y}_t = W_{hy}\mathbf{h}_t$.
  4. Parameters: $H^2 + HD + KH$ (+ biases), independent of sequence length.
  5. tanh: bounded, differentiable, and its derivative $1-\tanh^2$ is the source of vanishing gradients.
  6. Four topologies: one→many, many→one, many→many (aligned), many→many (encoder–decoder).
  7. Character LM: one-hot input, softmax over the vocabulary, cross-entropy per step, summed over $T$.
  8. Training feeds the true previous character; sampling feeds the model's own prediction.
  9. BPTT: $\partial L/\partial W = \sum_t \partial L_t/\partial W$, with a Jacobian product across time.
  10. Truncated BPTT: chunk length $\tau$; state carried, gradient cut.
  11. Dice $=2|P\cap G|/(|P|+|G|)$; IoU $=|P\cap G|/|P\cup G|$; AP is the area under precision–recall.

Exam traps, collected

WrongRight
“The RNN stores the whole sequence.”It stores a fixed-size summary $\mathbf{h}_t$; the past is compressed, not kept.
“Each timestep has its own weights.”One set of weights, reused $T$ times. That is why the parameter count has no $T$ in it.
“Dice and IoU are the same.”Dice $=2\mathrm{IoU}/(1+\mathrm{IoU})$. They rank identically but are not numerically equal.
“Vanishing gradients are a coding bug.”They follow from multiplying many Jacobians $\lt 1$. Truncation and gates are the fixes.
“Truncated BPTT forgets the past.”It keeps the state; it only cuts the gradient at the chunk boundary.
“Many-to-many is one architecture.”The deck draws two: aligned (output every step) and encoder–decoder (output after reading).

All 55 slides, in order

Tap any thumbnail to open it full size. The ones that carry the argument are also placed inline above, next to the explanation they belong to.