All labs Animated labs The chapter Course home

Lab 05Attention, one query at a time

Attention scores one query against every key, turns the scores into weights with a softmax and mixes the values by those weights. Three small experiments show what that does, why the scores are divided by √d_k, and why a language model needs a mask. Every number comes from attention.py.

1. One query, three keys

keyq · k÷ √3weight
output entropy of the weights

2. Why divide by √d_k

A dot product of two random vectors grows like √d_k. Without the division, a wide model's scores get so large that the softmax collapses onto one key before any training has happened. Pick a width and compare.

d_k

Averages over 200 fresh random draws, so they move a little each time. The chapter's table fixes the random seed.

3. The causal mask

A language model scoring position i must not read positions after it. Turn the mask on, then compare setting the blocked scores to minus infinity before the softmax with zeroing them after.

Where this fits

This is Self-Attention. Run attention.py to print the same tables as text.