Neural networks represent words, images and whole documents as lists of numbers, and then decide what is related to what by multiplying those lists together. The dot product is that multiplication, and understanding its geometry explains embeddings, retrieval and attention.
Vectors as points and arrows
A vector in is an ordered list of real numbers, . It can be read as a point in -dimensional space or as an arrow from the origin to that point. Vectors add component-wise, which places arrows tip to tail, and scale by multiplying every component by a number.
The length (Euclidean norm) of a vector is
Pythagoras' theorem extended to dimensions. A vector of length 1 is a unit vector; dividing any nonzero vector by its length normalises it.
In machine learning is large. A token embedding in a mid-sized transformer might have or components. None of these dimensions need correspond to anything human-interpretable; what matters is the geometry, meaning the lengths of vectors and the angles between them.
The dot product
The dot product of two vectors is the sum of their component-wise products:
Algebraically this is a single multiply-accumulate loop, the operation that modern accelerators are built to do quickly. Geometrically it has a second meaning:
where is the angle between the arrows. (This follows from the law of cosines applied to the triangle with sides , and .[1]) So the dot product is large and positive when the vectors point the same way, zero when they are perpendicular (orthogonal), and negative when they point in opposite directions. It also grows with the vectors' lengths.
Two related quantities fall out immediately.
Cosine similarity removes the length:
Projection: the component of along the unit vector is . A dot product with a unit vector measures "how much of points in this direction". Most linear-algebraic readings of neural networks, from a classifier's decision boundary to a probe for a concept, are projections.
Worked example
Let and .
- .
- , .
- , so .
Now double to . The dot product doubles to 8, but the cosine stays 0.596: the direction has not changed. Whether length should count is a modelling decision, and different systems decide differently.
Vectors and . What are and the cosine similarity? What about and ?
Show answer +Hide answer −
, so they are orthogonal and the cosine is 0. and , so the cosine is exactly 1: points the same way.
Distance and similarity agree on the sphere
Expanding the squared distance gives
For unit vectors this is . Ranking neighbours by smallest Euclidean distance and ranking by largest cosine similarity therefore give the same order once vectors are normalised, which is why vector databases can offer either metric on normalised embeddings with identical results.
From documents to word vectors
Representing text as vectors and comparing them with cosines is older than neural networks. Salton, Wong and Yang's 1975 vector space model represented each document as a vector of term weights and retrieved documents by their similarity to a query vector.[2]
Neural embeddings learn the vectors instead of counting words. Mikolov and colleagues' word2vec models (2013) trained shallow networks to predict a word from its neighbours (continuous bag-of-words) or the neighbours from a word (skip-gram), and reported learning high-quality vectors from a 1.6-billion-word dataset in under a day.[3] Words used in similar contexts end up with high cosine similarity. A companion paper reported that relationships appeared as roughly consistent vector offsets: the vector lies closest, by cosine similarity, to .[4] Analogy arithmetic works only approximately and for some relations, but it shows that directions in embedding space can carry meaning.
Dot products inside attention
A transformer's attention layer is a soft lookup driven by dot products. Each position produces a query vector , and every position produces a key and a value . The score for attending from the query to position is ; a softmax turns the scores into weights, and the output is the weighted average of the values.[5] The keeps the scores' spread independent of dimension (the variance argument appears in Expectation and concentration).
Attention uses the raw dot product, not the cosine, so a key's length acts as a volume control. A query that is perpendicular to a key gives that position a score of 0, not , so the position still receives some weight after the softmax. Positions only drop out when other scores are much larger. The full mechanism is the subject of Attention from first principles.
A query meets keys and , ignoring the scaling for simplicity. What are the scores and the softmax attention weights?
Show answer +Hide answer −
Scores: , . Weights: and . The orthogonal key still gets 12% of the attention.
High dimensions behave differently
Intuition from two and three dimensions misleads in . If two vectors have independent random components with mean zero, their cosine similarity has mean zero and a standard deviation of about : roughly 0.036 at . Random high-dimensional vectors are almost always nearly orthogonal. That is good news for capacity, since a space can hold far more nearly-orthogonal directions than it has dimensions, a fact interpretability research leans on (see Mechanistic interpretability).
Real learned embeddings are not random, however. Ethayarajh found that contextual representations in ELMo, BERT and GPT-2 are anisotropic, occupying a narrow cone rather than spreading in all directions; in GPT-2's last layer, two randomly chosen words had nearly perfect average cosine similarity.[6] A cosine of 0.9 can therefore mean "closely related" in one space and "unremarkable" in another. Similarity scores are meaningful relative to the distribution of scores in that particular space, not on an absolute scale.
Key takeaways
- A dot product is a sum of products, and geometrically : it measures alignment, scaled by length.
- Cosine similarity discards length; for unit vectors it ranks neighbours in exactly the same order as Euclidean distance.
- Embeddings (from the vector space model to word2vec) place related items at small angles; attention scores are scaled dot products between queries and keys.
- Random high-dimensional vectors are nearly orthogonal, but learned embedding spaces are often anisotropic, so judge similarity scores against their own baseline.
Sources
-
G. Strang (2023). Introduction to Linear Algebra, 6th ed. Wellesley-Cambridge Press. https://math.mit.edu/~gs/linearalgebra/ila6/indexila6.html ↩
-
G. Salton, A. Wong, C. S. Yang (1975). "A Vector Space Model for Automatic Indexing." Communications of the ACM 18(11): 613–620. https://doi.org/10.1145/361219.361220 ↩
-
T. Mikolov, K. Chen, G. Corrado, J. Dean (2013). "Efficient Estimation of Word Representations in Vector Space." arXiv:1301.3781. https://arxiv.org/abs/1301.3781 ↩
-
T. Mikolov, W. Yih, G. Zweig (2013). "Linguistic Regularities in Continuous Space Word Representations." NAACL-HLT 2013, 746–751. https://aclanthology.org/N13-1090/ ↩
-
A. Vaswani et al. (2017). "Attention Is All You Need." NeurIPS 2017. arXiv:1706.03762. https://arxiv.org/abs/1706.03762 ↩
-
K. Ethayarajh (2019). "How Contextual are Contextualized Word Representations? Comparing the Geometry of BERT, ELMo, and GPT-2 Embeddings." EMNLP 2019. arXiv:1909.00512. https://arxiv.org/abs/1909.00512 ↩
