Dot Product
The single arithmetic operation that measures how two vectors relate.
By the end of this chapter, you'll be able to:
- Compute the dot product of two vectors by hand and in NumPy
- Interpret a dot product as a similarity-like signal between two vectors
- Understand why raw dot products are sensitive to vector magnitude
Every attention score in a transformer, underneath all the terminology, comes down to one operation: the dot product.
The computation
For two vectors of the same length, the dot product multiplies each pair of matching elements together, then sums the results:
Worked by hand, for and :
Multiply position 1
2 × 3 = 6
Multiply position 2
5 × 5 = 25
Multiply position 3
3 × 2 = 6
Sum everything
6 + 25 + 6 = 37
import numpy as np
A = np.array([2, 5, 3])
B = np.array([3, 5, 2])
print(A @ B)
# 37What that number means
A and B above are close together in direction — a small angle between
them — and their dot product (4×3 + 3×4 = 24) is large and positive. That's the
general pattern:
A dot product is large and positive when two vectors point in similar directions and have large magnitudes; it's near zero when vectors are roughly perpendicular (unrelated); and it's negative when vectors point in opposing directions. That's the entire reason it's useful here: if two token embeddings have been trained to point in similar directions when the tokens are semantically related, their dot product becomes a computable stand-in for "how related are these two tokens?"
This is exactly what you saw computed all at once in the
Vectors chapter's sentence @ sentence.T — every
entry in that 3×3 result is one dot product, between one pair of tokens.
Dot product is not the same as similarity
A dot product is affected by magnitude, not just direction. Two vectors pointing in exactly the same direction, but where one is scaled up 10x, produce a much larger dot product than two identical, unscaled vectors — even though "how similar are these directions" hasn't changed at all. This is precisely the gap that Cosine Similarity closes, by dividing out the magnitude entirely.
Check your understanding
1. What is the dot product of [2, 5, 3] and [3, 5, 2]?
2. What does a dot product near zero suggest about two vectors?