RNN & backprop through time
This lecture processes ordered data with a recurrent network. It shares one set of weights across time steps and trains them with backprop through time. After this page you can run a two-step RNN forward pass by hand and trace one BPTT gradient.
Sequence learningSearch on YouTube
Feedforward networks and CNNs take fixed-size inputs. They treat every input as independent of the others. Sequence tasks break both rules. Length varies from sample to sample. Order changes the meaning.
The slides show auto word prediction. Feed d into the network and it predicts e. Feed that e back in and it predicts the next letter. Each prediction depends on the letters seen before.
Two more slide tasks work the same way. POS tagging assigns one tag to each word in order. Polarity scoring reads a whole review and outputs one label.
A sentence is a queue, not a bag of coins. Shuffle the words and the total stays the same, but the meaning breaks.
Sequence learning covers problems with ordered, variable-length input. Temporal dependence means the current input needs the past inputs for its meaning. Speech, text, sensor traces and video are natural examples.
Challenges in sequence learningSearch on YouTube
Three demands separate sequence learning from standard learning:
- Variable-length inputs. Sentences and traces have different lengths. The model must accept any length.
- Temporal dependencies. The meaning of the current input depends on previous elements.
notflips thegoodthat follows it. - Same function at each time step. The model must reuse one parameter set for every time step . Sharing cuts the parameter count and helps the model generalize across time.
Failed alternativesSearch on YouTube
Two naive designs fail before the RNN appears.
First, reuse one fixed network per element with no memory. It accepts any length. It keeps no dependency on previous inputs. Each step sees only the current element.
Second, train separate weights for each position. Position 1 gets one matrix, position 2 another, and so on. The parameter count grows with length. Computation grows with it. Long sentences become untrainable.
| Approach | Any length | Keeps history | Parameter cost |
|---|---|---|---|
| Fixed net, no memory | yes | no | small |
| One net per position | no | yes | grows with length |
| RNN with shared weights | yes | yes | fixed |
S0, S1 and S2 solutionSearch on YouTube
The slides build the fix from states. Keep a state that summarizes the past. Update it at each step. Read the output from it.
The chain runs . Each new state combines the current input with the previous state. The output at each step reads the current state. This is the recurrent solution. The next section names the pieces.
Recurrent neural networkSearch on YouTube
An RNN processes a sequence one element at a time. It keeps a hidden state that carries past information forward. The hidden state (the slides also call it state ) updates at every step with the same weights.
is the hidden state at step . is the input at step . maps inputs to the hidden state. maps the previous hidden state to the current one. is the bias. is the hidden activation function.
is the predicted value at step ( is the label). maps the hidden state to the output. is the output bias. is the output activation function: softmax, sigmoid or linear.
The same , , , and serve every step. Sharing is what keeps the model small. The hidden state is the only thing that changes with time.
Training a recurrent networkSearch on YouTube
Training follows three steps. They mirror feedforward training, with time added.
- Run the forward pass. Feed the sequence step by step. Update the hidden state and emit outputs.
- Compute the loss. Compare each prediction with its label. Add the per-step losses into one total.
- Run backprop through time. Send gradients back across steps. Add them and update the weights.
Outputs appear at each step or only at the final step. Tagging needs one output per step. Polarity needs only the last one.
is the total loss over a sequence of length . is the loss at step . All learnable parameters sit in plus biases.
Use squared error for real-valued targets. Use cross entropy for class targets. pairs with the loss: linear with squared error, sigmoid with binary labels, softmax with cross entropy.
Worked example. Scalar toy RNN, two steps. Weights , , , biases . Inputs , . Start state . Hidden and output activations are sigmoid.
Step 1. .
Step 2. .
Check. , , . Recompute each quotient and the digits match.
Backprop through timeSearch on YouTube
BPTT is backprop unrolled over time. It computes one gradient per step and adds them. Shared weights collect their updates from all steps.
Time order controls the chain rule. depends on twice over. The direct path is the term inside . The indirect path runs through , which itself used . The same split holds for .
Each step contributes its own gradient. Shared weights sum them. is a constant, so its derivative is .
The explicit part is the direct use of at step . The implicit part is the product chain back through . The gradient reuses the same chain with in place of .
The term is the explicit component. Terms with are implicit components. They trace back to . The term drops out because is constant.
Trace one at a time in exams. Write the output path first. Then expand one explicit term plus one implicit chain. Examiners award marks for the split.
Worked example. BPTT trace for with the toy numbers above. Loss with label and .
Output path. Error signal times sigmoid slope.
Hidden path. Sigmoid slopes: .
Combine. Implicit term dies on . Only the explicit term at stays.
Check. . Then . Then . Signs stay negative, so gradient descent raises .
The lab replays the two-step scalar RNN from the worked example. It then traces the BPTT chain and the clip plus truncate fixes.
Unrolled toy RNN. U, W and V stay shared across steps.
a2 = 0.3 + 0.5166 = 0.8166. h2 = 0.6935. y-hat = 0.6668.
0.25^5 = 0.0010 (0.25^5 is about 0.001). Signal vanishes.
Norm is 12. Scale is 0.4167. Clipped norm is 5.0.
k = 2 keeps steps 6 to 7. Older links stay unlearned.
Vanishing and exploding gradientsSearch on YouTube
The implicit chain multiplies many derivatives. Each factor is a Jacobian . Long products misbehave in two ways.
Vanishing means gradients shrink step by step. Early steps barely update. Learning stalls. Sigmoid slopes peak at . Tanh slopes peak at . Products of such factors decay fast.
Exploding means gradients grow step by step. Weights blow up. Training turns unstable. Factors above compound the same way in reverse.
One factor per step back. for sigmoid and for tanh. With the product shrinks toward . With it can grow fast.
Saturation adds to the damage. Large makes the sigmoid switch too fast. Large shifts it left or right into a flat end. Flat ends have near-zero slope, so gradients vanish there too.
| Vanishing | Exploding |
|---|---|
| Gradients shrink toward 0 | Gradients grow out of control |
| Early steps stop learning | Weights blow up, loss jumps |
| Caused by slopes below 1, saturation | Caused by factors above 1 |
| Fix: truncate history, gate memory | Fix: clip gradients |
Fixes: clipping and truncated BPTTSearch on YouTube
The slides name three fixes. The first two belong here. The third is a later lecture.
Gradient clipping caps exploding steps. Pick a ceiling such as or . Rescale any gradient above it. Direction stays the same. Size stops at .
Truncated BPTT caps the history length. Backpropagate only steps. A 100-word sequence might train on the last 20 steps. Long-range links beyond go unlearned. Cost per update stays flat.
LSTM adds a memory cell for long-range links. It is the topic of the next lecture.
is the gradient vector. is its norm. is the ceiling. Gradients below pass through unchanged.
C-T-L: Clip, Truncate, LSTM
Clip caps gradient size · Truncate caps history length · LSTM (next lecture) carries long memory.
Truncate with care on exams. A small speeds training but erases links longer than . Name the trade-off when you recommend it.
Bag of words for text classificationSearch on YouTube
The classic pipeline ignores order. Tokenize the text. Build a vocabulary with one index per word. Count words per document into a design matrix. Feed the matrix to a plain classifier.
Each row is one document. Each column is one word. Cell values are counts or term frequencies. Labels sit in a vector .
Worked example. Three reviews. Vocabulary: movie (0), is (1), good (2), not (3). Labels: for positive, for negative.
| Doc | Text | movie | is | good | not | |
|---|---|---|---|---|---|---|
| d1 | movie is good | 1 | 1 | 1 | 0 | 1 |
| d2 | movie is not good | 1 | 1 | 1 | 1 | 0 |
| d3 | not good | 0 | 0 | 1 | 1 | 0 |
Read it. The design matrix is . is . Row d3 equals the counts of good not. Order is lost: not good and good not share one row.
The slide pair proves the loss. The movie my friend has not seen is good is positive. The movie my friend has seen is not good is negative. Both use the same word multiset. Their count rows match. A BoW classifier cannot split them.
RNN text classificationSearch on YouTube
The RNN pipeline keeps order. Map words to integer ids. Pad short sentences to one length. Replace ids with vectors. Feed the vectors step by step.
Integers alone mislead. Id is not larger than id . One-hot vectors remove the fake order. Each word becomes a sparse row with one .
Dense embeddings replace the sparse rows. The embedding matrix has size . is the vocabulary size. is the embedding size (feature count per word). Rows come from Word2Vec, GloVe, FastText or training from scratch.
The lookup trick skips the sparse multiply. times gives . That product copies one row of . So gather rows by index instead of multiplying.
is one word vector. is the embedding matrix. is the dense word vector. Lookup copies row of when the sits at index .
Worked example. Vocabulary size (ids to , pad id ). Embedding size . Sentence ids padded to length with .
Lookup. Copy rows of in token order. Pad rows are zeros.
Stack. Four word rows plus three pad rows give a input matrix.
| 1 | 0 | 2 | 0 |
| 0 | 1 | 1 | 0 |
| 2 | 2 | 0 | 1 |
| 0 | 0 | 1 | 2 |
| 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 |
Check. Full one-hot math would multiply by to get . Lookup copies the same rows. Dims and values agree.
Out-of-vocabulary words need a plan. Map unseen words to one unknown vector. Or build their vectors from sub-word pieces. A fresh Word2Vec trained only on new words may land in a different space, so avoid that shortcut.
Character prediction with vocab E S TSearch on YouTube
Character RNNs use a tiny vocabulary. Here it is with size . Inputs are one-hot: , , . Possible words include SET, SEE, SETS, SEES and TEST. A full capital-letter vocabulary would need size .
The model reads one character per step. It predicts the next character. Softmax over logits gives the probabilities.
holds the logits. is the predicted probability per character. is the cross entropy loss at step for the true next character.
Worked example. Input so far: S E E. True next character: S (spells SEES). Logits for are .
Softmax. Exponentiate and normalize.
Decide and score. Max probability is , so the model emits S. Loss is . Probabilities sum to .
RNN variantsSearch on YouTube
One recurrence serves many layouts. The layout follows the task.
Sentiment and document classification is many-to-one. The RNN reads one word vector per step. It updates from and . After the last word, one vector passes through softmax into positive, negative or neutral.
Image captioning is one-to-many. A CNN encoder (such as ResNet) turns the image into a vector . seeds the initial hidden state . The RNN then emits words. Step 1 takes a start token and outputs . Step 2 takes and outputs . Decoding stops at an end token or a max length.
POS tagging is many-to-many and aligned. Each word maps to its tag at the same step. Input count equals output count. No delay.
Translation and question answering is many-to-many with delay. The RNN reads the full input first. Outputs start only after encoding ends. Alignment across languages is not one-to-one.
| Variant | Layout | Outputs start |
|---|---|---|
| Sentiment scoring | many-to-one | after last word |
| Image captioning | one-to-many | after image vector seeds |
| POS tagging | many-to-many, aligned | at same step |
| Translation | many-to-many, delayed | after full input |
Quick self-testSearch on YouTube
1. Why do feedforward nets fail on The movie my friend has not seen is good vs ... has seen is not good?
Both sentences share one word multiset, so fixed-size count inputs match. Order carries the flip from not. Sequence models read order, so they split the pair.
2. Scalar RNN with , , , . Input . Find with sigmoid.
. .
3. Per-step losses are , , . What total does BPTT differentiate?
. BPTT sums per-step gradients of this total.
4. Differentiate the explicit and implicit parts of .
Explicit is the direct use at step . Implicit is the chain back through . The term is purely explicit.
5. Each step multiplies the gradient by . How much survives after steps back?
. Only about a thousandth survives. That is vanishing in numbers.
6. Gradient norm is and the ceiling is . What scale factor applies?
Factor . New norm is . Direction is unchanged.
7. Vocabulary order: movie, is, good, not. Write the BoW row for movie not good. What label breaks BoW here?
Row is . good not gives the same row with opposite sense. Counts cannot split them.
8. Vocab size , embedding size , tokens in. What tensor feeds the RNN?
Each token gives . Five tokens stack to . Lookup skips the multiply.
9. Logits . Which character wins, with what probability?
Exponentials: , , . Sum . . wins at .
10. POS tagging vs translation: which emits outputs with a delay, and why?
Translation waits for the full input first. Its outputs align with encoded meaning, not with input positions. POS tagging emits at the same step instead.
- Sequence tasks have variable length and order-dependent meaning. Fixed independent inputs fail them.
- Failed options are memory-free reuse (no history) and per-position weights (too many parameters).
- The RNN updates and predicts with shared weights.
- Training runs forward pass, total loss , then BPTT sums per-step gradients.
- BPTT splits each gradient into explicit (direct use) and implicit (chain through past states) parts.
- Long chains vanish (factors below 1, saturation) or explode (factors above 1).
- Fixes are gradient clipping (), truncated BPTT (last steps) and LSTM memory (next lecture).
- BoW counts words into a design matrix but loses order (
not goodequalsgood not). - RNN text input runs integers to padding to one-hot to embedding lookup .
- Char prediction over uses softmax ; the SEES example gives and loss .
- Variants: sentiment (many-to-one), captioning (one-to-many from ), POS (aligned), translation (delayed).
RNNs Clearly Explained
RNNs Image Captioning LSTM