RNN & GRU

A plain recurrent network sends its learning signal back one step at a time, and each step shrinks it. Twenty steps back, only about one ten-millionth is left. A GRU's update gate opens a keep path that still delivers 12%.

Pick a cell, set how far back the signal must travel, and press Send. Then we build, piece by piece, the hidden state, backpropagation through time, the reason the signal dies and the two gates that fix it. In Chapter 8 a real GRU trains in this page.

You need a neuron (a weighted sum, then a squashing function) and backpropagation (the chain rule, run backwards; see Backpropagation). We build the rest from zero.

Built on Elman (1990), Hochreiter and Schmidhuber (1997), Pascanu, Mikolov and Bengio (2013), Cho et al. (2014) and Chung et al. (2014). The toys, numbers and devices here are our own.

Send the signal back in time

20

Illustrative per-step factors. Plain RNN: a recurrent stretch of 0.9 times a typical tanh slope of 0.5 (Chapter 3). GRU: the keep path alone, 1 − z per step (Chapter 4); the full GRU adds terms through its gates.

Chapter 0

The Memory Problem

See why a network with no memory cannot predict the next letter of hello

Read the word hello one letter at a time and guess the next letter. After h comes e. After e comes l. After the first l comes l, and after the second l comes o.

Give this job to a feed-forward network, a stack of weighted sums that maps one input to one output. Its input is the current letter as a one-hot vector: all zeros except a 1 at that letter's slot. Both l's give the same input, so the network must give the same answer twice.

The best single answer splits the bet: 0.5 on l and 0.5 on o. The cross-entropy loss is minus the log of the probability given to the true letter, so each l costs ln 2 = 0.693. No training gets below that floor. A bet of 0.9 and 0.1 costs 0.105 + 2.303 = 2.408 for the pair, worse than 1.386.

A wider input window helps until the needed letter falls outside it. With 27 symbols and 100 hidden units, a window of k letters costs 2,700 × k first-layer weights. It still has a hard edge.

The fix: carry a state

Keep a small notebook. At each letter, write a new page from the old page and the new letter. The notebook is the hidden state h. A network with this loop is a recurrent neural network (RNN), and it runs the same rule with the same weights at every step.

Make it tiny: one number. Give each letter a fixed score: h 1.0, e 0.5, l −0.4, o 0.2. Call the score of the letter at step t a(xt), and the weight that carries the old state forward u.

Say it aloud

h-t equals tanh of a of x-t, plus u times h-t-minus-1.

ht
h-t the state after reading letter t, between −1 and 1.
tanh
tanh squashes any number into the range −1 to 1.
a(xt)
a of x-t the fixed score of the letter read at step t.
u
u how much of the old state carries forward; 0.9 here.
ht−1
h-t-minus-1 the state before this letter; h-0 is 0.
In plain words

Shrink the old state h-t-minus-1 by u. Add the letter's score a. Squash with tanh. That is the new state h-t.

With numbers

With the made-up scores: h-1 = tanh(1.0) = 0.762, h-2 = tanh(0.5 + 0.686) = 0.829, h-3 = tanh(−0.4 + 0.746) = 0.333, h-4 = tanh(−0.4 + 0.300) = −0.100. The two l's leave different states.

Give the network a memory

Each bar is the state after one letter. Outlines mark the two l's. Drag u to 0 and watch them merge.

0.90

Illustrative one-number RNN with the made-up letter scores above, starting from h = 0.

At u = 0 both l's give tanh(−0.4) = −0.380, and the 0.693 floor comes back. Memory is the only difference.

Symptom: the training loss stops at a floor well above zero, on data a person finds easy.

Measure: look for inputs that are the same but need different outputs.

Fix: give the model a state, or context that tells those inputs apart.

