Neural-net foundations10 / 15

Lesson 10 · The primitives toolbox

Sequences: recurrence and attention

The problem

Two notes arrive with pizza orders:

  • "extra cheese, no onions"
  • "no cheese, extra onions"

They use the same four words, but they ask for opposite pizzas. Any model that reads text has to tell them apart. Words, sounds, prices over time and moves in a game are all sequences: the order of the items carries meaning.

The networks so far read a fixed list of numbers, with no idea of "before" and "after". This lesson shows two ways to give a network a sense of order. It can read the items one at a time with a running memory. Or it can let every item look at every other item.

Words as vectors

A network needs numbers, so give each word a vector. Here each word gets 2 numbers, small enough to draw. The first says how much the customer wants more of something; the second says how unhappy they sound.

WordVector
extra(1.0, 0.1)
cheese(0.6, 0.0)
no(−0.9, 0.3)
onions(−0.2, 0.1)

These numbers were picked by hand, so the pictures are easy to read. A real network learns a vector for every word. That's an embedding, the subject of the next lesson.

The simplest way to turn a whole note into one vector is to average its word vectors.

Predict first

Average the word vectors of 'extra cheese, no onions' and of 'no cheese, extra onions'. Can a model that sees only the average tell the two notes apart?

−1−0.500.51−0.100.10.20.30.4wants more →unhappy →extracheesenoonionsaverage
“extra cheese, no onions”“no cheese, extra onions”

Average of both notes = (0.13, 0.13)

Each arrow adds a quarter of one word. The order changes the path, not where it ends.

Each arrow adds a quarter of one word's vector. The two notes take different paths but end at the same average.

The path depends on the order; the end point doesn't. To keep the order, a network has to look at the path, not only where it ends.

Reading in order: recurrent networks

People read one word at a time, and keep a memory of what they've read so far. A network can do the same. It keeps a vector, the memory, and updates it after each word:

ht=tanh⁡(Wxxt+Whht−1+b)\mathbf{h}_t = \tanh\left(W_x \mathbf{x}_t + W_h \mathbf{h}_{t-1} + \mathbf{b}\right)

