14/29
Part 3 of 5 · From vectors back to wordsLearn and do

The head scores every word

After the last block, ln_f normalizes the stream one more time. Then the head turns each token's C numbers into V scores, one for each word in the vocabulary.

The head reuses the token table. This is called weight tying:

# C = 3 in, V = 5 scores out
lm_head = nn.Linear(3, 5, bias=False)
print(tok_emb.weight.shape, lm_head.weight.shape)
# one shared table
lm_head.weight = tok_emb.weight
print(lm_head.weight is tok_emb.weight)
torch.Size([5, 3]) torch.Size([5, 3])
True

On the way in, a word picks its row of the table. On the way out, the final vector is dotted with every row of the same table, and each dot product is one word's score:

The same table, used to score every wordInteractive
final
vector
0.5-1.00.8score = row · vectorthe→-0.68cat→0.25sat→-1.22on→0.54mat→-2.39
Score for cat = the vector dotted with cat's row: 0.50×0.57 + -1.00×-1.08 + 0.80×-1.40 = 0.25. The highest score, on, is the model's guess.

So the score for a word is the final vector dotted with that word's own row. The direction that means a word on the way in is the direction that predicts it on the way out.

In the editor, table is a hand-made token table for the five words, 3 numbers a row, and h is the final vector at one position. Set scores, h dotted with every row of table, and best, the word with the top score.