Lesson 3.1: Why averaging the past is not enough
See why a plain average of earlier tokens fails, how fixed weights per distance help, and where only content-based weights work. This sets up attention.
By the end of this lesson you will be able to compute a running average of the tokens so far in three equivalent ways (a loop, a matrix and a masked softmax), explain what an average throws away, train a model that mixes the past with fixed weights and measure how well it does, and describe the task that no fixed weights can solve. You will show that the three ways of averaging agree exactly, that a plain average of the whole window makes the model worse than a bigram (validation loss 1.331 against 1.1615), that learning one fixed weight per distance brings it to 1.0095 against a floor of 0.988, and that on a lookup task where the answer sits in a different place each time, fixed weights score 42% against a chance level of 25%, while the model of Lesson 3.2 scores 100%. You need Python and NumPy, and the code from Lessons 1.1 and 2.3.
Module 2 ended with a stream of token ids, turned into vectors and cut into batches. The model of Lesson 1.4 used only the current token to predict the next one. Its validation loss was 1.1615 and could not fall further, because one word of context cannot tell a subject from an object. Lesson 1.1 showed that two words of context do much better: a trigram table reached 0.992, close to the best any model can do on this language (0.988). But a table of contexts grows as 34 to the power of the number of words of context, and it cannot generalise. A real model needs a way to use many earlier tokens at once, without a table. This module builds that way. This lesson explains why the obvious first idea is not enough, and what the answer must look like.
The simplest idea: average the past
We have a vector for every token. To predict the next token from many earlier ones, the simplest move is to combine their vectors into one and use that. The simplest combination is the mean. At position t we take the mean of the vectors at positions 0, 1, ..., t. This is sometimes called a bag of words, since it forgets the order. Here is the same operation three ways. They are worth seeing together, because the third is the one that becomes attention.
First save the helper code that the whole module uses as helpers.py. It rebuilds the data of Module 2, and adds a softmax, the batch loader of Lesson 2.4, the sinusoidal positions of Lesson 2.3 and an optimiser. The optimiser is Adam. Lesson 5.2 explains it. For now treat it as gradient descent that adapts the step size of every number separately.
python
import numpy as np
from corpus import makecorpus
words = makecorpus().split()
vocab = sorted(set(words))
V = len(vocab) # 34
stoi = {w: i for i, w in enumerate(vocab)}
ids = np.array([stoi[w] for w in words])
cut = int(0.9 len(ids))
trainids, valids = ids[:cut], ids[cut:]
def softmax(z, axis=-1):
z = z - z.max(axis=axis, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=axis, keepdims=True)
def getbatch(data, batch, block, rng):
starts = rng.integers(0, len(data) - block, size=batch)
x = np.stack([data[s : s + block] for s in starts])
y = np.stack([data[s + 1 : s + block + 1] for s in starts])
return x, y
def sinusoidal(T, d):
pos = np.arange(T)[:, None]
i = np.arange(0, d, 2)[None, :]
angle = pos / (10000 (i / d))
P = np.zeros((T, d))
P[:, 0::2] = np.sin(angle)
P[:, 1::2] = np.cos(angle)
return P
class Adam:
"""Gradient descent with a running average of the gradient and of its square (Lesson 5.2)."""
def init(self, params, lr):
self.p, self.lr, self.t = params, lr, 0
self.m = {k: np.zeroslike(v) for k, v in params.items()}
self.v = {k: np.zeroslike(v) for k, v in params.items()}
def step(self, grads):
self.t += 1
for k, p in self.p.items():
g = grads[k]
self.m[k] = 0.9 self.m[k] + 0.1 g
self.v[k] = 0.999 self.v[k] + 0.001 g g
mh = self.m[k] / (1 - 0.9 self.t)
vh = self.v[k] / (1 - 0.999 self.t)
p -= self.lr mh / (np.sqrt(vh) + 1e-8)
Now the three ways.
python
from helpers import
T = 4
rng = np.random.defaultrng(0)
X = rng.standardnormal((T, 3)) # four tokens, three numbers each
1. a loop: the mean of everything up to and including position t
loop = np.stack([X[: t + 1].mean(axis=0) for t in range(T)])
2. a matrix: row t holds 1/(t+1) in columns 0..t and 0 after
W = np.tril(np.ones((T, T)))
W = W / W.sum(axis=1, keepdims=True)
print(np.round(W, 3))
print(np.allclose(loop, W @ X)) # True
3. a softmax: start from all-zero scores, block the future, normalise
mask = np.tril(np.ones((T, T)))
scores = np.where(mask == 0, -np.inf, 0.0)
W2 = softmax(scores)
print(np.allclose(W, W2)) # True
print(np.allclose(loop, W2 @ X)) # True
order blindness (Lesson 2.3)
rng = np.random.defaultrng(0)
d = 8
E = rng.standardnormal((V, d)) 0.1
a = [stoi[w] for w in "the dog chased the cat".split()]
b = [stoi[w] for w in "the cat chased the dog".split()]
print(np.allclose(E[a].mean(axis=0), E[b].mean(axis=0))) # True
The first uses a loop and is easiest to read. The second builds a matrix W with row t holding the weights that position t gives to each position. The row for position 2 is [0.333, 0.333, 0.333, 0]: equal weight on the three tokens so far, none on the future. A single matrix product W @ X produces every running mean at once. The third starts from all-zero scores, sets the scores of future positions to minus infinity, and applies a softmax to each row. A softmax of equal numbers gives equal weights, and exp(-inf) is zero, so the future gets exactly nothing. All three agree, and the output of the last three lines is True.
The last four lines repeat a point from Lesson 2.3: the mean of the vectors for "the dog chased the cat" equals the mean for "the cat chased the dog". An average cannot tell who chased whom.
The third way is the important one. In it, the weights are not written down. They come out of a softmax over scores, and the scores can be anything. Today they are all zero. Soon they will be numbers computed from the tokens.
What an average throws away
An average loses two things.
Order. Swapping words changes nothing, as the check above showed. For a language where "the dog chased the cat" differs from "the cat chased the dog", that is fatal unless something else carries position. Lesson 2.3 added position vectors to the token vectors for this reason, and we will use them. But averaging after adding positions still blurs them together.
Sharpness. In a mean over n tokens, each token has weight 1 divided by n. With a window of 16, the token that matters most counts for 6.25% of the result, and the 15 that do not count for 93.75%. The informative signal is diluted by noise, and the dilution grows with the window.
An experiment: three ways to mix the past
Let us measure. We train three small models on the toy language. Each one turns a window of 16 tokens into one context vector per position, and predicts the next token from it with a linear layer. They differ only in how they mix.
bigram: use only the current token. This is the model of Lesson 1.4, with an embedding layer.
uniform: the plain running mean of everything so far.
offset: a weighted sum in which the weight depends only on the distance back. The weight for the current token, the previous token, two tokens back and so on are numbers a[0], a[1], a[2], ... that the training learns. They are the same at every position and for every input.
python
from helpers import
T, d = 16, 16
def causalmean(T):
A = np.tril(np.ones((T, T)))
return A / A.sum(axis=1, keepdims=True)
def mix(kind, X, a=None):
"""X has shape (batch, T, d). Return the context vector for every position."""
if kind == "bigram": # only the current token
return X
if kind == "uniform": # plain average of everything so far
return np.einsum("ts,bsd->btd", causalmean(X.shape[1]), X)
C = np.zeroslike(X) # 'offset': a learned weight per distance back
for o in range(X.shape[1]):
C[:, o:, :] += a[o] X[:, : X.shape[1] - o, :]
return C
def trainmixed(kind, steps=3000, lr=0.01, seed=0):
rng = np.random.defaultrng(seed)
p = {"E": rng.standardnormal((V, d)) 0.1, "U": rng.standardnormal((d, V)) 0.1}
if kind == "offset":
p["a"] = np.zeros(T); p["a"][0] = 1.0 # start by looking only at the current token
opt = Adam(p, lr)
for step in range(steps):
x, y = getbatch(trainids, 32, T, rng)
X = p["E"][x]
C = mix(kind, X, p.get("a"))
P = softmax(C @ p["U"])
dZ = P.copy()
dZ[np.arange(32)[:, None], np.arange(T)[None, :], y] -= 1
dZ /= 32 T
g = {"U": np.einsum("btd,btv->dv", C, dZ)}
dC = dZ @ p["U"].T
if kind == "bigram":
dX = dC
elif kind == "uniform":
dX = np.einsum("ts,btd->bsd", causalmean(T), dC)
else:
dX = np.zeroslike(X); g["a"] = np.zeros(T)
for o in range(T):
dX[:, : T - o, :] += p["a"][o] dC[:, o:, :]
g["a"][o] = np.sum(dC[:, o:, :] X[:, : T - o, :])
g["E"] = np.zeroslike(p["E"]); np.add.at(g["E"], x, dX)
opt.step(g)
return p
def valloss(p, kind, n=400, seed=123):
x, y = getbatch(valids, n, T, np.random.defaultrng(seed))
P = softmax(mix(kind, p["E"][x], p.get("a")) @ p["U"])
return -np.log(P[np.arange(n)[:, None], np.arange(T)[None, :], y]).mean()
for kind in ("bigram", "uniform", "offset"):
p = trainmixed(kind)
print(kind, round(valloss(p, kind), 4))
if kind == "offset":
print(np.round(p["a"][:6], 2))
The lesson's numbers come from this code. Because it uses random batches, rerunning with another seed will change the last digit or two.
Model · Validation lossPlain running mean · 1.331
Bigram (current token only) · 1.1615
Learned weight per distance · 1.0095
Trigram table (Lesson 1.1) · 0.992
Best possible (Lesson 1.1) · 0.988
Two things stand out.
A plain average is worse than a bigram. The model with more information does worse, because the information is blended into a mush. The current token is the most important single input, and in a mean over 16 tokens it is a small part of the whole. This is the dilution problem in numbers.
A weight per distance is much better. With learned weights the model reaches 1.0095, close to the trigram. Look at what it learned:
[ 1.67 0.83 -0.42 -0.02 -0.19 -0.04 ]
The current token gets a weight of 1.67, the previous token 0.83, the one before it minus 0.42, and everything further back almost nothing. The model has found that this language needs the last two or three words, and has switched the rest off. A negative weight is allowed, since these are weights in a sum and not probabilities: it means "the third word back argues against whatever its vector suggests". That is why the model can do almost as well as a trigram. The mixing is no longer an average. It is a weighted sum, with the weights chosen by training.
This is a real step forward, and it uses nothing but what we have. It also hides a limit, which comes from the language we chose. In the toy language, what you need to know is always the same distance back: the previous word or two. A fixed weight per distance suits that.
Where fixed weights break
Real language is not like that. The word you need may be one token back, or forty. In "The keys that she left on the table yesterday were", the verb must agree with "keys", seven words earlier. In another sentence the matching word is three tokens back. No fixed weight for a given distance can serve both.
We can build the smallest case of this problem and test it. Each example holds four pairs, each a key and a value written as one token (key times 8 plus value), then a query: one more token, naming a key. The answer is the value that was paired with that key. The pair we need is in a different place each time, and which one it is depends on the query.
python
from helpers import
Four (key, value) pairs, each a single token key8 + value; then a query token 64 + key.
# The answer is the value (0..7) that was paired with the queried key.
def makelookup(n, rng):
X = np.zeros((n, 5), dtype=int); y = np.zeros(n, dtype=int)
for i in range(n):
keys = rng.permutation(8)[:4]
vals = rng.integers(0, 8, 4)
q = rng.integers(0, 4)
X[i, :4] = keys 8 + vals
X[i, 4] = 64 + keys[q]
y[i] = vals[q]
return X, y
X, y = makelookup(3, np.random.defaultrng(0))
print(X); print(y)
def trainfixed(learnweights, steps=3000, lr=0.01, d=16, seed=0):
rng = np.random.defaultrng(seed)
p = {"E": rng.standardnormal((72, d)) 0.1, "U": rng.standardnormal((d, 72)) 0.1}
if learnweights:
p["a"] = np.full(5, 0.2)
opt = Adam(p, lr)
wof = lambda p: p["a"] if learnweights else np.full(5, 0.2)
for step in range(steps):
x, y = makelookup(64, rng)
Xe = p["E"][x]
C = np.einsum("s,bsd->bd", wof(p), Xe) # one fixed-weight average per example
P = softmax(C @ p["U"])
dZ = P.copy(); dZ[np.arange(64), y] -= 1; dZ /= 64
g = {"U": C.T @ dZ}
dC = dZ @ p["U"].T
g["E"] = np.zeroslike(p["E"])
np.add.at(g["E"], x, wof(p)[None, :, None] dC[:, None, :])
if learnweights:
g["a"] = np.einsum("bd,bsd->s", dC, Xe)
opt.step(g)
x, y = makelookup(2000, np.random.defaultrng(999))
C = np.einsum("s,bsd->bd", wof(p), p["E"][x])
return (softmax(C @ p["U"]).argmax(axis=1) == y).mean()
print("equal weights: ", trainfixed(False))
print("learned weights:", trainfixed(True))
The first lines print three examples. In the first, the pairs are 17, 38, 29, 55. The token 17 is key 2 with value 1, and 38 is key 4 with value 6. The query token is 67, which is 64 plus 3: it asks for key 3. The pair for key 3 is 29, whose value is 5. The answer in y is 5.
We train two models that use a weighted sum of the five tokens' vectors. One uses equal weights and one learns five weights, one per position. Chance, if the model could find the four values present and pick one, is 25%. The results:
equal weights: 42.0% correct
learned weights: 41.4% correct
Both are far from perfect. The reason is that the weights are fixed before the model sees the query. The right pair is in position 0 in one example and position 3 in the next. A fixed weight on position 0 helps one case and hurts another. The best a fixed sum can do is to sum up what is there and guess among the values present, and the extra accuracy over 25% comes from partial clues in the vectors.
What the task needs is the opposite: weights that depend on the query and on the content of each position. For each example the model must put most of its weight on the pair whose key matches the query, wherever that is, and almost none elsewhere.
What we want: scores from the content
Go back to the third way of computing an average. The weights were a softmax over scores, and we set every score to zero. If the scores come from the tokens instead, the weights follow the content. A token whose score is high gets a large weight, and a token whose score is low gets a small one. Write g for how much higher the score is for the tokens that matter than for the others. With n tokens in the window, k of which matter, the share of the weight on the tokens that matter is
k times e to the power g, divided by (k times e to the power g, plus n minus k).
With n = 16 and k = 1, a plain average gives the one token that matters 6.25% of the weight. If its score is higher by 3, the softmax gives it e³ = 20.1 against 15 for the rest: 57.3%. With a gap of 6, it gives e⁶ = 403.4 against 15: 96.4%. A gap of 6 in the scores gives nearly all the weight to the right token and almost none to the rest, in a window of any size. That is the lever: a modest difference in scores turns a diluted average into a sharp lookup.
Predict first: a window has 16 tokens, and one of them matters. If the scores are all equal, the token gets 6.25% of the weight. If its score is higher than the others by 3, roughly what share does it get? Decide before running the simulator.
The last line of the simulator hints at a problem we will meet in Lesson 3.2: as the window grows, the scores have to become larger to keep a sharp focus.
We have the plan. A model that uses a softmax over scores computed from the content can focus on the right tokens, wherever they are. The scores must come from the tokens themselves, in a form that training can adjust. The next lesson builds exactly that, from three small matrices, and shows it solving the lookup task that fixed weights could not: 100% on the same test.
What the model has now, and what it lacks
Let us take stock of what these experiments gave.
A running mean, written as a lower-triangular matrix times the vectors, or as a masked softmax of zeros. These are the same thing.
Fixed weights per distance, which already beat a bigram and match a trigram on a language whose structure sits at fixed distances.
A clear failure: when the place of the needed token changes, fixed weights cannot follow.
A clear remedy: scores that depend on the content, passed through the same masked softmax.
Notice also what the two good ideas have in common. Both use a matrix of weights with one row per position, a lower-triangular shape and rows that add to one. In the fixed-weight model, the matrix is built from five or sixteen numbers. In attention, it will be built from the tokens. The shape of the rest of the computation will not change.
Key takeaways
A running mean of the vectors up to each position can be computed by a loop, by a lower-triangular matrix with rows that sum to one, or by a softmax over zero scores with the future set to minus infinity. All three agree. The third is the one that becomes attention.
An average loses order and dilutes the token that matters: in a window of 16 it gives each token 6.25%.
A plain average of the whole window makes the model worse than a bigram: validation loss 1.331 against 1.1615.
A learned weight per distance back brings the loss to 1.0095, near the trigram (0.992) and the best possible (0.988). The weights it found were 1.67, 0.83 and minus 0.42 for the current token and the two before.
On a lookup task whose answer is in a different place each time, fixed weights score 42.0% and 41.4% (chance among the four values is 25%).
A softmax over scores that depend on the content can concentrate weight where it is needed: a score gap of 3 gives one token in 16 a share of 57.3%, and a gap of 6 gives 96.4%.
The matrix of weights (lower-triangular, rows summing to one) is the shared shape. Attention differs only in where the weights come from.
Common mistakes
Averaging over the whole window and expecting more context to help. Dilution can make a model with more context worse than one with less.
Forgetting the future. A running mean at position t must use only positions 0 to t. A full-window mean leaks the answer, as Lesson 3.3 shows.
Reading negative weights as an error. A weighted sum may use them, and a trained model does. They are not probabilities.
Concluding that fixed weights are useless. They matched a trigram here, because this language has structure at fixed distances. They fail when the position of the useful token varies.
Using minus infinity carelessly. A whole row of minus infinity gives NaN in a softmax. In a causal mask each row keeps at least the diagonal.
Comparing losses from different windows. Report the loss over a fixed validation set of the same window length.
Check yourself
1. Write the matrix that gives the running mean for a window of three tokens.
Row 0 is [1, 0, 0], row 1 is [0.5, 0.5, 0], row 2 is [1/3, 1/3, 1/3].
2. Why does a softmax over all-zero scores give equal weights?
Every score gives the same exponential, so each weight is that exponential divided by the sum of equal terms, which is 1 over the count.
3. In a plain average of 20 tokens, what weight does one token get?
1 divided by 20, which is 5%.
4. A window has 32 tokens, one of which matters, and its score is higher than the others by 4. What share of the weight does it get?
e⁴ = 54.6 against 31 for the others, so 54.6 ÷ 85.6 = 63.8%.
5. Why did the learned weight per distance work on the toy language but fail on the lookup task?
In the toy language the useful tokens are always the last two or three, a fixed distance back. In the lookup task the useful pair is in a different place each time, so no fixed weight can be right.
6. Why must row t of a causal weight matrix be zero for columns after t?
Position t must not use tokens that come after it. Using them would let the model see the answer it is meant to predict.
Try this
Set aside ninety minutes. You need Python, NumPy and helpers.py.
1. Type in the three ways of computing the running mean. Try a window of 6 and check all three agree with np.allclose.
2. Change the scores in the third way from zeros to [0, 0, 2, 0] for every row before masking. Print the matrix. Which token gets the most weight in each row, and what happens in rows 0 and 1, where that position is in the future?
3. Train the three mixing models for 3,000 steps with a different seed. How much do the three losses move? Is the order the same?
4. Change the window T from 16 to 4 and to 64 for the uniform and offset models. What happens to each?
5. Print the learned offset weights a for the offset model. Add weight decay (Lesson 5.2 explains it) and see whether the small weights shrink to zero.
6. Run the lookup experiment with five pairs instead of four. What accuracy do the fixed-weight models reach, and what do you expect chance to be?
A good result is three running means that agree to many digits, a table of losses like the one above and a clear idea of the task fixed weights cannot do. The next lesson computes the scores from the content, and trains the model that solves it.
Read more
Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio, "Neural Machine Translation by Jointly Learning to Align and Translate" (2014), introduced the idea of weighting positions by learned scores. Andrej Karpathy's lecture "Let's build GPT: from scratch, in code, spelled out" builds the running mean in the same three ways, ending at the masked softmax. Ashish Vaswani and colleagues, "Attention Is All You Need" (2017), is the paper that made it the core of the transformer.
Tags: Build an LLM Attention Context Weighted average Language model