Vectors, dot products and the geometry of meaning¶
A modern model turns every word, image patch and user query into a list of numbers, then compares and combines those lists with one operation: the dot product. Learn to see a vector as an arrow, a list and a point at once, and the dot product as "how much do these two point the same way", and half of deep learning becomes geometry you can picture.
10,000 ft
Every AI system since the early 2010s represents things as vectors: points in a space with hundreds or thousands of axes. Words, tokens, images, songs, users and documents all become vectors (embeddings), and "similar meaning" becomes "nearby" or "pointing the same way". The dot product is how a model measures that alignment. It is the core of a neuron (neurons and MLPs), of attention (attention), of the final layer that picks the next token, and of every vector search engine behind retrieval (embeddings and vector search). Matrices (next page) are just many dot products done at once.
2,000 ft
A vector is a list of \(d\) numbers, which you can also draw as an arrow from the origin. Adding vectors and scaling them is how a model mixes information. The dot product \(\mathbf{a}\cdot\mathbf{b}=\sum_i a_i b_i\) equals \(\lVert\mathbf{a}\rVert\,\lVert\mathbf{b}\rVert\cos\theta\), so it measures length and alignment together; divide out the lengths and you get cosine similarity, pure alignment. Learned embedding spaces turn out to put related concepts in similar directions and even to encode relations as directions ("male → female", "true → false"). And in high dimensions there is a surprising amount of room: random directions are almost perpendicular, which is why a 4,096-dimensional space can hold far more than 4,096 distinguishable concepts.
Ground level¶
Three ways to see a vector¶
A vector in \(\mathbb{R}^d\) is an ordered list of \(d\) real numbers, \(\mathbf{x} = (x_1, \dots, x_d)\). You will use three pictures of the same object, and switching between them fluently is most of the skill:
- A list of features. \((\text{price}, \text{bedrooms}, \text{area})\) for a house; 784 pixel brightnesses for a 28×28 image; 4,096 learned numbers for a token in a 7-billion-parameter LLM. Each position (coordinate) has a meaning, even when no human can name it.
- An arrow from the origin. Length and direction. Adding vectors is placing arrows head to tail; multiplying by a scalar stretches or flips the arrow.
- A point in space. Two vectors are "close" if the points are near each other. A dataset is a cloud of points; a classifier is a surface that cuts the cloud.
The arrow picture only works in 2-D and 3-D, but the algebra is identical in 12,288 dimensions (the width of GPT-3's largest model, per Brown et al., 2020, Table 2.1). The trick every practitioner uses is to reason in 2-D or 3-D, then check which conclusions survive in high dimensions. Some do not, and we will meet those below.
Formally, \(\mathbb{R}^d\) is a vector space: you can add any two vectors and scale any vector by a real number, and the usual rules hold (addition commutes, there is a zero vector, scaling distributes over addition). Nothing else is assumed. Lengths and angles are extra structure, which the dot product supplies.
Linear combinations, span and basis¶
The two operations combine into the single most important construction in linear algebra, the linear combination:
The set of all linear combinations of some vectors is their span. Two non-parallel arrows in the plane span the whole plane; two parallel arrows span only a line. Vectors are linearly independent if none of them is a combination of the others, which means each adds a genuinely new direction. A basis is an independent set that spans the space, and every basis of \(\mathbb{R}^d\) has exactly \(d\) vectors: that number is the dimension.
The standard basis \(\mathbf{e}_1=(1,0,\dots)\), \(\mathbf{e}_2=(0,1,0,\dots)\) is the one coordinates silently refer to: \(\mathbf{x} = x_1\mathbf{e}_1 + \dots + x_d\mathbf{e}_d\). Choosing a different basis changes the numbers, not the vector. That idea is the doorway to PCA and SVD (Eigenvectors, SVD and PCA), which are nothing but "find the basis in which this data is simplest".
A neural network layer outputs linear combinations
The output of a linear layer, \(W\mathbf{x}\), is a linear combination of the columns of \(W\), with the entries of \(\mathbf{x}\) as the coefficients. So a layer can only produce vectors inside the span of its columns. That one sentence explains why a layer with a 64-wide bottleneck cannot carry more than 64 independent directions of information, and why LoRA's low-rank updates (LoRA) restrict where a fine-tune can move the model.
Length: norms¶
The length (Euclidean or L2 norm) of a vector follows from Pythagoras applied coordinate by coordinate:
Machine learning uses other norms too, because each one encodes a different idea of "size":
| Norm | Formula | Unit "ball" in 2-D | Where it appears in AI |
|---|---|---|---|
| L2 (Euclidean) | \(\sqrt{\sum_i x_i^2}\) | circle | weight decay, gradient clipping by norm, RMSNorm, cosine similarity |
| L1 (Manhattan) | \(\sum_i \lvert x_i\rvert\) | diamond | lasso; sparsity penalties in sparse autoencoders |
| L∞ (max) | \(\max_i \lvert x_i\rvert\) | square | adversarial perturbation budgets ("change no pixel by more than 8/255") |
A unit vector has length 1. Dividing any non-zero vector by its length, \(\hat{\mathbf{x}} = \mathbf{x}/\lVert\mathbf{x}\rVert\), keeps the direction and throws away the magnitude. This normalising step is everywhere: embedding models normalise their outputs, and LayerNorm and RMSNorm (initialisation and normalisation) are close cousins of it.
The dot product, two ways¶
The dot product (inner product) of two vectors of the same length is
That is the algebraic definition: multiply matching coordinates and add. The geometric fact, derived in First principles, is
where \(\theta\) is the angle between the arrows. So the sign of the dot product tells you the rough relationship: positive if they point broadly the same way (\(\theta<90^\circ\)), zero if they are perpendicular (orthogonal), negative if they point apart.
Worked example. Take \(\mathbf{a}=(3,1)\) and \(\mathbf{b}=(2,4)\).
- \(\mathbf{a}\cdot\mathbf{b} = 3\cdot 2 + 1\cdot 4 = 10\).
- \(\lVert\mathbf{a}\rVert=\sqrt{10}\approx 3.162\), \(\lVert\mathbf{b}\rVert=\sqrt{20}\approx 4.472\).
- \(\cos\theta = 10/(3.162\times 4.472) = 10/\sqrt{200} \approx 0.7071\), so \(\theta = 45^\circ\).
Projection: the shadow of one vector on another¶
The dot product's most useful reading is projection. The component of \(\mathbf{a}\) along the direction of \(\mathbf{b}\) (its "shadow" on the line through \(\mathbf{b}\)) is
With our numbers: \(\frac{10}{20}(2,4) = (1,2)\). The leftover, \(\mathbf{a} - (1,2) = (2,-1)\), is perpendicular to \(\mathbf{b}\): check \((2)(2) + (-1)(4) = 0\). So every vector splits uniquely into a part along \(\mathbf{b}\) and a part orthogonal to it.
Projection is the geometry behind least-squares regression (linear regression): the fitted values are the projection of the target vector onto the span of the feature columns, and the residuals are orthogonal to every feature. It is also how interpretability researchers "read" a concept from a hidden state: project the state onto a direction that represents the concept.
Drag the two vectors below and watch the dot product, cosine and projection change together. Make them perpendicular and the dot product hits zero; flip one and it turns negative.
Dot product, cosine similarity and distance¶
Three ways to compare two vectors, and when each is the right one:
- Dot product \(\mathbf{a}\cdot\mathbf{b}\): alignment and magnitude. A longer vector scores higher. Attention and output logits use raw dot products, so magnitude carries information there (a confident hidden state can have a larger norm).
- Cosine similarity \(\cos\theta = \dfrac{\mathbf{a}\cdot\mathbf{b}}{\lVert\mathbf{a}\rVert\lVert\mathbf{b}\rVert} \in [-1, 1]\): alignment only. The default for comparing text embeddings, because document length and word frequency inflate norms without changing meaning.
- Euclidean distance \(\lVert\mathbf{a}-\mathbf{b}\rVert\): how far apart the points are.
For unit vectors the three are equivalent rankings, because
That is why vector databases let you choose "cosine", "dot" or "L2" and why normalising your embeddings once at index time makes all three agree. (A practical consequence: maximum-inner-product search over unnormalised vectors is a genuinely different problem, and indexes built for L2 need a transformation to answer it.)
Cosine similarity is not automatically 'semantic similarity'
Steck, Ekanadham and Kallus (2024) show that for embeddings learned by some regularised matrix-factorisation models, the learned vectors can be rescaled per dimension without changing the model's predictions, yet the rescaling changes the cosine similarities arbitrarily. Cosine is only as meaningful as the training objective that shaped the space. Embedding models trained with a cosine-based contrastive loss (as most text-embedding models are) make cosine the right comparison; for other spaces, check.
The geometry of meaning¶
Here is the idea that made vectors the lingua franca of AI. If a model must predict words from their contexts, words that occur in similar contexts receive similar vectors, because a similar vector produces similar predictions. Linguists had stated the hypothesis long before: J. R. Firth's 1957 line "you shall know a word by the company it keeps" is the usual citation for the distributional hypothesis. Bengio et al. (2003) learned such word vectors inside a neural language model; Mikolov et al. (2013) made them cheap enough to train on about 6 billion tokens of Google News and found something striking: relations became directions. In their words, vector("King") − vector("Man") + vector("Woman") "results in a vector that is closest to the vector representation of the word Queen". They built a test of 8,869 semantic and 10,675 syntactic analogy questions to measure it.
A four-dimensional toy shows the mechanism. Give each word hand-made coordinates for (royal, male, female, fruit):
| word | royal | male | female | fruit |
|---|---|---|---|---|
| king | 0.9 | 0.8 | 0.1 | 0.0 |
| queen | 0.9 | 0.1 | 0.8 | 0.0 |
| man | 0.1 | 0.9 | 0.1 | 0.0 |
| woman | 0.1 | 0.1 | 0.9 | 0.0 |
| apple | 0.0 | 0.1 | 0.1 | 0.9 |
Then king − man + woman \(= (0.9, 0.0, 0.9, 0.0)\): the "royal" survives, "male" is subtracted, "female" is added. Its cosine with queen is 0.995 and with king only 0.585 (computed in Build it). Real embeddings have no labelled axes. The concept directions are oblique combinations of hundreds of coordinates, and the arithmetic works only approximately, but it is the same geometry.
The modern form of this observation is the linear representation hypothesis: high-level concepts are represented as directions in a model's activation space. Park, Choe and Veitch (2023) formalise it and argue the right notion of "angle" between concept directions is not always the naive Euclidean one; Marks and Tegmark (2023) find a linear direction separating true from false statements in LLM activations. Interpretability work (mechanistic interpretability) is largely the search for such directions.
The famous analogies are flattering by construction
Word2vec's analogy evaluation searches for the nearest word to king − man + woman after discarding the three input words (Mikolov et al., 2013, Section 4). Without that exclusion the nearest word is often "king" itself. Nissim, van Noord and van der Goot (2020) show how this rule produced headline-grabbing "biased analogies" that partly reflect the evaluation, not only the embeddings. Embeddings do absorb social bias from text (Bolukbasi et al., 2016); measure it with care rather than with the analogy trick.
High dimensions are roomy and strange¶
Intuition from 2-D and 3-D misleads you in two specific ways.
Random directions are nearly orthogonal. Pick two random unit vectors in \(\mathbb{R}^d\). Their cosine has mean 0 and standard deviation almost exactly \(1/\sqrt{d}\) (derived in The maths). Measured with 1,000 random pairs per dimension:
| \(d\) | mean \(\lvert\cos\rvert\) | std of cos | \(1/\sqrt{d}\) |
|---|---|---|---|
| 2 | 0.644 | 0.715 | 0.707 |
| 16 | 0.198 | 0.244 | 0.250 |
| 128 | 0.069 | 0.087 | 0.088 |
| 1,024 | 0.025 | 0.031 | 0.031 |
| 12,288 | 0.007 | 0.009 | 0.009 |
In 2-D the angle between two random arrows is spread evenly over 0°–180°, so |cos| averages 2/π ≈ 0.64; in 12,288-D a typical pair is within about half a degree of perpendicular (arcsin 0.009 ≈ 0.5°). So in an embedding space a cosine of 0.3 is a strong signal, not a weak one. It is roughly 33 standard deviations above chance at \(d=12{,}288\).
There is room for far more than \(d\) "almost orthogonal" directions. Only \(d\) vectors can be exactly orthogonal, but the number of vectors whose pairwise cosines all stay below a small \(\varepsilon\) grows exponentially in \(d\). The Johnson–Lindenstrauss lemma is the quantitative version: any \(n\) points can be mapped into \(k = O(\log n / \varepsilon^2)\) dimensions with all pairwise distances preserved to within a factor \(1\pm\varepsilon\), and a random projection does it. Elhage et al. (2022) show networks exploit this: when features are sparse, a model stores many more features than it has dimensions, in nearly orthogonal directions, accepting a little interference. They call it superposition, and it is why individual neurons in LLMs often respond to several unrelated things.
Two pictures to keep
- Meaning is direction. The concept is the direction; how far along it a vector goes is the intensity.
- High-dimensional space is mostly perpendicular. Unrelated things are close to orthogonal by default, so any noticeable alignment is information.
Dot products everywhere in AI¶
Once you can see the dot product, you see it in every component of a model:
- A neuron computes \(\mathbf{w}\cdot\mathbf{x} + b\). The set where it equals zero is a hyperplane with normal vector \(\mathbf{w}\); the neuron measures which side of that plane the input is on, and how far (\((\mathbf{w}\cdot\mathbf{x}+b)/\lVert\mathbf{w}\rVert\) is the signed distance). A perceptron or logistic regression is exactly this.
- Attention scores how relevant token \(j\) is to token \(i\) by \(\mathbf{q}_i\cdot\mathbf{k}_j/\sqrt{d_k}\) (attention). The \(\sqrt{d_k}\) comes straight from the variance calculation below.
- The output layer of a language model computes one logit per vocabulary word as \(\mathbf{h}\cdot\mathbf{e}_{\text{word}}\), the dot product of the final hidden state with that word's output embedding. Predicting the next token is finding the word vector most aligned with the hidden state, then a softmax (information theory).
- Retrieval for RAG ranks documents by cosine similarity between the query embedding and each chunk's embedding (RAG).
- Contrastive learning (CLIP, sentence embeddings such as Sentence-BERT) is trained by pushing the dot products of matching pairs up and of non-matching pairs down.
In Jarvis
Jarvis's storage layer keeps one embedding vector per chat message and searches them by cosine distance, \(1-\cos\theta\), documented in the code as "0 = identical, 2 = opposite": the range you get from \(\cos\theta\in[-1,1]\). It is semantic conversation memory, scoped so a search never crosses users. The vectors decide what past context is relevant; the financial numbers always come from the FIRE engine, never from the vectors. See the Jarvis case study.
History¶
From arrows to embeddings
Hermann Grassmann's Die lineale Ausdehnungslehre (1844) set out the algebra of vectors in any number of dimensions; it was largely ignored for decades. Josiah Willard Gibbs and Oliver Heaviside, working independently in the 1880s, distilled the dot and cross products into the vector calculus physicists and engineers still use. Information retrieval adopted vectors in the 1960s–70s (Gerard Salton's SMART system and the vector space model, with documents as term-count vectors compared by cosine). Latent semantic analysis (1990) applied the SVD to those vectors to get dense "concept" dimensions (Eigenvectors, SVD and PCA). Neural word vectors followed with Bengio et al. (2003), went mainstream with word2vec (2013) and GloVe (2014), and became contextual (a different vector for "bank" in each sentence) with ELMo, BERT and GPT in 2018.
First principles¶
Why should "multiply matching coordinates and add" have anything to do with angles? Start from what we want of a notion of length and angle, and the dot product falls out.
Step 1: the law of cosines. In a triangle with sides \(\mathbf{a}\), \(\mathbf{b}\) and \(\mathbf{a}-\mathbf{b}\), elementary geometry gives
Step 2: expand the left side in coordinates. Using Pythagoras for length,
Step 3: compare. The squared-length terms cancel, leaving \(\sum_i a_i b_i = \lVert\mathbf{a}\rVert\lVert\mathbf{b}\rVert\cos\theta\). The coordinate formula and the geometric one are the same quantity. Nothing about this depended on \(d=2\) or \(3\): in \(d\) dimensions, the two vectors span a plane, the triangle lives in that plane, and the argument goes through. In high dimensions we simply define the angle by \(\cos\theta = \mathbf{a}\cdot\mathbf{b}/(\lVert\mathbf{a}\rVert\lVert\mathbf{b}\rVert)\), and Cauchy–Schwarz (below) guarantees this is always between −1 and 1, so the definition makes sense.
What makes something an inner product. Abstracting, a function \(\langle\mathbf{a},\mathbf{b}\rangle\) is an inner product if it is (i) linear in each argument, (ii) symmetric, and (iii) positive: \(\langle\mathbf{x},\mathbf{x}\rangle > 0\) for \(\mathbf{x}\neq \mathbf{0}\). The dot product is one; so is \(\mathbf{a}^\top M\mathbf{b}\) for any symmetric positive-definite matrix \(M\). Each choice of \(M\) is a different geometry, a different idea of which directions count as "far". The Mahalanobis distance in statistics, natural-gradient methods in optimisation, and Park et al.'s "causal inner product" for LLM concept directions are all instances. When someone says two concept directions are "orthogonal", always ask: under which inner product?
What breaks if you change it. Drop symmetry and "the angle from a to b" differs from "the angle from b to a". Drop positivity and some non-zero vectors have zero or negative "length", and you lose the triangle inequality, nearest-neighbour search and projection. Drop linearity and gradients of similarity scores stop being simple. Attention's \(\mathbf{q}^\top\mathbf{k} = \mathbf{x}_i^\top W_Q^\top W_K\mathbf{x}_j\) is a bilinear form that is neither symmetric nor positive, and that freedom is deliberate: "is token \(j\) useful to token \(i\)" is not a symmetric question.
The maths¶
Definitions. For \(\mathbf{a},\mathbf{b}\in\mathbb{R}^d\): \(\mathbf{a}\cdot\mathbf{b} = \mathbf{a}^\top\mathbf{b} = \sum_{i=1}^d a_ib_i\); \(\lVert\mathbf{a}\rVert = \sqrt{\mathbf{a}\cdot\mathbf{a}}\); \(\cos\theta = \mathbf{a}\cdot\mathbf{b}/(\lVert\mathbf{a}\rVert\lVert\mathbf{b}\rVert)\). Vectors are orthogonal when \(\mathbf{a}\cdot\mathbf{b}=0\).
Properties. Linearity \((\alpha\mathbf{a}+\beta\mathbf{c})\cdot\mathbf{b} = \alpha\,\mathbf{a}\cdot\mathbf{b} + \beta\,\mathbf{c}\cdot\mathbf{b}\); symmetry \(\mathbf{a}\cdot\mathbf{b}=\mathbf{b}\cdot\mathbf{a}\); positivity \(\mathbf{a}\cdot\mathbf{a}\ge 0\) with equality only at \(\mathbf{0}\).
Cauchy–Schwarz: \(\lvert\mathbf{a}\cdot\mathbf{b}\rvert \le \lVert\mathbf{a}\rVert\,\lVert\mathbf{b}\rVert\)
If \(\mathbf{b}=\mathbf{0}\) both sides are 0. Otherwise, for every real \(t\), positivity gives
This is a quadratic in \(t\) that is never negative, so its discriminant is \(\le 0\):
Rearranging gives the inequality. Equality holds exactly when \(\mathbf{a} - t\mathbf{b} = \mathbf{0}\) for some \(t\), i.e. when the vectors are parallel. (The minimising \(t\) is \(\mathbf{a}\cdot\mathbf{b}/\lVert\mathbf{b}\rVert^2\): the projection coefficient. Projection is the closest point on the line.)
Triangle inequality. \(\lVert\mathbf{a}+\mathbf{b}\rVert \le \lVert\mathbf{a}\rVert + \lVert\mathbf{b}\rVert\), because \(\lVert\mathbf{a}+\mathbf{b}\rVert^2 = \lVert\mathbf{a}\rVert^2 + 2\,\mathbf{a}\cdot\mathbf{b} + \lVert\mathbf{b}\rVert^2 \le (\lVert\mathbf{a}\rVert + \lVert\mathbf{b}\rVert)^2\) by Cauchy–Schwarz.
Projection onto a subspace. If \(\mathbf{q}_1,\dots,\mathbf{q}_k\) are orthonormal (\(\mathbf{q}_i\cdot\mathbf{q}_j = 1\) if \(i=j\), else 0) and stacked as rows of \(Q\in\mathbb{R}^{k\times d}\), the projection of \(\mathbf{x}\) onto their span is
The coordinates of \(\mathbf{x}\) in an orthonormal basis are just dot products with the basis vectors. That is why orthonormal bases are so convenient.
Gram–Schmidt turns any independent set \(\mathbf{v}_1,\dots,\mathbf{v}_k\) into an orthonormal one with the same span: for each \(\mathbf{v}_j\), subtract its projections onto the \(\mathbf{q}\)'s found so far, then normalise:
In matrix form this is the QR decomposition, which numerical libraries compute with more stable variants.
Why random dot products scale like \(\sqrt{d}\) (and why attention divides by \(\sqrt{d_k}\))
Let \(\mathbf{q},\mathbf{k}\in\mathbb{R}^d\) have independent entries with mean 0 and variance 1. Then \(s = \mathbf{q}\cdot\mathbf{k} = \sum_i q_ik_i\) is a sum of \(d\) independent terms, each with mean \(\mathbb{E}[q_i]\mathbb{E}[k_i] = 0\) and variance \(\mathbb{E}[q_i^2k_i^2] - 0 = \mathbb{E}[q_i^2]\,\mathbb{E}[k_i^2] = 1\). Variances of independent terms add, so
Dividing by \(\sqrt{d}\) brings the scores back to unit variance whatever the head size. Without it, at \(d_k = 128\) typical scores would be around ±11, the softmax would put almost all weight on one token, and its gradients would vanish. Measured: \(\operatorname{Var}[\mathbf{q}\cdot\mathbf{k}]\) = 16.1, 63.2, 259.1 for \(d_k\) = 16, 64, 256; after scaling, 1.006, 0.987, 1.012. This is the argument in footnote 4 of Vaswani et al. (2017).
For unit vectors, divide each by its length (\(\approx\sqrt{d}\)): \(\cos\theta \approx s/d\), which has standard deviation \(\sqrt{d}/d = 1/\sqrt{d}\). That is the near-orthogonality table above.
Build it¶
NumPy, no frameworks: cosine similarity for a whole vocabulary in one matrix multiply, the analogy search with the input words excluded, Gram–Schmidt, and a projection onto a subspace.
import numpy as np
def normalize(X):
"""Scale each row to unit length (L2)."""
return X / np.linalg.norm(X, axis=-1, keepdims=True)
def gram_schmidt(V):
"""Orthonormal basis for the span of V's rows."""
basis = []
for v in V:
w = v - sum((v @ q) * q for q in basis) # remove components along earlier directions
if np.linalg.norm(w) > 1e-10:
basis.append(w / np.linalg.norm(w))
return np.array(basis)
# A tiny vocabulary with hand-made 4-D embeddings: (royal, male, female, fruit)
words = ["king", "queen", "man", "woman", "apple"]
E = np.array([[0.9, 0.8, 0.1, 0.0],
[0.9, 0.1, 0.8, 0.0],
[0.1, 0.9, 0.1, 0.0],
[0.1, 0.1, 0.9, 0.0],
[0.0, 0.1, 0.1, 0.9]])
En = normalize(E)
# 1. Cosine-similarity matrix in one matrix multiply
S = En @ En.T
print("cosine matrix:\n", S.round(2))
# 2. Analogy by vector arithmetic, excluding the query words (as word2vec does)
q = normalize(E[0] - E[2] + E[3])
scores = En @ q
for i in (0, 2, 3):
scores[i] = -np.inf
print("king - man + woman ->", words[int(np.argmax(scores))], f"(cos={scores.max():.3f})")
# 3. Gram-Schmidt: an orthonormal basis for span{king, man}
Q = gram_schmidt(E[[0, 2]])
print("Q Q^T =\n", (Q @ Q.T).round(6))
# 4. Project 'queen' onto that 2-D subspace and measure what is left over
x = E[1]
p = Q.T @ (Q @ x)
print("queen projected:", p.round(3), " residual norm:", round(float(np.linalg.norm(x - p)), 3))
Output:
cosine matrix:
[[1. 0.66 0.74 0.24 0.08]
[0.66 1. 0.24 0.74 0.08]
[0.74 0.24 1. 0.23 0.12]
[0.24 0.74 0.23 1. 0.12]
[0.08 0.08 0.12 0.12 1. ]]
king - man + woman -> queen (cos=0.995)
Q Q^T =
[[1. 0.]
[0. 1.]]
queen projected: [0.911 0.184 0.033 0. ] residual norm: 0.772
Read the output: king is closer to man (0.74) than to queen (0.66) in this toy, because the male coordinate dominates; analogy arithmetic still finds queen because it cancels the shared "male" component rather than relying on raw similarity. The projection of queen onto span{king, man} keeps its royalty but loses almost all of its "female" coordinate, which lives outside that plane: hence the residual of 0.772.
And the high-dimension experiment behind the table above:
import numpy as np
rng = np.random.default_rng(0)
for d in [2, 16, 128, 1024, 12288]:
X = rng.standard_normal((2000, d))
X /= np.linalg.norm(X, axis=1, keepdims=True)
cos = np.sum(X[:1000] * X[1000:], axis=1) # 1000 random pairs
print(f"d={d:>5}: mean|cos|={np.abs(cos).mean():.4f} std={cos.std():.4f} 1/sqrt(d)={1/np.sqrt(d):.4f}")
d= 2: mean|cos|=0.6436 std=0.7148 1/sqrt(d)=0.7071
d= 16: mean|cos|=0.1981 std=0.2444 1/sqrt(d)=0.2500
d= 128: mean|cos|=0.0694 std=0.0873 1/sqrt(d)=0.0884
d= 1024: mean|cos|=0.0245 std=0.0307 1/sqrt(d)=0.0312
d=12288: mean|cos|=0.0073 std=0.0090 1/sqrt(d)=0.0090
Things to try
- Download a small pretrained embedding set (GloVe's 50-d vectors from the GloVe project page) and rerun the analogy search with and without excluding the input words. How often is the answer just "king"?
- Replace cosine with the raw dot product in the analogy search on unnormalised vectors. Which words win, and why (look at their norms)?
- Generate 4,000 random unit vectors in \(d=256\) (16× more vectors than dimensions) and find the largest absolute pairwise cosine. With seed 0 we got a maximum of 0.317 and a mean of 0.050 over all 8 million pairs: thousands of directions, none closer than about 72° to any other.
- Implement \(\mathbf{a}^\top M\mathbf{b}\) similarity with \(M=\operatorname{diag}(1, 10, 10, 1)\). Which pairs in the toy vocabulary become more or less similar?
Common misconceptions¶
- "High cosine means the same meaning." It means similar usage under the training objective. Antonyms ("hot", "cold") occur in near-identical contexts and often have high cosine in distributional embeddings.
- "Embedding dimensions mean something." Individual coordinates are usually arbitrary; any rotation of the space gives an equally good model. Meaning lives in directions, which are generally not axis-aligned. (Sparse autoencoders are an attempt to find a basis where they are.)
- "More dimensions means more features, one per axis." Superposition lets a model store many more sparse features than dimensions, at the cost of some interference.
- "Euclidean and cosine search give different results." Not for normalised vectors: they produce identical rankings.
Check yourself¶
Compute the dot product, cosine and angle for a = (1, 2, 2) and b = (2, 0, 1).
\(\mathbf{a}\cdot\mathbf{b} = 2 + 0 + 2 = 4\). \(\lVert\mathbf{a}\rVert = 3\), \(\lVert\mathbf{b}\rVert = \sqrt{5}\approx 2.236\). \(\cos\theta = 4/(3\sqrt5) \approx 0.596\), so \(\theta\approx 53.4^\circ\).
Show that for unit vectors, ranking by Euclidean distance and by cosine similarity give the same order.
\(\lVert\hat{\mathbf{a}}-\hat{\mathbf{b}}\rVert^2 = 2 - 2\cos\theta\), a strictly decreasing function of \(\cos\theta\). Smaller distance ⇔ larger cosine.
A neuron has w = (3, 4), b = −10. What is the signed distance from x = (2, 2) to its decision boundary, and which side is x on?
\(\mathbf{w}\cdot\mathbf{x}+b = 6 + 8 - 10 = 4\); \(\lVert\mathbf{w}\rVert = 5\); signed distance \(4/5 = 0.8\) on the positive side.
Why does the output of a linear layer W x lie in the span of W's columns, and what does that imply for a 4096 → 64 → 4096 bottleneck?
\(W\mathbf{x} = \sum_j x_j W_{:,j}\), a linear combination of columns. After the 64-wide layer, everything downstream is a function of 64 numbers, so the 4096-wide output of the second linear map lies in a subspace of dimension at most 64. That is a rank constraint, the same one LoRA exploits deliberately.
Two random unit vectors in d = 4096 have cosine 0.2. Is that meaningful?
Very. The chance level has standard deviation \(1/\sqrt{4096} = 1/64 \approx 0.016\), so 0.2 is about 13 standard deviations from zero. In high dimensions small-looking cosines carry real signal.
Attention uses q·k/√d_k. Derive the √d_k and say what goes wrong without it.
With unit-variance independent entries, \(\operatorname{Var}[\mathbf{q}\cdot\mathbf{k}] = d_k\), so scores grow like \(\sqrt{d_k}\). Large scores make softmax nearly one-hot, its Jacobian nearly zero, and learning stalls. Dividing by \(\sqrt{d_k}\) restores unit variance at initialisation.
Hard: why might two concept directions in an LLM look non-orthogonal under the Euclidean dot product even if the concepts are causally independent?
The Euclidean inner product depends on the arbitrary basis the model happened to learn; any invertible linear change of coordinates of the residual stream (compensated in the weights) would change Euclidean angles without changing behaviour. Park, Choe and Veitch (2023) argue for an inner product defined by the model's unembedding geometry, under which causally separable concepts become orthogonal. The general lesson: orthogonality is relative to a chosen inner product.
Go deeper¶
Papers
- Efficient Estimation of Word Representations in Vector Space — Mikolov, Chen, Corrado, Dean, 2013. Word2vec; read Section 4 for the analogy test set and how it is scored.
- Distributed Representations of Words and Phrases and their Compositionality — Mikolov et al., 2013. Negative sampling, the trick that made training cheap: a dot product pushed up for real pairs and down for random ones.
- A Neural Probabilistic Language Model — Bengio, Ducharme, Vincent, Jauvin, JMLR 2003. Where learned word vectors began.
- GloVe: Global Vectors for Word Representation — Pennington, Socher, Manning, EMNLP 2014. Derives why ratios of co-occurrence counts become vector differences.
- Toy Models of Superposition — Elhage et al., Anthropic, 2022. How networks pack more features than dimensions into nearly orthogonal directions.
- The Linear Representation Hypothesis and the Geometry of Large Language Models — Park, Choe, Veitch, 2023. Concepts as directions, and which inner product makes them orthogonal.
- Is Cosine-Similarity of Embeddings Really About Similarity? — Steck, Ekanadham, Kallus, 2024. A short, sharp warning about using cosine blindly.
- Fair is Better than Sensational — Nissim, van Noord, van der Goot, 2020. How the analogy evaluation rule shapes what you see.
Videos and lectures
- Vectors, Chapter 1, Essence of linear algebra — 3Blue1Brown. The three views of a vector, animated.
- Linear combinations, span, and basis vectors — 3Blue1Brown, Chapter 2.
- Dot products and duality — 3Blue1Brown, Chapter 9. Why the dot product is secretly a linear map to the number line.
- MIT 18.06 Linear Algebra — Gilbert Strang. The classic course; lectures 1, 14 and 15 cover vectors, orthogonality and projection.
Articles and blog posts
- The Illustrated Word2vec — Jay Alammar. Embeddings and the dot-product training loop, drawn.
Courses and books
- Mathematics for Machine Learning — Deisenroth, Faisal, Ong, 2020 (free PDF). Chapters 2–3: vector spaces, norms, inner products, projections.
- Deep Learning, Chapter 2: Linear Algebra — Goodfellow, Bengio, Courville. A compact reference with ML-flavoured notation.
- Linear Algebra Done Right — Sheldon Axler (free online). Chapter 6 on inner product spaces, for when you want the proofs.
Where this leads¶
- Matrices as linear maps — a matrix is a stack of dot products, and a layer is a transformation of the whole space.
- Eigenvectors, SVD and PCA — finding the directions that matter most in a cloud of vectors.
- Embeddings and representation learning — how networks learn the spaces described here.
- Attention from first principles — dot products as soft lookups.
- Embeddings and vector search — cosine similarity at production scale.