Unit 5 of 7 · about 5 hours · derive, implement
Recurrent gradients, GRU and LSTM gates
Gates are the fix for the gradient pathology of the previous unit. Each gate is a differentiable decision to keep, overwrite or reveal memory.
You'll be able to
- Derive why repeated hidden Jacobians vanish or explode from their eigenvalue powers.
- Write the GRU and LSTM updates from memory and explain what each gate preserves or erases.
- Implement both cells from tensor ops and match framework cells on values and gradients.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Jacobian powers and gradient pathologyD2L - convolutional and recurrent architecture route
Backprop Through Time in Detail: the linear-recurrence gradient derivation ending in hidden-Jacobian powers. Exercises question 1: symmetric-matrix powers and what they mean for RNN gradients.
- GRU gates and scratch implementationD2L - convolutional and recurrent architecture route
Reset Gate and Update Gate, Candidate Hidden State, Hidden State, and Implementation from Scratch
- LSTM gates and scratch implementationD2L - convolutional and recurrent architecture route
Input, Forget and Output Gates, Memory Cell Internal State with , Hidden State, and Implementation from Scratch
Skip the JAX
lax.scanbranches unless you train in JAX. The equations are framework-free.
Focus on
- fans out through powers of transposed. Eigenvalues below 1 decay geometrically and above 1 grow geometrically, and tanh or sigmoid derivatives shrink most steps further.
- GRU: gates how much past state enters the candidate, and interpolates old state with candidate. LSTM splits the same job across for erase, for write and for reveal, with a separate cell .
- With and the cell holds its value exactly and gradients flow unchanged. That constant-error path is the whole point.
- PyTorch and D2L agree on the update gate: weights the old state. They differ on the reset gate: D2L multiplies into the state before , while
torch.nn.GRUapplies after the recurrent matmul and its bias, . Implement the PyTorch form when you matchtorch.nn.GRU.
Common mistakes · 3
- Porting gate formulas between sources without checking conventions. Some texts write , the opposite of D2L and PyTorch, and the reset placement differs between D2L and
torch.nn.GRU. - Assuming LSTM always beats GRU. Cost and data decide, which is why the LSTM page asks for the cost comparison.
- Treating saturated gates as a bug to tune away. Gates at 0 or 1 stop gate learning while protecting memory, so that trade is expected.
Try it yourself
Closed-book, before checking anything
torch.nn.GRU and torch.nn.LSTM outputs on random input to float32 tolerance, using the PyTorch reset-gate form for the GRU.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A linear recurrence has with spectral radius 1.5. What gradient scale results over 100 steps?Answer
About , near 4e17: explosion. Below 1 it vanishes the same way, so only near-1 spectra plus gating survive long spans.
2.GRU with everywhere under the D2L convention. What behavior results?Answer
equals : the state freezes and ignores all inputs. With the state is just the candidate, a tanh RNN whose recurrent input is gated by .
3.LSTM: which gate settings copy unchanged?Answer
and . The output gate then decides how much of shows in .
4.A GRU with a reset gate but no update gate. What breaks?Answer
Every step replaces the state with a fresh tanh candidate, so there is no copy path. Long-span memory must survive repeated multiplication by and tanh, which brings back vanishing gradients.
Practice
- TrenTorch: GRU Forward
Implement
gru_cell_forwardwithtorch.nn.GRUCell's[reset, update, new]packing; one test is aGRUCelloracleThe reset gate multiplies only the hidden-side candidate term, the PyTorch form. Then solve LSTM Forward (seq-rnn-lstm-cell-forward) in the same track, with the
[input, forget, cell, output]packing. - D2L GRU Exercises 1 and 4: gate values and single-gate ablation
Exercises: question 1 (best reset and update values to use only the input at for the output at ) and question 4 (a GRU with only a reset gate or only an update gate)
- D2L LSTM Exercise 3: gated-cell cost comparison
Exercises: question 3 (computational cost of GRU, LSTM and plain RNN at fixed hidden size, training and inference)
You're done when
Your cells match framework outputs and gradients, and the ablations show which gate carries long-span memory.
Only when you can do this without notes.
Leads to
Notes
Resources · 1 for this unit, 6 more in the section
- D2L - convolutional and recurrent architecture routeD2L authors · primary
Use why convolution, convolution layer, padding and strides, pooling, channels, batch normalization and ResNet, then RNN, BPTT, scratch RNN, GRU, LSTM, encoder-decoder and seq2seq. Work through the scratch mechanisms before concise APIs.
Also in this section
- Understanding Deep Learning - convolution and residual networksSimon J. D. Prince · required
Use Chapters 10 and 11 to sharpen convolutional invariance, receptive-field reasoning, residual paths and normalization. D2L remains the recurrent implementation route.
- Stanford CS231n - Assignments 1 and 2Stanford University · support
Use only the neural network, normalization, dropout, convolution and PyTorch components that match this section. Do not complete the course or unrelated vision tasks.
- Deep-ML candidate - convolution and recurrence problemsDeep-ML · optional
After the platform admission check, use at most one of 41 Conv2D, 62 RNN with BPTT, 287 GRU or 59 LSTM as a changed-prompt drill.
- TrenTorch - convolution cost and recurrent cellsTrenTorch · support
Solve FLOPs Estimation, GRU Forward and LSTM Forward after the D2L scratch models. Each reference cell matches torch.nn.GRUCell or LSTMCell.
- PyTorch nn.Conv2d referencePyTorch · reference
Read Signature and Shape for the exact floor formula with dilation, the groups divisibility rule with grouped and depthwise examples, and the weight layout . D2L and UDL teach the mechanism; this page is the shape contract to code against.
- PyTorch sequence packing utilitiesPyTorch · reference
Read
pack_padded_sequenceforlengths,enforce_sortedand batch-first at recognition depth: what packing skips and what contract it demands. Do not reimplement the packed format; pair it with the masked-loss implementation in D2L seq2seq.