Scaled dot-product attention that survives hidden cases, and a parameter count you can defend. You compute attention by hand on small matrices, count every parameter of a small model, and then implement attention in plain Python. The aim is for the transformer to be real numbers to you and not a diagram.
Allow eight to ten hours. Read Chapters 17 and 18 first.
Python and nothing else. The implementation must use the standard library alone.
Scores . Weights are the row-wise softmax of . The output is .
Causal mask. Before the softmax set for all , so that row attends only to positions up to and including .
Rows and columns are indexed from zero. Report numbers to four decimal places.
A worked example. Reproduce this by hand before you touch your own matrices. Take The scaled scores, the weights and the output are
| output | ||
|---|---|---|
With the causal mask the first output row collapses to , because token can only see itself, and the second becomes , an even mix of and . The third row is unchanged, because it may see every position. Then choose your own , and with three tokens and and report four probe cells: one score, one unmasked weight, one output vector and one causal weight.
Parameter counting. Count every parameter of a small transformer under this convention, where is the model width, the vocabulary size, the longest sequence and the width of the feed-forward layer. Token embeddings cost and learned positional embeddings . Per layer, attention costs , because , , and are each with a bias. Per layer the feed-forward block costs , plus two layer norms of each. One final layer norm costs . The output head costs nothing if it is tied to the embeddings, meaning it reuses the embedding matrix, and otherwise.
Check. With , two layers, , , and tied embeddings, each layer costs and the total is . Say which side holds more parameters, the embeddings or the blocks, and notice that the number of heads appears nowhere in the count. Explain why.
In code. Write
attention(Q, K, V, causal=False) for lists of lists,
returning the output as lists of lists. Cases to survive include larger
shapes, float entries, both mask settings, and a case with
where a hard-coded
fails.
Check. Your function must reproduce the table above without
the mask. With causal=True the output rows are
,
and
.
Remove the scaling and measure the entropy of the weights as grows, as in Chapter 17.
Add two heads and check that the parameter count does not change while the output does.
Compare your count with
torch.nn.TransformerEncoderLayer, itemising every
difference, as in Chapter 18.
From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.