The road

  1. One vector of memory: the Elman cell, by hand.
  2. Unrolling time: backpropagation through time.
  3. Why the signal dies: vanishing and exploding gradients.
  4. The update gate: a keep path for the gradient.
  5. The reset gate: the full GRU, one step.
  6. GRU versus LSTM: gates, parameters, evidence.
  7. Training a character model: loss, loop, temperature.
  8. The live lab: a GRU trains in this page.
  9. Beyond the cell: stacks, attention and modern recurrences.
  10. The field guide: terms, numbers, code.
Why can a network with no memory not get below 0.693 at each l of hello?

Chapter 1

One Vector of Memory

Turn the one-number notebook into the vanilla RNN cell and step it by hand

One number holds one fact. Make the state a vector of n numbers. This is the Elman network, from Jeffrey Elman's 1990 paper Finding Structure in Time, and it is what people mean by a vanilla RNN.

Name the parts first. The input x-t is the one-hot vector for letter t, of length d, the vocabulary size. W-x is an n by d matrix: what the new letter adds. W-h is an n by n matrix: how the old state is rewritten. b is a bias of length n.

Say it aloud

h-t equals tanh of W-x times x-t, plus W-h times h-t-minus-1, plus b.

ht
h-t the state after step t: n numbers, each between −1 and 1.
Wx
W-x the input weights, n by d.
xt
x-t the one-hot vector for letter t, length d.
Wh
W-h the recurrent weights, n by n.
ht−1
h-t-minus-1 the state before this letter.
b
b the bias: a resting level for each unit.
In plain words

Look up the letter's column of W-x. Multiply the old state h-t-minus-1 by W-h. Add both and b, then squash each number with tanh.

With numbers

With the made-up weights below, reading a from h-0 = 0: column 1 of W-x plus b is [1.0 + 0.1, 0.0 − 0.1] = [1.1, −0.1]. So h-1 = [tanh 1.1, tanh −0.1] = [0.800, −0.100].

Wx = [[1.0, −0.5, 0.2], [0.0, 0.8, −0.3]]   Wh = [[0.5, −0.2], [0.1, 0.6]]   b = [0.1, −0.1]vocabulary a, b, c; n = 2

read b: Whh1 = [0.420, 0.020] → pre = [0.020, 0.720] → h2 = [0.020, 0.617]

read c: Whh2 = [−0.113, 0.372] → pre = [0.187, −0.028] → h3 = [0.185, −0.028]

Step the cell through a, b, c

Each row is one unit. Blue is what the letter adds, teal is what the old state adds, grey is the bias. The right bar is the new state. Scale W-h and step again.

1.0

The made-up weights of the worked example. The scale multiplies all of W-h.

A one-hot input picks one column of W-x, so real code uses an embedding lookup in place of the product. The same weights run at every step, so a text of 3 letters and one of 3,000 use the same number of weights. To predict, a readout matrix W-y maps h-t to one score per letter, and softmax turns the scores into probabilities.

Symptom: the model ignores everything before the current letter.

Measure: set W-h to zero. If the loss does not change, the state carries nothing.

Fix: check that h passes from step to step and is not reset inside the loop.

For a one-hot input x-t, what is W-x times x-t?

Chapter 2

Unrolling Time

Write the loop out as a deep network and run the chain rule backwards through it

Backpropagation needs a graph without loops. So write out one copy of the cell per step, left to right. A 100-step text becomes a 100-layer network whose layers share one set of weights. Backpropagation over it is backpropagation through time (BPTT).

Use a one-number cell to see every value: h-t = tanh(w x-t + u h-t-minus-1), with input weight w and recurrent weight u. The loss looks only at the last state: L = ½(h-3 − y)², where y is the target. The gradient at state t, written dL/dh-t, says how much the loss moves when h-t moves a little.

Say it aloud

d L by d h-t equals d L by d h-t-plus-1, times one minus h-t-plus-1 squared, times u.

∂L/∂ht
d L by d h-t the gradient at step t: how much the loss moves per unit move of h-t.
∂L/∂ht+1
d L by d h-t-plus-1 the gradient one step later, already known.
1 − ht+12
one minus h-t-plus-1 squared the slope of tanh at that step, between 0 and 1.
u
u the recurrent weight.
In plain words

