Sequences and memory
How does a network process something that happens in order, like a sentence?
Lesson complete
If you like:
Look at this sentence: “The flowers I bought at the market are wilted.” To get “are” and not “is,” you have to remember “flowers,” which is six words back.
No voice: the lesson advances on its own with subtitles.
The voice for this lesson is being recorded: for now it advances on its own with subtitles.
Review modeComment on this stepI finished the lesson
What you will achieve
- Explain how a recurrent network reads a sequence step by step and what its hidden state holds.
- Predict what happens to the blame for the error when it travels back through many steps, and why it fades or turns erratic.
- Describe what the gates of an LSTM do (forget, write, read) and which limits still stand.
Key ideas
- A sequence is data whose order matters and whose length varies. A recurrent network reads it step by step with the same cell and passes a hidden state, its memory, from one step to the next.
- Unrolled in time, an RNN is a deep network with one layer per step and the same weights in all of them. Training it means backpropagating through time.
- The blame for the error is multiplied by a factor at every step it travels back. With factors below one it vanishes and what is far away is not learned; with large weights it turns erratic and the state saturates.
- The LSTM adds a memory belt and three learned gates (forget, input, and output, with values between zero and one). With the forget gate near one, the blame travels almost intact along the belt.
- Even so, the LSTM runs in a line (steps are not computed at once), squeezes everything into one fixed-size vector, and its useful memory is still short: those limits motivate attention.
What many people believe
Common belief A recurrent network remembers the whole sentence word by word, like a notebook.
What is true It keeps a fixed-size summary, a handful of numbers rewritten at every step, and what came early fades. The LSTM stretches that memory with gates, but it stays short.
Check yourself
Four questions. No grade, no account: they just show whether the idea stuck.
Under the hoodFor those who want the math and the code. You do not need it to follow the course.
The recurrent cell
Given an input and a state , Elman’s RNN computes
with , , and . That is parameters, the same at every step: they do not grow with the length of the sentence. To predict the next word, an output layer is added, (lesson 19). In the lesson, , , with no bias ( parameters) and random, untrained weights: only the mechanics are on display.
Blame through time
The total loss is . The blame that reaches state from step is the chain rule (lesson 8) applied along time:
It is a product of matrices. The scene shows the size of that product, (the typical gain for a nudge in a random direction; = nothing is lost). Since , if the norm of (its largest singular value) is , the product falls like an exponential: . With a sigmoid the ceiling of the derivative is and everything falls faster (lesson 8). In general, Pascanu, Mikolov, and Bengio (2013) show, for a nonlinearity with ( for tanh, for sigmoid), that is **sufficient** for the far contribution to vanish, and that is necessary for it to explode (: the largest eigenvalue of in absolute value).
With an explosion is not guaranteed: tanh saturates () and switches units off, as the scene shows, where with large weights the blame turns erratic, huge in some sentences and nearly zero in others. Two classic remedies: clip the gradient norm against explosion (Pascanu et al., 2013) and redesign the cell against vanishing. Bengio, Simard, and Frasconi (1994) add a dilemma: to store a datum stably against noise the dynamics must contract, and that makes long-term gradients vanish.
The LSTM
With gates , a candidate , and the elementwise product :
The belt is updated by addition, not by rewriting. Along it, (plus indirect paths through ), so the blame is multiplied only by the forget gate: with it arrives nearly intact, the “constant error carousel” of the 1997 paper. The original LSTM had input and output gates; the forget gate was added by Gers, Schmidhuber, and Cummins (2000). A practical trick: initialize the bias near so the belt starts open (Jozefowicz et al., 2015). A layer has parameters: four times those of the RNN. With that is . Stacked LSTMs went far: Google’s neural machine translation system (Wu et al., 2016) used eight LSTM layers in the encoder and eight in the decoder, with attention and residual connections.
In the lesson the gates are fixed numbers and there is a single cell: , , where are illustrative grammatical-number cues (plural for “flowers,” singular for “market”) and at the key word. A trained network computes and from the word and the state. In 2019, Lakretz et al. found that, in an LSTM trained as a language model, long-distance number information is largely managed by two “number units,” just what our toy cell does.
In code
import numpy as np
def influence(g, steps):
"""How much of a nudge to the initial state survives after `steps` steps (2-unit RNN with tanh)."""
c, s = np.cos(0.8), np.sin(0.8)
Wh = g * np.array([[c, -s], [s, c]]) # a 0.8 rad rotation, scaled by g
x = np.array([0.5, -0.3]) # the “word” that arrives at every step
h, P = np.zeros(2), np.eye(2)
for _ in range(steps):
h = np.tanh(Wh @ h + x)
P = ((1 - h**2)[:, None] * Wh) @ P # P = J_t · P, with J_t = diag(1 − h²) · Wh
return np.linalg.norm(P) / np.sqrt(2)
for g in (0.5, 0.9, 1.5, 2.0):
print(g, [round(float(influence(g, n)), 4) for n in (1, 5, 10, 20)])
# 0.5 [0.4266, 0.0083, 0.0001, 0.0]
# 0.9 [0.7679, 0.0989, 0.0152, 0.0004]
# 1.5 [1.2798, 0.8562, 1.218, 1.154]
# 2.0 [1.7064, 2.2703, 2.4696, 1.3574]
With or the nudge dies out; with it is amplified; around and with this fixed input there is a narrow window where it holds. A small move takes you out of it.
import math
cues = [0, 1.2, 0.3, -0.5, 0.2, -0.1, -0.9] # number cue for each word (illustrative)
def cell(f, i, o):
c = 0.0
for t, v in enumerate(cues, start=1):
gate_in = 1.0 if t == 2 else i # “flowers” opens the input gate
c = f * c + gate_in * math.tanh(v) # the belt: forget a little, write a little
return o * math.tanh(c) # what is read at the end (positive = plural)
print(round(cell(0.6, 0.8, 1.0), 3)) # -0.5 (the cue is lost and “market” wins: singular)
print(round(cell(1.0, 0.1, 1.0), 3)) # 0.638 (plural)
print(round(0.97 ** 5, 2)) # 0.86 (blame reaching “flowers” along the belt)
What comes next
The RNN and the LSTM read in a line and squeeze everything into one vector; attention (lesson 21) lets each word look directly at the others, in parallel. Before that, lesson 13 tells why deep learning took off around 2012: data, GPUs, and a few tricks, among them residual connections, which in depth play a role similar to the LSTM’s belt.
Decision lens
What this idea means if your job is to decide, not to code.
- Theoretical memory is not useful memory. When a vendor says its model “remembers the whole context,” ask for a test with texts as long as yours: LSTM language models were measured using only about two hundred words of context.
- What runs in a line costs time. A recurrent architecture processes the steps of a sequence one after another: training and response time grow with the length of the text, and the GPU is poorly used. Ask how latency scales with length.
- Sequence models remain reasonable for small problems: short time series, sensors, low-compute devices. If someone proposes an LSTM, ask why that one and not another architecture, and what data it was compared on.
- The symptom of a short memory is getting the recent right and missing what depended on something far away: agreement, references, a clause from the beginning. Design tests that put the key fact far from the question.
Terms in this lesson
- Sequence model A model that processes data whose order matters and whose length varies, such as text, audio, or time series, usually by reading it step by step.
- Recurrent neural network (RNN) A network that processes a sequence step by step with the same cell: at each step it receives the current input and the previous hidden state, and produces a new state.
- Hidden state The vector of numbers a recurrent network carries from one step to the next: its memory of what it has read so far. It is rewritten at every step.
- Vanishing gradient The phenomenon in which the gradient (the blame) is multiplied by factors below one as it travels back through many steps or layers and ends up near zero, so what is far away is not learned. With factors above one the opposite happens: the gradient explodes.
- LSTM (long short-term memory) A recurrent cell with a memory belt (the cell state) and three learned gates, forget, input, and output, that decide what is kept, what is written, and what is read. Proposed in 1997 by Hochreiter and Schmidhuber; the forget gate was added in 2000.
- Backpropagation An algorithm that computes the gradient of the loss with respect to every weight of a network in a single backward sweep, applying the chain rule layer by layer. It computes the blames; it does not move the weights (in the 1986 paper, the name covered the whole learning procedure).
- Chain rule If a quantity depends on another through a chain of steps, its total influence is the product of the influence of each step. It is the basis of backpropagation.
- Gradient The list of the slopes of the error, one for each weight. Seen as an arrow, it points to where the error rises fastest.
- Sigmoid The function σ(z) = 1/(1 + e⁻ᶻ): it turns any number into a value between 0 and 1, and equals 0.5 when z = 0.
- Activation function A function applied to the weighted sum plus the bias to produce the neuron’s output. Examples: the step and the sigmoid.
- Weight (w) In a linear model, the number that multiplies the input: the slope of the line. It tells how much the prediction rises for each unit the input grows.
- Vector An ordered list of numbers. In machine learning, each example reaches the model as a vector.
- Forward pass Computing a network’s output: the numbers move on layer by layer, from input to output.
- Layer A group of neurons that receive the same inputs and compute at the same time. A network is a chain of layers: input, one or more hidden ones, and output.
- Kernel (filter) The small grid of weights of a convolution. In a convolutional network, its values are learned during training.
Full transcript
Sources
- Elman, J. L. (1990). Finding structure in time
- Hochreiter, S. (1991). Untersuchungen zu dynamischen neuronalen Netzen (tesis de diploma)
- Bengio, Y., Simard, P., Frasconi, P. (1994). Learning long-term dependencies with gradient descent is difficult
- Hochreiter, S., Schmidhuber, J. (1997). Long short-term memory
- Gers, F. A., Schmidhuber, J., Cummins, F. (2000). Learning to forget: continual prediction with LSTM
- Pascanu, R., Mikolov, T., Bengio, Y. (2013). On the difficulty of training recurrent neural networks
- Sutskever, I., Vinyals, O., Le, Q. V. (2014). Sequence to sequence learning with neural networks
- Cho, K., van Merriënboer, B., Bahdanau, D., Bengio, Y. (2014). On the properties of neural machine translation: encoder-decoder approaches
- Jozefowicz, R., Zaremba, W., Sutskever, I. (2015). An empirical exploration of recurrent network architectures
- Wu, Y., Schuster, M., Chen, Z., Le, Q. V., Norouzi, M., et al. (2016). Google’s neural machine translation system: bridging the gap between human and machine translation
- Khandelwal, U., He, H., Qi, P., Jurafsky, D. (2018). Sharp nearby, fuzzy far away: how neural language models use context
- Lakretz, Y., Kruszewski, G., Desbordes, T., Hupkes, D., Dehaene, S., Baroni, M. (2019). The emergence of number and syntax units in LSTM language models
CommentsThis lesson’s public conversation: questions, facts to check, ideas.
Comments live in GitHub Discussions, in the course’s public repository; writing one requires a GitHub account. They load from giscus.app when you open this section. The course reviewers read them, and if a change is accepted, it is applied in both languages. Open the thread on GitHub