πŸ“š Study Notes / Home / Neural Nets / Exam Notes / RNNs
Exam Notes Β· W5S2

Sequence Modeling: RNNs

The world is sequential β€” order matters. RNNs share one set of weights across time, carry a hidden-state memory, are trained with BPTT, and ultimately choke on vanishing gradients beyond ~20 tokens.

1 Why MLPs fail on sequences


  • Text, audio, stock prices, video, DNA all have a temporal/order dimension β€” shuffling destroys meaning. CNNs assume spatial locality; sequences are temporal.
  • Three fatal MLP problems:
    1. Fixed input size β€” MLP needs a predetermined number of input neurons.
    2. No notion of order β€” position 1 and position 100 are treated as unrelated features.
    3. Parameter explosion β€” 500 words Γ— 300-dim = 150,000 input neurons.
  • Flattening a sentence into one long vector loses all temporal structure.
  • What makes sequences special: variable length, order matters ("dog bites man" β‰  "man bites dog"), and long-range dependencies (e.g. "The students who came from France ___ French" β†’ answer "speak" depends on "students" 6 words back).
  • Key insight β€” weight sharing across time: apply the same function at every timestep. Same weights handle word 1 and word 1000 β†’ handles any length with constant parameters.

2 The vanilla RNN & recurrence


  • An RNN is a network with memory: it takes the previous hidden state h_t-1 plus input x_t and produces a new hidden state h_t.
Must-know for exam The recurrence equation:
h_t = tanh(W_xh Β· x_t  +  W_hh Β· h_t-1  +  b_h)
Start from h_0 = 0 (no prior memory). Each step combines the current input with accumulated context.
  • Unrolling: the folded loop = compact notation; the unrolled chain = what actually happens. It is the same network copied across time with identical weights at every step.
  • Three weight matrices (the only learned params, shared across all timesteps):
MatrixConnectionRole
W_xhinput β†’ hiddenhow to process new input
W_hhhidden β†’ hiddenhow to update memory
W_hyhidden β†’ outputhow to produce predictions
  • Parameter count for length T: MLP is O(TΒ·dΒ²) (grows with length); RNN is O(dΒ²) β€” constant regardless of length.
  • PyTorch: nn.RNN(input_size, hidden_size, batch_first=True); input shape (batch, seq_len, features). Forward returns output (hidden states at all timesteps) and h_n (final hidden state only).

3 Hidden state as memory


  • h_t summarizes everything from x₁ to x_t in a fixed-size vector β€” its job is to compress all past information.
  • It is a lossy compression: you can't reconstruct all past inputs. The network learns what to remember during training.
  • Karpathy's char-level RNN: hidden units spontaneously learn to track quote open/close, line position, inside-comment-vs-code, indentation β€” without explicit supervision.
  • The bottleneck: a fixed-size vector (e.g. 256 dims) must encode everything. Older info gets overwritten by newer info; finite memory means early tokens get "forgotten" on long sequences β€” this leads directly to vanishing gradients.

4 Backpropagation Through Time (BPTT)


  • The big idea (3 steps): (1) unroll the RNN across all T timesteps; (2) the unrolled RNN looks like a very deep feedforward network (a 100-token sequence β‰ˆ a 100-layer net); (3) apply standard backprop on this unrolled graph. Gradients flow backward through time.
  • The chain rule through time β€” gradient of loss w.r.t. W_hh is a product of Jacobians across timesteps:
βˆ‚L/βˆ‚W_hh  ∝  ∏ (t=k..T)  βˆ‚h_t / βˆ‚h_t-1

each factor:  βˆ‚h_t/βˆ‚h_t-1 = W_hh^T Β· diag(tanh'(Β·))
  • Truncated BPTT: full BPTT on 10,000 tokens = backprop through 10,000 layers β€” impractical. Instead, only unroll K steps (common K = 20–100, e.g. 35): process the sequence in chunks, carry h forward, backprop only within each chunk. Trade-off: can't learn dependencies longer than K steps.

5 Vanishing & exploding gradients


Must-know for exam Repeated matrix multiplication makes gradients vanish or explode. Driven by the largest singular value (spectral radius) of W_hh:
  • singular value < 1 β†’ product β†’ 0 β†’ vanishing
  • singular value > 1 β†’ product β†’ ∞ β†’ exploding
Also: tanh' ≀ 1 always, which compounds the decay.
  • Vanishing intuition: multiply a number < 1 by itself repeatedly β†’ 0. e.g. 0.9¹⁰ β‰ˆ 0.349, 0.9⁡⁰ β‰ˆ 0.005, 0.9¹⁰⁰ β‰ˆ 0.00003. The gradient from the loss barely reaches early timesteps.
  • Consequence: the network cannot learn that an input 50 steps ago matters. In practice vanilla RNNs fail on dependencies beyond ~20 tokens.
  • Exploding: symptoms are loss β†’ NaN, params β†’ ∞. Fix = gradient clipping: if β€–βˆ‡β€– > threshold, scale it down. torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0).
  • Clipping fixes exploding, NOT vanishing. Vanishing needs a new architecture β†’ LSTMs/GRUs (gates create "gradient highways" through time).

6 RNN task patterns


PatternInput β†’ OutputExample tasks
Many-to-onesequence β†’ labelsentiment, document classification, spam detection
Many-to-manysequence β†’ sequencePOS tagging, NER, machine translation
One-to-manysingle β†’ sequenceimage captioning, music generation

β˜… Likely exam questions


Q1. Write the vanilla RNN recurrence equation and name the three weight matrices.

A. h_t = tanh(W_xh·x_t + W_hh·h_t-1 + b). W_xh: input→hidden; W_hh: hidden→hidden (memory update); W_hy: hidden→output. All three are shared across every timestep.

Q2. Why can't a standard MLP handle variable-length sequences?

A. An MLP needs a fixed-size input vector. To use one you'd pad every sequence to the max length β€” wasting parameters and destroying the notion of temporal order. RNNs sidestep this via weight sharing across time.

Q3. Why does the unrolled RNN resemble a very deep feedforward network?

A. Each timestep acts like one layer, so a 100-step sequence becomes equivalent to a 100-layer net during backprop (BPTT).

Q4. Why do gradients vanish in RNNs?

A. The gradient w.r.t. W_hh is a product of Jacobians across timesteps. When the largest singular value of W_hh is < 1 (and tanh' ≀ 1), repeated multiplication decays exponentially, so gradients barely reach early timesteps.

Q5. If the largest singular value of W_hh is 0.9 and the sequence is 50 steps, how much gradient reaches step 1?

A. β‰ˆ 0.9⁡⁰ β‰ˆ 0.005 β€” only about 0.5%. The network effectively cannot learn from that early input.

Q6. What is truncated BPTT, and what does gradient clipping fix?

A. Truncated BPTT only backpropagates through K timesteps (carrying h forward between chunks), trading long-range learning for feasibility. Gradient clipping rescales gradients above a threshold β€” it fixes exploding gradients but does nothing for vanishing (that needs LSTMs/GRUs).