Start at the last state. To step back once, multiply the gradient by that step's tanh slope and by u. Repeat until you reach step 1.

With numbers

Made-up: w = 0.8, u = 0.9, inputs 1, 1, 1, target 0.5. The states are 0.664, 0.885, 0.921. So dL/dh-3 = 0.921 − 0.5 = 0.421. One step back multiplies by 0.152 × 0.9 = 0.136, so dL/dh-2 = 0.057.

The cell uses a shared weight at every step, so its gradient is a sum with one term per step. For w, the term at step t is dL/dh-t times the tanh slope at t times x-t:

∂L/∂w = 0.0638 + 0.0125 + 0.0063 = 0.0826terms from steps 3, 2 and 1

The newest step gives ten times more than the oldest. Chapter 3 follows that ratio over 50 steps.

Truncated BPTT

Long texts are cut into chunks of k steps. The state's value carries across a chunk edge, but its gradient path is cut. Drop step 1 above (k = 2) and the gradient becomes 0.0763, 7.6% low. In PyTorch the cut is one line: h = h.detach().

Choose how far back credit goes

Each bar is one step's share of the gradient for w, newest on the right. Truncation keeps the lit bars. Drag the window, then raise u.

3
0.90

Illustrative one-number cell over 12 steps with a small alternating input, so the state stays near 0 and the tanh slope near 1. Bars are sizes; signed terms can cancel.

pythonw, u, y, xs = 0.8, 0.9, 0.5, [1.0, 1.0, 1.0]
hs = [0.0]
for x in xs: hs.append(np.tanh(w*x + u*hs[-1]))   # forward, keep every state
dw = du = 0.0; dh = hs[-1] - y
for t in (3, 2, 1):
    da = dh * (1 - hs[t]**2)          # through the tanh
    dw += da * xs[t-1]; du += da * hs[t-1]   # += : shared weights
    dh = da * u                      # one step further back
print(round(dw, 4), round(du, 4))          # 0.0826 0.0647

Symptom: a hand-written RNN learns but stalls above a library model.

Measure: compare your gradients with autograd on a 3-step example.

Fix: add shared-weight gradients with +=, never =.

In truncated BPTT, what is cut at a chunk edge?

Chapter 3

Why the Signal Dies

Multiply one factor per step and watch the gradient shrink to nothing or blow up

For a vector cell, one step back multiplies the gradient by a matrix, the Jacobian of h-t with respect to h-t-minus-1. It equals D-t W-h, where D-t is a diagonal matrix of each unit's tanh slope. Going back T steps multiplies T of them.

Bound the size. Call γ (gamma) the largest tanh slope at any step; it is at most 1. Call σ-max (sigma max) the most W-h can stretch a vector in one step, its largest singular value.

Say it aloud

The size of d h-T by d h-0 is at most gamma times sigma-max, to the power T.

‖ ‖
the size of the norm: the most a matrix can stretch a vector.
∂hT/∂h0
d h-T by d h-0 how a nudge to the first state moves the state T steps later.
γ
gamma the largest tanh slope at any step, at most 1.
σmax
sigma-max the largest singular value of W-h.
T
T the number of steps between the two states.
In plain words

Multiply gamma by sigma-max to get one step's worst-case factor. Raise it to the power T. Below 1 the bound shrinks fast; above 1 it allows growth.

With numbers

Made-up: sigma-max 0.9 and a typical slope 0.5 give 0.45 a step. After 20 steps, 0.45 to the 20 = 1.2 × 10−7. A factor of 1.5 gives 1.5 to the 20 = 3,325.

This is the analysis of Pascanu, Mikolov and Bengio (2013). If sigma-max is below 1/γ, gradients from far steps must vanish. Above it, they can explode.

Turn the dial through 1

The curve is the per-step factor raised to the distance, on a log scale. Move sigma-max and the tanh slope.

0.90
0.50

