3.5.1 · D4Sequence Models

Exercises — Recurrent Neural Networks (RNN) architecture

3,655 words17 min readBack to topic

This page is a self-test ladder for Recurrent Neural Networks (RNN) architecture. Each rung is harder than the last: you start by recognising the formula, and end by synthesising a full training-time reasoning chain. Every solution is hidden inside a collapsible box — try the problem first, then reveal.

Before we begin, here is the single equation everything rests on. We define each symbol in words so a reader who has never seen it can follow.

We also name the quantity inside the : call it the pre-activation , defined as So is "the raw weighted sum before squashing." We will need it when we differentiate in Level 3.

The same three matrices are reused at every step — this is called weight sharing. That fact drives most of the counting problems below.

Figure — Recurrent Neural Networks (RNN) architecture

Figure s01 — the unrolled RNN. Read it left to right: each blue box is the same cell drawn three times (weight sharing). An orange arrow feeds the input up into the cell; a green arrow carries the output out the top; the red arrow between boxes is the memory handed from one step to the next. The parameter count never grows with the number of boxes.


Level 1 — Recognition

Goal: can you read the equation and identify its parts?

Exercise 1.1

An RNN has input dimension , hidden dimension , output dimension . State the shape (rows × columns) of each of , , .

Recall Solution

Read the shapes straight off the definition. A matrix that maps a vector of size into a vector of size has rows and columns (output-dim × input-dim).

  • maps input () → hidden (): .
  • maps hidden () → hidden (): .
  • maps hidden () → output (): .

What we did: matched each arrow in the figure to a matrix. Why: the shape is forced by "the output vector must come out the right size."

Exercise 1.2

True or false, and say why: "An RNN needs different weight matrices for each of its 20 time steps, so a 20-step sequence has 20 copies of ."

Recall Solution

False. There is exactly one , reused at every step. The picture of the unrolled chain shows many boxes, but they are the same box drawn again — like frames of a film showing one actor, not twenty actors. That is weight sharing.


Level 2 — Application

Goal: plug numbers in and turn the crank.

Exercise 2.1

With , , , count the total number of trainable parameters (include the biases of size and of size ).

Recall Solution

Add up every matrix and bias.

  • :
  • :
  • :
  • :
  • :

Total .

Why the count is independent of : weight sharing again — the same numbers describe a 3-step or a 3000-step sequence.

Exercise 2.2

A tiny RNN has (a single-number memory), , , , and initial state . The input sequence is . Compute (round to 4 decimals).

Recall Solution

Apply step by step (here the pre-activation is ).

What it looks like (see figure s02): the memory climbs but flattens — each new input pushes higher, yet caps it below 1. That ceiling is exactly what keeps a single RNN neuron from blowing up.

Figure — Recurrent Neural Networks (RNN) architecture

Figure s02 — the blue curve is the hidden state over 8 identical inputs; the numbers printed at the first three points are the values computed above. The dashed red line at is the ceiling — notice the curve bends toward it and never crosses. Even with input piling up forever, the memory saturates.


Level 3 — Analysis

Goal: reason about why things behave, especially gradients.

Before the exercises, two pieces of notation used in the gradient formula:

  • = the pre-activation at step (defined above): the raw weighted sum fed into . We need it because the slope of depends on where on the curve we are, and that location is .
  • = the slope of at input ; it peaks at (when ) and shrinks toward as grows.
  • = the operation that takes a vector and places its entries on the diagonal of an otherwise-zero square matrix. It appears because differentiating the element-wise scales each hidden component by its own slope — a per-component multiply, which as a matrix is a diagonal matrix. In the 1-D case (a single hidden number) is just that one number, so the whole Jacobian collapses to an ordinary product of scalars.

Where the Jacobian comes from (a 3B1B-style sketch)

We are about to multiply many copies of together. Before trusting that formula, let us see why those two pieces — and no others — show up when we ask "if I nudge a little, how much does move?"

Recall with . A tiny nudge in travels through two gates in series:

  1. Through the matrix : the nudge first hits the linear map that turns old memory into the pre-activation. So changes by . When we later push the error backward (as BPTT does) instead of pushing the input forward, this same linear map acts as its transpose — that is simply what "running a matrix in reverse" means for gradients.

  2. Through the squash: the changed then enters . But is not straight — its steepness is at that exact spot. So the change is scaled by the local slope, component by component. Packaging one slope per hidden unit onto a diagonal gives .

Multiply the two gate-effects and you get exactly one factor for one step. Chaining steps means the nudge passes through the same pair of gates over and over — hence the product of identical-looking factors. The figure below makes the "two gates in series, repeated" picture concrete.

Figure — Recurrent Neural Networks (RNN) architecture

Figure s04 — one BPTT step as two gates in series. A gradient entering from the right (red) first passes the blue gate (linear rescale by the recurrent matrix), then the orange gate (multiply by the local slope of , always ). Chaining many steps stacks these gate-pairs — every extra step multiplies in another factor, which is precisely why the product either shrinks to nothing or blows up.

Exercise 3.1

Recall the through-time Jacobian product that appears in Backpropagation Through Time (BPTT): Suppose (1-D case) and at every step. What is across a gap of steps? Is this vanishing or exploding?

Recall Solution

In 1-D, is just the number and is just the number , so the product becomes a plain power: each factor is , multiplied times. Since , raising it to the 20th power drives the gradient toward zero: this is a vanishing gradient. A signal from 20 steps back arrives roughly weaker.

Why this is the whole story of RNN failure: the derivative of is at most (and usually well below it), so unless compensates by being large, the per-step factor is and long-range memory decays exponentially.