In words: the new memory ht\mathbf{h}_t (the subscript tt is the word's position, not a layer) mixes the word it has read (xt\mathbf{x}_t, through the weights WxW_x) with the old memory (ht−1\mathbf{h}_{t-1}, through WhW_h). Then tanh squashes each entry into −1 to 1. The memory starts at h0=0\mathbf{h}_0 = \mathbf{0}.

The memory vector is called the hidden state. A network built around this loop is a recurrent neural network (RNN). "Recurrent" means the same step happens again and again. The same WxW_x, WhW_h and b\mathbf{b} are used at every position. So an RNN uses weight sharing across time, the way a convolution shares its filter across an image.

For the pictures, the weights are set by hand. WxW_x is the identity matrix (copy the word in). WhW_h is half the identity (keep half of the old memory). The bias is b=0\mathbf{b} = \mathbf{0}. So each step is ht=tanh⁡(xt+0.5 ht−1)\mathbf{h}_t = \tanh(\mathbf{x}_t + 0.5\,\mathbf{h}_{t-1}).

Worked example

The first two steps of 'extra cheese, no onions'

  1. Read "extra". The memory is empty, so h1=tanh⁡((1.0,0.1)+0.5×(0,0))=(tanh⁡1.0,tanh⁡0.1)=(0.76,0.10)\mathbf{h}_1 = \tanh\big((1.0, 0.1) + 0.5 \times (0, 0)\big) = \big(\tanh 1.0, \tanh 0.1\big) = (0.76, 0.10).

Step through both notes below. Each arrow is a hidden state.

−1−0.500.51−0.200.20.40.6wants more →unhappy →extracheesenoonions
“extra cheese, no onions”“no cheese, extra onions”

Both start with an empty memory, h₀ = (0, 0).

Each step: h_new = tanh(word + 0.5 × h_old). The dotted trail shows the earlier states.

Words read 0 of 4
An RNN reads both notes word by word, with hidden states as arrows. Same words and same rule, but the two notes end in different places.

Things to notice:

  • After the first word, the two notes are far apart: one read "extra", the other "no".
  • They come closer after "cheese", but never meet. Each memory still holds half of what came before.
  • The final states differ, so a layer on top can give the two notes different answers. Averaging couldn't.

These hand-set weights favour recent words: each step keeps only half of the old memory. A trained RNN learns its own WxW_x and WhW_h, so its memory keeps whatever helps the loss, such as which food the "no" came before.

The cost is the loop itself. Word 4 can't be read until word 3 is done, so an RNN can't process a sentence's words in parallel. Information from word 1 must survive every step to reach the end.

DigressionWhy RNNs forget, and the LSTM's fixA long sentence is a deep network. Gradients shrink on the way back. · 3 min

Unroll an RNN over a 50-word sentence and it is a 50-layer network, with the same weights in every layer. To learn from word 1, the gradient has to travel back through all 50 steps. Each step multiplies it by WhW_h and by tanh's slope, which is at most 1.

That's the chain of multiplications from vanishing gradients. If each step shrinks the gradient a little, 50 steps shrink it to almost nothing. A plain RNN learns short patterns well and long ones poorly.

The long short-term memory (LSTM), from Hochreiter and Schmidhuber in 1997, adds a second memory vector, the cell. Small learned gates decide, at each step, what to forget, what to write, and how much to output. When the forget gate says "keep", the cell passes through almost unchanged, so the gradient does too. The gated recurrent unit (GRU), from 2014, is a simpler version of the same idea.

The Language and sequences course builds both.

Looking at everything at once: attention

An RNN passes information along a chain, one step at a time. Attention takes a shortcut. Every word looks directly at every other word, and they all do it at the same time.

Here's how one word, "no", looks at the note "extra cheese, no onions":

  1. Score each word. Take the dot product of "no" with each word's vector, and divide by d\sqrt{d}, where d=2d = 2 is the vector length. A big score means the two vectors point the same way, as with cosine similarity.
  2. Turn the scores into weights. Apply softmax, so the weights are positive and add up to 1.
  3. Mix. The output for "no" is the weighted sum of all the word vectors, using those weights. It's a weighted average.

This is attention. Each word gets a new vector that blends in the words it matches best.

Worked example

Attention for 'no' in 'extra cheese, no onions'

  1. Scores. "no" is (−0.9,0.3)(-0.9, 0.3). Its dot product with "extra" (1.0,0.1)(1.0, 0.1) is −0.9+0.03=−0.87-0.9 + 0.03 = -0.87. With "cheese", "no" and "onions" it's −0.54-0.54, 0.900.90 and 0.210.21. Divide each by 2≈1.414\sqrt{2} \approx 1.414: the scores are −0.615-0.615, −0.382-0.382, 0.6360.636 and 0.1480.148.

Tap any word in the matrix below to see its weights and output.

Attention weights (tap a word)

extracheesenoonionsextra.41.31.11.18cheese.35.29.15.21no.13.16.44.27onions.22.23.29.26

Output for “no”

−1−0.500.51−0.200.20.40.6wants more →unhappy →extracheesenoonionsoutput

0.13 × extra + 0.16 × cheese + 0.44 × no + 0.27 × onions

output for “no” = (−0.23, 0.17)

Thicker blue lines mean bigger weights. Switch notes: each word’s output stays the same.

Attention on one note. Row i of the matrix holds word i's weights over all four words; each row adds up to 1. The plot shows the selected word's output, a weighted average of the word vectors.

Things to notice:

  • "no" gives its biggest weight to itself, then to "onions", the word that points most nearly the same way. The words "extra" and "cheese" point away from it, so they get little.
  • Every word reaches every other word in one step. "onions" sees "extra" directly, no matter how far apart they are, with no long chain to forget along.
  • All four rows can be computed at once, so attention runs in parallel. That's a big reason it took over from RNNs on long texts.
  • Switch notes. The matrix rows and columns move, but each word's weights and output stay exactly the same. On its own, attention can't see the order.

The maths

Stack the word vectors as the rows of a matrix XX, one row per word. Then all of attention is three lines:

S=XX⊤/devery pair’s scoreA=softmax⁡(S)softmax along each rowoutput=AXeach row: a weighted average of the rows of X\begin{aligned} S &= X X^\top / \sqrt{d} && \text{every pair's score} \\ A &= \operatorname{softmax}(S) && \text{softmax along each row} \\ \text{output} &= A X && \text{each row: a weighted average of the rows of } X \end{aligned}

Read it back: row ii of SS holds word ii's scores against every word, which is the matrix in the figure before softmax. AA is the matrix in the figure. Row ii of AXAX is the output arrow when you tap word ii.

Here every word plays three roles. It asks (its own row of scores), it gets matched (the other side of each dot product), and it is the content that gets mixed. The Transformers course gives each role its own learned weights, called queries, keys and values. That lets a word look for something other than itself.

DigressionAttention has no sense of order on its ownSwap the words and each one gets the same output. Transformers fix this by adding position to each word. · 2 min

The figure shows the problem. Swap "extra" and "no", and each word's output is unchanged. Each output depends only on which words are in the note, not where they are. So attention alone can't tell the two notes apart, and nor can the average.

The fix is to put the position into each word's vector before attention runs. The original transformer, from 2017, added a pattern of sine and cosine waves to each word's vector, a different pattern for each position. Many newer models use other schemes. Either way, "no" in position 1 and "no" in position 3 now have different vectors, so they get different scores.

The Transformers course covers how this works.

In PyTorch

The RNN is a loop with one line inside. Each word vector x_t has shape (2,), and so does the hidden state h.

An RNN, written by hand
# The lesson's hand-picked weights: copy each word in, keep half of the old memory.
W_X = torch.eye(2)  # (d_in, d_hidden)
W_H = 0.5 * torch.eye(2)  # (d_hidden, d_hidden)
B = torch.zeros(2)  # (d_hidden,)


def rnn(x: torch.Tensor, w_x: torch.Tensor = W_X, w_h: torch.Tensor = W_H, b: torch.Tensor = B) -> torch.Tensor:
    """Read x (seq_len, d_in) one row at a time. Returns every hidden state, (seq_len + 1, d_hidden)."""
    h = torch.zeros(w_h.shape[0], dtype=x.dtype)  # h0: an empty memory
    states = [h]
    for x_t in x:  # the same weights at every step
        h = torch.tanh(x_t @ w_x + h @ w_h + b)  # (d_hidden,)
        states.append(h)
    return torch.stack(states)

The code writes x_t @ w_x, with the word as a row vector on the left, which is the PyTorch habit. The maths above writes WxxtW_x \mathbf{x}_t. The two are the same up to a transpose of the weights. With this lesson's weights (multiples of the identity), the transpose changes nothing.

Attention is the three lines from the maths, with shapes. q, k and v are all the same matrix of word vectors here, with shape (4, 2).

Attention in three lines
def attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """Dot-product attention. q, k, v: (seq_len, d). Returns the outputs (seq_len, d) and weights (seq_len, seq_len)."""
    d = q.shape[-1]
    scores = q @ k.T / d**0.5  # (seq_len, seq_len): row i = how well word i matches each word
    weights = scores.softmax(dim=-1)  # each row adds up to 1
    return weights @ v, weights  # (seq_len, d): each output is a weighted average of the rows of v

scores.softmax(dim=-1) is softmax along each row, so each word's weights add up to 1.

You won't write these loops in practice. PyTorch has both as built-in layers:

The same, with PyTorch's layers
def library_versions(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """The same two computations with PyTorch's built-in layers. x: (seq_len, 2)."""
    layer = nn.RNN(input_size=2, hidden_size=2, batch_first=True, dtype=x.dtype)
    with torch.no_grad():  # load the lesson's weights; nn.RNN stores them as (out, in)
        layer.weight_ih_l0.copy_(W_X.T)
        layer.weight_hh_l0.copy_(W_H.T)
        layer.bias_ih_l0.copy_(B)
        layer.bias_hh_l0.zero_()
    all_h, last_h = layer(x[None])  # (1, seq_len, 2) every state, (1, 1, 2) the last one
    attn_out = F.scaled_dot_product_attention(x[None], x[None], x[None])  # (1, seq_len, 2)
    return all_h[0], attn_out[0]
  • nn.RNN runs the loop for you over a whole batch. It stores its weights as (out, in), the transpose of the hand-written version, and has two biases that add together. nn.LSTM and nn.GRU are drop-in replacements with gates.
  • F.scaled_dot_product_attention(q, k, v) (from torch.nn.functional) computes the same three lines, with a fast kernel on GPUs.

The test file checks that the loop matches nn.RNN and the three lines match F.scaled_dot_product_attention. The Language and sequences and Transformers courses use them properly.

Common misconceptions

"An average of word vectors keeps some of the order." It keeps none. Adding is the same in any order, so every rearrangement of the same words gives the same average.

"An RNN has a separate set of weights for each word position." It has one set, used at every step. That's why it can read a sequence of any length.

"Attention knows which word comes first." Not by itself. Swap two words and each word's output stays the same. Position has to be added to the word vectors.

"Attention weights are learned numbers stored in the network." They're computed fresh for every input, from dot products between its words. Change the note and the weights change. What's learned (in the Transformers course) are the matrices that make the queries, keys and values.

Recap

  • In a sequence, order carries meaning. Averaging the items, a bag of words, throws the order away.
  • An RNN reads one item at a time and updates a hidden state with the same weights at each step: ht=tanh⁡(Wxxt+Whht−1+b)\mathbf{h}_t = \tanh(W_x \mathbf{x}_t + W_h \mathbf{h}_{t-1} + \mathbf{b}). Its final state depends on the order.
  • RNNs read step by step, so they're slow to run in parallel, and over long sequences their gradients fade.
  • Attention lets every item score every other item (dot products, then softmax) and output a weighted average of them. All items do this at once.
  • Attention alone ignores order, so models that use it add position to each item.
  • PyTorch names used: torch.tanh, Tensor.softmax, nn.RNN, nn.LSTM, nn.GRU, F.scaled_dot_product_attention.
  • The Language and sequences course goes deeper into RNNs and LSTMs; the Transformers course builds on attention.