An illustrative bound, not a measured gradient. The dashed line is 1, where the signal neither grows nor shrinks.

FailureSymptomFix
Explodingthe loss spikes, then turns to NaNgradient norm clipping
Vanishingthe loss falls, but long dependencies are never learneda gated cell (Chapters 4 and 5)

Gradient norm clipping rescales the whole gradient when its size passes a threshold c. With size 47.3 and c = 5, clipping multiplies every entry by 5/47.3 = 0.106, so 12.0 becomes 1.27. The direction stays and the size becomes 5.

pythonloss.backward()
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0)   # returns the size before clipping: log it
optimizer.step(); optimizer.zero_grad()
Your RNN trains smoothly but never learns a dependency 40 steps long. Which fix targets the cause?

Chapter 4

The Update Gate

Blend the old state with fresh content so the gradient gets a path it can keep near 1

The trouble is the factor D-t W-h at every step. We want a different path back, one the network can set near 1 when a memory matters.

Let each unit choose: keep its old value, or replace it with fresh content. Call the fresh content the candidate h̃-t (h-tilde-t). A hard switch has no gradient, so blend the two with a learned number z-t between 0 and 1, the update gate.

Say it aloud

h-t equals one minus z-t times h-t-minus-1, plus z-t times h-tilde-t, unit by unit.

ht
h-t the new state.
1 − zt
one minus z-t the share of the old value each unit keeps.
⊙
times, unit by unit multiply matching entries.
ht−1
h-t-minus-1 the old state.
zt
z-t the update gate: one number per unit, 0 to 1, the share written.
h̃t
h-tilde-t the candidate: the fresh content.
In plain words

For each unit, keep the share 1 − z of the old value and write the share z of the candidate. The shares add to 1, so h-t lands between the old value and the candidate.

With numbers

Made-up: old value 0.5, candidate 0.575, z = 0.675. Then h = 0.325 × 0.5 + 0.675 × 0.575 = 0.551.

The gate comes from the letter and the old state, squashed into 0 to 1 by the sigmoid σ(a) = 1/(1 + e−a). W-z and U-z are the gate's own input and recurrent weights, and b-z is its bias:

zt = σ( Wz xt + Uz ht−1 + bz )

Now the gradient. Through the keep term alone, one step back multiplies by 1 − z. Near z = 0 that is near 1: a highway, the same idea as a residual connection.

Open the keep path

Teal is the GRU keep path, (1 − z) to the T. Grey is the plain RNN's 0.45 to the T. Drag z and the distance.

0.10
20

The keep path only; the full GRU Jacobian adds terms through the gates and the candidate. 0.45 is Chapter 3's illustrative plain-RNN factor.

At z = 0.5 the keep path gives 9.5 × 10−7 after 20 steps; at z = 0.9, only 10−20. The gate does not make memory free. It makes survival a choice, unit by unit.

Symptom: you set b-z positive "to remember more", and the model forgets faster.

Measure: print the mean of z early in training.

Fix: here z is the share written, so push b-z negative to keep.

With z = 0.1 at every step, how much does the keep path deliver 20 steps back?

Chapter 5

The Reset Gate and the Full GRU

Let the candidate choose how much past to read, then run one full step by hand

The plain way to make the candidate is the Elman cell, which always reads the whole old state. At the start of a new sentence you want a proposal that ignores the last one.

So add a second gate, the reset gate r-t, inside the candidate. It scales how much of the old state the candidate may read. W-h, U-h and b-h are the candidate's own weights.

Say it aloud

h-tilde-t equals tanh of W-h times x-t, plus U-h times r-t times h-t-minus-1, plus b-h.

h̃t
h-tilde-t the candidate.
Wh xt
W-h times x-t what the letter proposes.
Uh
U-h the candidate's recurrent weights, n by n.
rt
r-t the reset gate: one number per unit, 0 to 1, how much past to read.
ht−1
h-t-minus-1 the old state, filtered by r-t unit by unit.
bh
b-h the candidate's bias.
In plain words

