Contents Projects Code Course home

Chapter 33Project 6: Transformer Anatomy

What you will build

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.

What you need

Python and nothing else. The implementation must use the standard library alone.

The conventions

  • Scores S=QK⊤/dkS = QK^{\top}/\sqrt{d_k}. Weights are the row-wise softmax of SS. The output is WVWV.

  • Causal mask. Before the softmax set Sij=−∞S_{ij} = -\infty for all j>ij > i, so that row ii attends only to positions up to and including ii.

  • Rows and columns are indexed from zero. Report numbers to four decimal places.

Stages

  1. A worked example. Reproduce this by hand before you touch your own matrices. Take Q=(100111),K=(110110),V=(100122).Q = \begin{pmatrix}1&0\\0&1\\1&1\end{pmatrix},\quad K = \begin{pmatrix}1&1\\0&1\\1&0\end{pmatrix},\quad V = \begin{pmatrix}1&0\\0&1\\2&2\end{pmatrix}. The scaled scores, the weights and the output are

    SS WW output
    (0.707100.70710.70710.707101.41420.70710.7071)\begin{pmatrix}0.7071&0&0.7071\\0.7071&0.7071&0\\1.4142&0.7071&0.7071\end{pmatrix} (0.40110.19780.40110.40110.40110.19780.50350.24830.2483)\begin{pmatrix}0.4011&0.1978&0.4011\\0.4011&0.4011&0.1978\\0.5035&0.2483&0.2483\end{pmatrix} (1.20331.00000.79670.79671.00000.7448)\begin{pmatrix}1.2033&1.0000\\0.7967&0.7967\\1.0000&0.7448\end{pmatrix}

    With the causal mask the first output row collapses to V0=(1,0)V_0 = (1, 0), because token 00 can only see itself, and the second becomes (0.5,0.5)(0.5, 0.5), an even mix of V0V_0 and V1V_1. The third row is unchanged, because it may see every position. Then choose your own QQ, KK and VV with three tokens and dk=2d_k = 2 and report four probe cells: one score, one unmasked weight, one output vector and one causal weight.

  2. Parameter counting. Count every parameter of a small transformer under this convention, where dd is the model width, VV the vocabulary size, LL the longest sequence and dffd_{\mathrm{ff}} the width of the feed-forward layer. Token embeddings cost VdVd and learned positional embeddings LdLd. Per layer, attention costs 4(d2+d)4(d^2 + d), because WQW_Q, WKW_K, WVW_V and WOW_O are each d×dd \times d with a bias. Per layer the feed-forward block costs ddff+dff+dffd+dd\,d_{\mathrm{ff}} + d_{\mathrm{ff}} + d_{\mathrm{ff}}\,d + d, plus two layer norms of 2d2d each. One final layer norm costs 2d2d. The output head costs nothing if it is tied to the embeddings, meaning it reuses the embedding matrix, and VdVd otherwise.

    Check. With d=8d = 8, two layers, dff=16d_{\mathrm{ff}} = 16, V=100V = 100, L=32L = 32 and tied embeddings, each layer costs 600600 and the total is 22722272. 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.

  3. 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 dk=4d_k = 4 where a hard-coded 2\sqrt{2} fails.

    Check. Your function must reproduce the table above without the mask. With causal=True the output rows are (1.0000,0.0000)(1.0000, 0.0000), (0.5000,0.5000)(0.5000, 0.5000) and (1.0000,0.7448)(1.0000, 0.7448).

Extensions

  • Remove the scaling and measure the entropy of the weights as dkd_k 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.