12 / 37 · Neural Sequence Models
Recurrent neural networks
A network that reads one token at a time and carries a hidden state has unbounded context in principle and a parameter count independent of length; it can classify a sequence from its last state or predict the next token at every step. Gradients through many steps vanish or explode, which limits what the context can actually hold.
CNNs for text classification · N-gram language models · Backpropagation
On this page 9
The convolutional classifier of the previous note sees a window of tokens and forgets position at pooling. The n-gram language model of the earlier note sees tokens and cannot generalize across them. Both have a context of fixed, small size. This note introduces a model whose context is, in principle, the entire prefix: it reads tokens in order and keeps a summary in a vector that it updates at every step.
Notation. Input token vectors ; hidden states ; outputs . Weight matrices , , and biases . is the element-wise product.
The recurrence#
reads the current token, carries the previous state forward, and keeps every coordinate of in . The same are used at every step, so the parameter count is whatever is: a sequence of 5 tokens and one of 500 run the same cell 5 or 500 times. Unrolled over time, the computation is a chain of identical cells with the hidden state as the only connection between them.
Shapes for a batch: input , hidden states , final state . The PyTorch module nn.RNN(d, H, batch_first=True) returns both the full sequence of states and the last one.
Worked example#
Scalar case, , , , , inputs :
| 1 | 1 | ||
| 2 | 0 | ||
| 3 | 0 |
The input at step 1 is still visible in , attenuated by per step and by the . With instead, the same input would grow: , , saturating at the edge of ‘s range. The recurrent weight decides whether the past fades or floods, and it is the same weight at every step, so whatever it does, it does times.
Step by step#
One step of a recurrent network: what goes where
The numbers in the figure follow one application of the cell:
- Read the input. is what the current token contributes, a vector of numbers.
- Read the memory. is what the previous state contributes; at the first step and the term vanishes.
- Add. The two vectors and the bias are summed coordinate by coordinate.
- Squash. maps every coordinate into ; the result is the new state .
- Predict, if needed. gives scores over the classes or over the vocabulary, and a softmax turns them into probabilities.
- Pass the state on. becomes the of the next step, which repeats steps 1–5 with the same , and .
The models of the following notes keep this skeleton, a state carried from step to step and updated from the current input, and each changes one piece of it. The LSTM changes how the state is updated, seq2seq hands the final state from one network to another, attention lets the second network look back at every state of the first, and self-attention drops the chain altogether. Their figures use the same colours: green for inputs, blue for states, amber for weights and gates, red for outputs, and an amber outline for what a model adds to the previous one.
Two ways to use the states#
One recurrence, two ways to use its states
RNN as a classifier#
Read the whole document and use the last state as its representation: . Unlike max-pooling, is computed in order, so it can in principle distinguish not good from good not. In the AG News setting of the previous note, a one-layer GRU (a gated cell from the next note) with reads the same 100-dimensional Word2Vec vectors and feeds its last state to a linear layer. It has parameters, comparable to the convolutional models.
One practical point. The last state of a padded sequence is the state after the padding tokens, not after the last real one. Either pack the sequences so the recurrence stops at the true length, or feed the padding at the start, or read the state at index length - 1 per example.
RNN as a language model#
Produce an output at every step and make it a distribution over the vocabulary:
This is the chain-rule factorization of the n-gram note with the Markov assumption removed: the conditional depends on , which depends on the whole prefix. Training uses teacher forcing: the input sequence is the text shifted by one, , the targets are , and the loss is the cross-entropy summed over positions, which is exactly the per-token negative log-likelihood whose exponential is the perplexity. Padding positions are excluded from the loss with ignore_index. At generation time the model’s own sample is fed back as the next input, as in every autoregressive model.
Shapes: ids → embeddings → states → logits . The cross-entropy is computed on the flattened logits against targets.
Take a model over a BPE vocabulary of tokens with and : it has 9.6 M parameters in the input embedding, 0.39 M in the recurrent cell, and 19.3 M in the output layer, 29.3 M in total. Two thirds of the model is the output softmax, the same cost structure that drove negative sampling in Word2Vec; for a language model the full softmax is kept because the distribution itself is the output. The GPT note returns to neural language-model perplexities with a Transformer.
Gradients through time#
Training unrolls the recurrence and backpropagates through every step. The gradient of the loss at step with respect to the state at step passes through applications of the cell:
Each factor is the same scaled by the derivative of (at most 1). If the largest singular value of is below 1 the product shrinks geometrically and the gradient vanishes: the loss at the end of a sentence cannot adjust what the cell did at its start. If it is above 1 the product can grow, and the gradient explodes (Pascanu, Mikolov and Bengio, 2013 show that this condition is necessary, not sufficient). With a scalar recurrent weight and states in the linear part of , where its derivative is close to 1, fifty steps multiply the gradient by . The figure below, shared with the Generative Models note where the computation is written out, shows the mechanism.
Unrolled RNN with recurrent weight w = 2
Two consequences for practice. Gradient clipping rescales the gradient vector when its norm exceeds a threshold, such as 1.0, which stops explosions from destroying the weights but does nothing for vanishing. And vanishing is the binding constraint: a plain RNN learns dependencies over a handful of tokens and loses the rest, which is why “context is the whole prefix” is true of the forward pass and not of what the model learns (Bengio, Simard and Frasconi, 1994). The next note changes the cell so that the state has an additive path with a gradient factor near 1.
What changed#
| CNN classifier | N-gram LM | RNN | |
|---|---|---|---|
| Context | tokens per filter | tokens | Whole prefix (in principle) |
| Parameters vs length | Independent | Table grows with data | Independent |
| Position | Lost at pooling | Last only | Encoded in state order |
| Generalizes across tokens | Yes (embeddings) | No | Yes |
| Generation | No | Yes | Yes, with -way output |
| Parallel over | Yes | — | No: needs |
Limitations#
- Short effective memory. Gradients vanish over tens of steps; the state cannot be trained to keep information for long.
- Sequential computation. Step waits for step , so an RNN cannot use a GPU’s parallelism along the sequence. Training time grows linearly with per example, and the Transformer note will make this the central argument against recurrence.
- One state for everything. A single vector must summarize the whole input. For classification that is adequate; for translating a 30-word sentence it is the bottleneck that the seq2seq note runs into.
- Padding interacts with the last state. Variable lengths need packing or masking that the convolutional model did not.
What you should remember#
- : the same cell at every step, parameters independent of length, state carries the prefix.
- Classifier: last state → linear. Language model: every state → softmax over , trained by teacher forcing on the shifted sequence with padding ignored.
- The gradient through steps is a product of copies of ; it vanishes or explodes geometrically. Clipping handles explosion only.
- Recurrence is sequential: no parallelism along the sequence.
Notebook#
Two notebooks. Cell numbers count every cell, markdown included, from 1. Quoted numbers come from the run saved with the course; cells changed since then for current library versions have no saved output.
week02_NN_text_classification.ipynb, cells 40–43: SimpleRNN wraps nn.GRU(100, 128, batch_first=True) and a linear layer on the last hidden state, trained with the same loop as the convolutional models for 5 epochs. The final printout is absent from the saved outputs, so the course has no accuracy to compare this GRU with the convolutional classifiers and the TF-IDF baseline. The classifier takes the final state after the padding tokens rather than after the last real token, the simplification discussed under RNN as a classifier.
- Cells 46–49 BPE-tokenize the joke corpus and build a 37,580-entry vocabulary with fixed ids for
<pad>(0) and<unk>(1). - Cell 51 builds batches: each joke is cut to 128 tokens, inputs are
s[:-1], targetss[1:], both padded with 0. - Cell 52 defines
SimpleRNNLM:nn.Embedding(V, 256, padding_idx=0),nn.RNN(256, 512, batch_first=True),nn.Linear(512, V), the 29.3 M-parameter model counted in RNN as a language model. - Cell 53 runs one epoch: cross-entropy with
ignore_index=0, gradient-norm clipping at 1.0, and perplexity as of the token-weighted mean loss (set to above a loss of 20 to avoid overflow). Cell 55 trains for three epochs with AdamW at and batches of 64; the run saved with the course was interrupted after a few batches, so there are no saved perplexities. The softmax over 37,580 tokens makes this cell practical only on a CUDA GPU, as the markdown cell before it says.
Next#
The recurrence gives the model a memory and the gradient takes it away. The next note keeps the recurrence and redesigns the cell: a separate memory line that is updated additively and gates that decide what to write, keep and read, so that the gradient along the memory line is a product of factors close to 1 rather than of .
References#
- J. L. Elman. Finding Structure in Time. Cognitive Science, 14(2), 1990. The simple recurrent network.
- Y. Bengio, P. Simard, P. Frasconi. Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks, 5(2), 1994.
- R. Pascanu, T. Mikolov, Y. Bengio. On the difficulty of training recurrent neural networks. ICML, 2013. The product-of-Jacobians analysis and gradient clipping.
- T. Mikolov, M. Karafiát, L. Burget, J. Černocký, S. Khudanpur. Recurrent neural network based language model. Interspeech, 2010.
- I. Goodfellow, Y. Bengio, A. Courville. Deep Learning. MIT Press, 2016. Chapter 10 (sequence modelling, teacher forcing, long-term dependencies).