Filter the old state h-t-minus-1 through r-t. Mix it with the letter's input, add b-h and squash. At r = 0 the candidate sees only the letter.

With numbers

In the step below, r = [0.520, 0.666] and the old state is [0.5, −0.2]. The filtered state is [0.260, −0.133], and the candidate is [0.575, 0.249].

The reset gate has the same form as z, with its own weights: r-t = σ(W-r x-t + U-r h-t-minus-1 + b-r). Why put r inside the candidate and not on h-t? Inside, it limits only what the proposal reads. The old state still survives in the (1 − z) term, so reading and keeping are two separate choices.

One step, every number

Old state [0.5, −0.2], letter b, the made-up weights in the code below.

  1. Update gate: a-z = [0.6 + 0.13, −0.4 − 0.20 + 0.1] = [0.73, −0.50], so z = [0.675, 0.378].
  2. Reset gate: a-r = [−0.3 + 0.18 + 0.2, 0.7 − 0.01] = [0.08, 0.69], so r = [0.520, 0.666].
  3. Candidate: a-h = [0.5 + 0.155, 0.4 − 0.146] = [0.655, 0.254], so h̃ = [0.575, 0.249].
  4. Blend: h = [0.325 × 0.5 + 0.675 × 0.575, 0.622 × (−0.2) + 0.378 × 0.249] = [0.551, −0.031].

Drive the two gates yourself

Each line is one unit. The grey dot is the old value, yellow the candidate, the teal ring the new state. Set z and r for each unit.

0.675
0.378
0.520
0.666

The made-up weights of the worked step. Here you set the gates by hand; in the cell they come from the sigmoids. The hand example rounds the gates to three places.

pythonsig = lambda a: 1 / (1 + np.exp(-a))
# made-up weights; only the column for letter b matters in this step
Wz_b, Uz, bz = np.array([0.6, -0.4]), np.array([[0.3, 0.1], [-0.2, 0.5]]), np.array([0.0, 0.1])
Wr_b, Ur, br = np.array([-0.3, 0.7]), np.array([[0.2, -0.4], [0.1, 0.3]]), np.array([0.2, 0.0])
Wh_b, Uh, bh = np.array([0.5, 0.4]), np.array([[0.7, 0.2], [-0.1, 0.9]]), np.zeros(2)
h = np.array([0.5, -0.2])
z  = sig(Wz_b + Uz @ h + bz)              # share to write   [0.675 0.378]
r  = sig(Wr_b + Ur @ h + br)              # share to read    [0.520 0.666]
hc = np.tanh(Wh_b + Uh @ (r * h) + bh)     # candidate        [0.575 0.249]
h  = (1 - z) * h + z * hc                  # new state        [0.551 -0.031]

Unit 1 writes two thirds of its candidate. Unit 2 keeps 62% of its old value and moves only from −0.2 to −0.031. Cho et al. (2014) wrote that because each unit has its own gates, each unit learns its own time scale.

Symptom: your GRU and PyTorch's disagree on the same weights.

Measure: compute one step by hand and compare.

Fix: PyTorch applies r after the U-h product and uses the mirror z. Match the formula, not only the numbers.

Why does the GRU apply r inside the candidate, not to the final state?

Chapter 6

GRU Versus LSTM

Compare the two gated cells by structure, by weight count and by what experiments found

The GRU was not the first gated cell. Hochreiter and Schmidhuber published the LSTM (long short-term memory) in 1997, 17 years before the GRU. The forget gate in today's LSTM came later, from Gers, Schmidhuber and Cummins (2000).

The LSTM keeps a private cell state c-t next to the exposed state h-t. It has a forget gate f, an input gate i and an output gate o, each a sigmoid, plus a tanh candidate g:

ct = ft ⊙ ct−1 + it ⊙ gt    ht = ot ⊙ tanh(ct)

