Attention Is Just Similarity, Measured Three Ways

3 min read

The last video showed attention as gravity: words pull each other closer so the model can tell a fruit from a brand. This one does the math behind those moving embeddings. Everything comes down to one question: how similar are two words? The video gives three answers that turn out to be the same idea in different clothes, and the third one is the formula attention actually uses.

First, the dot product. In these word embeddings, give each axis a meaning: horizontal for tech, vertical for fruitness. Cherry sits at 1, 4, high fruitness and low tech. Orange sits at 0, 3. Multiply matching coordinates and add: 1 times 0 plus 4 times 3 equals 12. Cherry and phone, at 3, 0, give 1 times 3 plus 4 times 0, which is 3. Orange and phone give 0 times 3 plus 3 times 0, which is 0. Similar words score high, different words score low, and perpendicular words score exactly zero.

Dot product similarity
cherry-orange12dot produccherry-phone3dot producorange-phone0dot produc
Data from the sources listed below.

Second, cosine similarity. Forget the lengths and look at the angle between the vectors. Cherry and orange sit 14 degrees apart, and the cosine of that angle is 0.97. Cherry and phone are 76 degrees apart, cosine 0.24. Orange and phone are 90 degrees apart, cosine 0. The scale runs from 1 for identical directions down to negative 1 for opposite ones. It looks nothing like a dot product, but the two are the same thing when the vectors have length one. In general, the dot product equals cosine similarity times the product of the two lengths.

Third, the scaled dot product, which is the one attention uses. It is just another multiple of the dot product, adjusted so the numbers stay well behaved as vectors get longer. That is the whole mathematical core of the attention mechanism: measure similarity between words, turn the scores into weights, and let each word gather information from the words most similar to it. The query, key, and value matrices are linear transformations that produce the vectors being compared, but the comparison itself is nothing more exotic than a dot product.

That is what makes the mechanism feel less mysterious once you see it. Attention is not a black box that understands language. It is arithmetic on coordinates: similar words pull together, dissimilar words barely move each other, and the sentence reshapes every word in it. The next video in the series puts these pieces together into the full transformer, but the idea that carries the most weight is already here: meaning, for a model, is a direction in space, and the dot product is how you measure it.

Try this

bash
pip install numpy
python -c "import numpy as np; c=np.array([1,4]); o=np.array([0,3]); p=np.array([3,0]); print(np.dot(c,o), np.dot(c,p), np.dot(o,p))"

Sources