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.
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
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.
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.
h-t equals tanh of a of x-t, plus u times h-t-minus-1.
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 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.
Each bar is the state after one letter. Outlines mark the two l's. Drag u to 0 and watch them merge.
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.
Chapter 1
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.
h-t equals tanh of W-x times x-t, plus W-h times h-t-minus-1, plus b.
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 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]
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.
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.
Chapter 2
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.
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.
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.
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.
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().
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.
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 =.
Chapter 3
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.
The size of d h-T by d h-0 is at most gamma times sigma-max, to the power T.
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.
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.
The curve is the per-step factor raised to the distance, on a log scale. Move sigma-max and the tanh slope.
An illustrative bound, not a measured gradient. The dashed line is 1, where the signal neither grows nor shrinks.
| Failure | Symptom | Fix |
|---|---|---|
| Exploding | the loss spikes, then turns to NaN | gradient norm clipping |
| Vanishing | the loss falls, but long dependencies are never learned | a 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()
Chapter 4
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.
h-t equals one minus z-t times h-t-minus-1, plus z-t times h-tilde-t, unit by unit.
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.
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.
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.
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.
Chapter 5
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.
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.
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.
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.
Old state [0.5, −0.2], letter b, the made-up weights in the code below.
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.
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.
Chapter 6
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)
| Property | GRU | LSTM |
|---|---|---|
| State vectors | one, h | two, c and h |
| Keep and write | tied: 1 − z and z | separate: f and i |
| Hide memory | no output gate | o hides part of c |
| State range | stays in −1 to 1 | c can grow past 1 |
| Weight blocks | 3 | 4 |
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.
params equals G times n times d, plus n squared, plus n.
Count one block: n times d, plus n squared, plus n. Multiply by the number of blocks G.
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.
Bars are weights per layer. Drag the input width d and the state width n.
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.
Chapter 7
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.
L-t equals minus the natural log of p-t at k.
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.
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.
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.
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
Green bars are the odds at this temperature. Press Sample to draw 200 times; the outlines are the tally.
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.
Chapter 8
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.
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.
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 this | Look for |
|---|---|
| Break it | the loss stalls high, near the letter-frequency line, and samples turn to noise |
| Learning rate 0.001 | slow progress in the same number of steps |
| 2 units, then 64 | the narrow state stalls higher; the wide one costs more per step |
| Temperature 0.2, then 2 | repeated 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.
Chapter 9
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.
| Combination | What it does | Cost at d = 128, n = 256 |
|---|---|---|
| Stacked, 2 layers | layer 2 reads layer 1's states | 295,680 + 393,984 = 689,664 weights |
| Bidirectional | a left-to-right and a right-to-left cell, states joined | 591,360 weights; cannot generate left to right |
| Encoder and decoder | the encoder's last state starts the decoder | one 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.
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
Teal is the GRU's fixed state. Grey is the KV cache. Drag the number of tokens.
A plain full-attention decoder with no cache compression. Grouped-query attention, lower precision and sliding windows shrink the cache.
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.
Chapter 10
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.
| Term | Meaning |
|---|---|
| Hidden state h | The vector the cell rewrites each step: its whole memory. |
| BPTT | Backpropagation over the loop written out one copy per step. |
| Truncated BPTT | Cut the gradient path every k steps; keep the state's value. |
| Jacobian | How a change in h-t-minus-1 moves h-t: D-t W-h for the Elman cell. |
| Gradient clipping | Rescale the gradient to size c when it is bigger. |
| Update gate z | Share of the candidate written (here); the unit keeps 1 − z. |
| Reset gate r | Share of the old state the candidate may read. |
| Candidate h̃ | The fresh content the cell proposes. |
| Teacher forcing | Feed the true previous character during training. |
| Temperature T | Divide the logits by T before sampling. |
| What | Number | Why it matters |
|---|---|---|
| Memoryless floor on hello | 0.693 nats per l | Same input, two targets |
| Plain RNN, 20 steps at 0.45 | 1.2 × 10−7 | Far credit vanishes |
| GRU keep path, z = 0.1, 20 steps | 0.12 | The gate lets credit survive |
| Truncate 3 steps to 2 | 7.6% off | Truncation adds bias |
| GRU against LSTM, d 128, n 256 | 295,680 against 394,240 | 3 blocks against 4 |
| Forget bias 0 against 1, 30 steps | 9.3 × 10−10 against 8.3 × 10−5 | Initialization sets the start |
| Lab baselines | 3.18 and 2.65 nats | Uniform and frequency-only |
| Decode memory at 10,000 tokens | 4 KB against 82 MB | Fixed state against KV cache |
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()
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.