PropertyGRULSTM
State vectorsone, htwo, c and h
Keep and writetied: 1 − z and zseparate: f and i
Hide memoryno output gateo hides part of c
State rangestays in −1 to 1c can grow past 1
Weight blocks34

Each block, a gate or a candidate, has an input matrix, a recurrent matrix and a bias. Call the number of blocks G, the state width n and the input width d.

Say it aloud

params equals G times n times d, plus n squared, plus n.

params
params the weights in one layer of the cell.
G
G the number of blocks: 1 vanilla, 3 GRU, 4 LSTM.
n·d
n times d the input matrix of one block.
n2
n squared the recurrent matrix of one block.
n
n the bias of one block, one per unit.
In plain words

Count one block: n times d, plus n squared, plus n. Multiply by the number of blocks G.

With numbers

d = 128, n = 256: one block is 32,768 + 65,536 + 256 = 98,560. A GRU has 3 × 98,560 = 295,680; an LSTM has 394,240. PyTorch reports 296,448 for the GRU, because it keeps two biases per block.

Price a GRU against an LSTM

Bars are weights per layer. Drag the input width d and the state width n.

128
256

The formula above with one bias per block. PyTorch adds n more weights per block.

What did experiments find? Chung, Gulcehre, Cho and Bengio (2014) compared the units on polyphonic music and raw speech. Both gated units clearly beat the plain tanh unit. Between GRU and LSTM they "could not make concrete conclusion". The GRU was best on most music sets; on speech, each cell won one set.

Gate biases set where training starts. An LSTM forget bias of 0 starts f at 0.5, and 0.5 to the 30 is 9.3 × 10−10. A bias of 1 starts f at 0.731, and 0.731 to the 30 is 8.3 × 10−5. The GRU mirror is b-z = −1, which starts the keep share at 0.731.

Symptom: an LSTM trains worse than a GRU of the same size.

Measure: print the mean forget gate at step 0.

Fix: set the forget bias to 1. PyTorch packs it in the second quarter of each LSTM bias.

At the same widths, a GRU has three quarters of an LSTM's weights. Why?

Chapter 7

Training a Character Model

Score each guess with cross-entropy, train in chunks, then sample with a temperature

A character-level language model reads text and predicts each next character. At every step the readout gives one score per character, the logits. Softmax turns them into probabilities p: raise e to each score, then divide by the sum. Call the index of the true next character k.

Say it aloud

L-t equals minus the natural log of p-t at k.

Lt
L-t the loss at step t, in nats.
−ln
minus the natural log turns a probability near 1 into a loss near 0, and a small probability into a big loss.
pt
p-t the probabilities the model gives at step t.
[k]
at k the entry for the true next character k.
In plain words

Find the probability p-t gave to the true character k. Take its natural log and flip the sign. Average L-t over the steps of a chunk.

With numbers

Made-up logits [2.0, 0.5, −1.0, 0.3, 1.2], true character first. The exponentials sum to 14.08, so p[k] = 7.389/14.08 = 0.525 and L = −ln 0.525 = 0.644 nats. A uniform guess over 5 costs ln 5 = 1.609.

The gradient of L with respect to the logits is p minus the one-hot target: [−0.475, 0.117, 0.026, 0.096, 0.236]. The true score goes up, the rest go down, and the entries sum to 0.

The training loop

  1. Take 25 characters as inputs and the same 25, shifted by one, as targets.
  2. Run the GRU forward from the carried state. Keep every z, r, h̃, h and p.
  3. Add the loss of all 25 steps.
  4. Run BPTT backward, adding into every gradient with +=.
  5. Clip, then take one optimizer step.
  6. Keep h for the next chunk and cut its gradient.

During training, each input is the true previous character, even after a wrong guess. This is teacher forcing. When generating, the model feeds back its own samples, so it can meet prefixes it never trained on.

Temperature

To generate, divide the logits by a temperature T before softmax, then draw. T below 1 sharpens the odds; T above 1 flattens them. It changes decoding only, not the model.