Exercise 3.2

Now set with . Over steps, does the gradient vanish or explode? Give the magnitude.

Recall Solution

Per-step factor . Over 20 steps: This explodes — the gradient grows about , which in higher dimensions produces NaN losses. The standard patch is Gradient Clipping (rescale the gradient if its norm exceeds a threshold).

Figure — Recurrent Neural Networks (RNN) architecture

Figure s03 — the gradient magnitude versus how many steps back you look, on a log vertical axis. The blue line (per-step factor ) plunges toward zero (vanishing); the red line (factor ) rockets upward (exploding). The gray dashed line at height is the knife-edge: below it gradients die, above it they blow up.

Exercise 3.3

Take (a negative recurrent weight) with at every step. Compute the 1-D through-time factor for gaps of and describe the pattern.

Recall Solution

Each per-step factor is , so the gap- factor is :

  • :
  • :
  • :
  • :

The sign flips every step while the magnitude still shrinks (). So a negative produces an oscillating, decaying gradient: the influence of a past step alternates between pushing the loss up and pulling it down as the gap grows. Vanishing/exploding is governed by the magnitude ; the sign of adds this alternation on top.


Level 4 — Synthesis

Goal: combine architecture choices to design or diagnose a full system.

Two definitions we will lean on here:

  • The logistic sigmoid is the squashing function , which takes any real number and returns a value in . That output range is exactly what we want for a probability.

Exercise 4.1

You must classify a movie review (a variable-length sentence) as positive or negative. Which RNN type (many-to-many, many-to-one, one-to-many, encoder-decoder) is correct, which hidden state feeds the classifier, and why do we ignore the intermediate outputs?

Recall Solution

Type: many-to-one (sequence → single label). You feed the whole sentence word-by-word using Word Embeddings as inputs , then read only the final hidden state into a small classifier head: Here is a new weight vector (one weight per hidden component, so its length is ) and is a new scalar bias. These belong to the classifier head and are distinct from the RNN's own — in a pure classifier you replace the sequence-output layer with this single-number head . The dot product collapses the -vector to one number, and turns that number into a probability in . Why only : by construction has "read" every earlier word (each folded in the previous memory), so it is already a summary of the entire review. The intermediate would be per-word predictions we simply do not need for a single sentence-level verdict.

Exercise 4.2

For machine translation French → English, sentences differ in length between the two languages. Explain why a plain many-to-many RNN (one output per input step) fails, and what architecture fixes it.

Recall Solution

A synchronous many-to-many RNN emits exactly one output per input step, forcing . But sentence pairs almost never match length: "Je t'aime" (3 tokens) → "I love you" (3) happens to align, yet "Il pleut" (2) → "It is raining" (3) does not. Any fixed one-output-per-input rule cannot produce a different number of output tokens than input tokens, so this architecture cannot even express most translations.

Fix: the encoder–decoder (see Sequence-to-Sequence Models). It splits the job across two separate RNNs:

  1. Encoder RNN — reads the French sentence step by step and does not emit any output. Its only job is to fold the whole sentence into its final hidden state, called the context vector . Think of as a fixed-size summary of the meaning.
  2. Decoder RNN — a second RNN whose initial hidden state is loaded from (a one-to-many pattern). It then generates English tokens autoregressively: at each step it takes the token it just produced as the next input, updates its memory, emits the next token, and repeats. It keeps going until it emits a special end-of-sentence token, so the number of output steps is decided by the decoder at run time and is free to differ from .

This decoupling — encode into , then freely decode — is exactly what lets input and output lengths differ. When a single fixed becomes a bottleneck for long sentences (it must hold the entire meaning in one vector), we add an Attention Mechanism so the decoder can look back at all encoder states rather than just the last one; that idea ultimately grew into Transformers.


Level 5 — Mastery

Goal: full end-to-end derivations, catching every case and edge condition.

Exercise 5.1

Redo Exercise 2.2 but with a negative input burst: , , , , and . Compute and verify the state stays inside .

Recall Solution

:

Every value lies in , confirming the case coverage point: bounds the memory in for any sign or size of input. Negative inputs push the memory toward (the floor) exactly as positive inputs push it toward (the ceiling), and it can never escape the band.

Exercise 5.2

Consider the degenerate zero case: for all , , and any , with . Prove that for all , and explain what this tells you about an untrained / un-driven RNN.

Recall Solution

Induction. Base: (given). Step: assume . Then So for all . Interpretation: with no input and no bias, the network has nothing to remember — the memory sits at the origin forever. The state only becomes non-trivial once real inputs or a non-zero bias drive it. This is the sanity-check baseline: any non-zero hidden state must be traceable to actual data flowing in.

Exercise 5.3

A per-step factor in the through-time gradient is . Since (attained at ), find the exact scalar that keeps the gradient magnitude constant over any gap when sits at its maximum, and explain why this "perfect" value is still unusable in practice.

Recall Solution

We want . With , that forces . Why it still fails: only at . As soon as the pre-activation moves away from 0 (which it does the moment real data arrives), , so the actual factor drops below 1 and the gradient vanishes again. There is no fixed scalar that keeps across the changing of a real sequence — precisely the impossibility that motivates gated architectures (Long Short-Term Memory (LSTM), Gated Recurrent Unit (GRU)).


Quick self-check

Predicted-answer cloze — cover the right side.

Total parameters for (with biases)
Per-step gradient factor when
(vanishing)
Gap-2 factor when
(sign flips, magnitude shrinks)
Which single hidden state feeds a sentiment classifier
the final state
Value of , giving the zero-input fixed point
Scalar that keeps gradient constant when
(but only at )