p = softmax(logits / T)top probability 0.777 at T = 0.5, 0.525 at T = 1, 0.358 at T = 2

Reshape the next-character odds

Green bars are the odds at this temperature. Press Sample to draw 200 times; the outlines are the tally.

1.00

The made-up logits above, given made-up character labels. Draws use your browser's random numbers.

Symptom: samples repeat one phrase forever.

Measure: sample the same model at T = 1.

Fix: if T = 1 looks fine, raise the temperature. If not, the model needs more training.

What does sampling at temperature 0.5 instead of 1 do?

Chapter 8

The Live Lab

Train a real character-level GRU in this page, then break it on purpose

Everything above now runs here: Chapter 5's cell, Chapter 2's backward pass and Chapter 7's loop, in plain JavaScript. The text is 273 characters about gates and state, with 24 distinct characters. Press Train.

Train a GRU in your browser

Top: the loss per character, with the uniform and letter-frequency baselines dashed. Below: z (purple) and r (pink) for the last 25 steps, one row per unit.

GENERATED SAMPLE
0.100
32
0.80

Real training, run live: 25-step chunks, Adagrad, each gradient entry clipped to ±5. The curve is a moving average with decay 0.97, so it lags about 33 steps. The loss is on training chunks only. Break it sets the learning rate to 5 and the width to 2.

Read the curve against two baselines. A uniform guess costs ln 24 = 3.18 nats. A guess that knows only letter frequencies costs 2.65 nats on this text: e appears 51 times, v once. Below 2.65, the model uses context.

Do thisLook for
Break itthe loss stalls high, near the letter-frequency line, and samples turn to noise
Learning rate 0.001slow progress in the same number of steps
2 units, then 64the narrow state stalls higher; the wide one costs more per step
Temperature 0.2, then 2repeated phrases, then noisy text

Dark z in the heatmap means that unit keeps its value at that step. A stripe is a hint about what a unit tracks, not proof. At 32 units and 24 characters, one forward step costs 3 × (32 × 24 + 32²) = 5,376 multiply-adds in the gates and candidate. At 64 units it costs 3.1 times more, because the n² term grows fastest.

Symptom: the loss turns to NaN or climbs back to the uniform line.

Measure: note the learning rate and the step where it jumped.

Fix: lower the learning rate. Clipping each entry limits a step but cannot save a rate that is far too high.

The lab's loss falls from 3.18 to 2.0 nats. What does that show?

Chapter 9

Beyond the Cell

Stack the cell, run it both ways, add attention, and price a fixed state against a growing cache

One GRU layer reading left to right is a building block. Real systems combine it in three ways.

CombinationWhat it doesCost at d = 128, n = 256
Stacked, 2 layerslayer 2 reads layer 1's states295,680 + 393,984 = 689,664 weights
Bidirectionala left-to-right and a right-to-left cell, states joined591,360 weights; cannot generate left to right
Encoder and decoderthe encoder's last state starts the decoderone 256-number summary for any source length

The encoder and decoder squeeze a whole sentence into one vector. Bahdanau, Cho and Bengio (2014) suspected that fixed-length vector was a bottleneck. Their fix lets the decoder look back at every encoder state with learned weights: attention. In 2017 the Transformer kept attention, dropped recurrence and trained on all positions at once.

The price of no fixed state

A Transformer decoder stores a key and a value for every past token: the KV cache. A GRU stores one state. Take 2 layers of width 512 in float32, 4 bytes a number.

GRU state = 2 × 512 × 4 = 4,096 bytesthe same at any length

KV cache = 2 layers × 2 (key, value) × 512 × 4 = 8,192 bytes per token

Grow the context

Teal is the GRU's fixed state. Grey is the KV cache. Drag the number of tokens.

10,000

A plain full-attention decoder with no cache compression. Grouped-query attention, lower precision and sliding windows shrink the cache.

Attention is a recurrence too

Remove the softmax from attention and the past collapses into one fixed matrix that each token adds to: an RNN whose state is a matrix. That is linear attention. DeltaNet swaps the plain add for the delta rule, which corrects before it writes. Linear Transformers as Fast Weight Programmers builds this from zero.

RWKV, Mamba, xLSTM, Griffin and Hawk also keep a fixed-size state when they generate, and each finds a way to train in parallel. A standard GRU cannot, because its gates depend on the last state through a squashing function, so each step waits for the one before.

Symptom: the GPU sits mostly idle while a GRU trains on long sequences.

Measure: GPU use against batch size.

Fix: bigger batches, a fused kernel such as cuDNN's, or a recurrence that trains in parallel.

Why can a bidirectional GRU not generate text left to right?

Chapter 10

The Field Guide

Keep the terms, the numbers, a checklist and the core code on one page

An RNN rewrites a fixed-size state at every step, so it can use a long prefix in constant memory. BPTT multiplies one factor per step, so plain gradients vanish or explode. Clipping handles explosion. The GRU's update gate opens a keep path for vanishing, and its reset gate lets the candidate ignore the past.

The terms

TermMeaning
Hidden state hThe vector the cell rewrites each step: its whole memory.
BPTTBackpropagation over the loop written out one copy per step.
Truncated BPTTCut the gradient path every k steps; keep the state's value.
JacobianHow a change in h-t-minus-1 moves h-t: D-t W-h for the Elman cell.
Gradient clippingRescale the gradient to size c when it is bigger.
Update gate zShare of the candidate written (here); the unit keeps 1 − z.
Reset gate rShare of the old state the candidate may read.
Candidate h̃The fresh content the cell proposes.
Teacher forcingFeed the true previous character during training.
Temperature TDivide the logits by T before sampling.

The numbers

WhatNumberWhy it matters
Memoryless floor on hello0.693 nats per lSame input, two targets
Plain RNN, 20 steps at 0.451.2 × 10−7Far credit vanishes
GRU keep path, z = 0.1, 20 steps0.12The gate lets credit survive
Truncate 3 steps to 27.6% offTruncation adds bias
GRU against LSTM, d 128, n 256295,680 against 394,2403 blocks against 4
Forget bias 0 against 1, 30 steps9.3 × 10−10 against 8.3 × 10−5Initialization sets the start
Lab baselines3.18 and 2.65 natsUniform and frequency-only
Decode memory at 10,000 tokens4 KB against 82 MBFixed state against KV cache

The checklist

The core as code

pythonimport torch, torch.nn as nn

class CharGRU(nn.Module):
    def __init__(self, V, H):
        super().__init__()
        self.emb = nn.Embedding(V, H)             # the one-hot column lookup
        self.gru = nn.GRU(H, H, batch_first=True)
        self.out = nn.Linear(H, V)                # readout: one score per character
    def forward(self, x, h=None):              # x: (B, T) ids
        o, h = self.gru(self.emb(x), h)          # o: (B, T, H)
        return self.out(o), h                   # logits: (B, T, V)

model = CharGRU(V, 128); opt = torch.optim.Adam(model.parameters(), lr=2e-3)
h = None
for xb, yb in loader:                          # consecutive 25-character chunks
    logits, h = model(xb, h)
    h = h.detach()                             # truncation: keep the value, cut the graph
    loss = nn.functional.cross_entropy(logits.reshape(-1, V), yb.reshape(-1))
    opt.zero_grad(); loss.backward()
    nn.utils.clip_grad_norm_(model.parameters(), 5.0)
    opt.step()

Keep going

The takeaway. A recurrent cell carries one state forward; training multiplies one factor per step backward. Gates let the network set that factor near 1 where a memory matters.
What does the GRU change about the path the gradient takes back through time?

Now press Present or Teach and explain from memory: the state, BPTT, the vanishing factor, the two gates and the weight count. Then go back to the hero and say why each cell's signal survives as it does.

Sources

RNN & GRU: Recurrent Architectures
Cho et al. 2014 · Chung et al. 2014 · Back to Gleams