Inner products, norms and high-dimensional geometry
Formalize geometry through abstract inner products, norms and their unit balls, Cauchy–Schwarz, orthogonality, complements and orthonormal bases. Explore the counterintuitive geometry of high dimensions, where random vectors are nearly orthogonal and norms concentrate, explaining design choices in embeddings and attention.
After this lesson you can
Verify the axioms of inner products and norms, including the Frobenius product of matrices.
Prove the Cauchy–Schwarz inequality and derive the triangle inequality.
Calculate orthogonal complements and coordinates in orthonormal bases using inner products.
Relate the shape of the ℓ1, ℓ2 and ℓ∞ unit balls to properties such as solution sparsity.
Predict and simulate the near-orthogonality of random vectors in high dimensions.
A retrieval system turns each document into a vector in R768 or R1536 and answers queries by returning the nearest vectors. A k-nearest-neighbor classifier, a clustering algorithm and a contrastive loss do the same under different names: compare vectors. Regularization penalizes the size of weights, ∥w∥22 or ∥w∥1, producing different models depending on the choice. Attention computes q⊤k/dk and the dk is not decorative.
All these cases involve a prior, usually implicit choice: what we mean by length, distance and angle. In the first lesson you saw the dot product on Rn and its geometric meaning. Here we turn it into axioms and ask what follows from them alone. The payoff is twofold:
One theory applies to weighted vectors, functions, matrices and random variables. The Frobenius product of matrices, for example, defines the gradient with respect to a weight matrix.
With precise tools in hand, the second half studies high-dimensional geometry, where intuition from R2 and R3 systematically fails. Those failures explain the attention factor 1/dk, why a cosine of 0.3 can be huge in R768, and why Euclidean distances between unstructured data stop distinguishing neighbors.
Inner products
The dot product on Rn satisfies three properties sufficient to reconstruct all Euclidean geometry. We take them as a definition.
By symmetry, linearity also holds in the second argument: an inner product is a symmetric positive definite bilinear form. Taking a=b=0 in the second property gives ⟨0,w⟩=0, so ⟨v,v⟩=0 if and only if v=0.
Four examples that recur
Weighted dot product. In Rn, with weights w1,…,wn,
⟨x,y⟩w=i=1∑nwixiyi=x⊤diag(w)y.
Symmetry and bilinearity are immediate; positivity requires all weights to be positive, since if wk≤0 then ⟨ek,ek⟩w=wk≤0. This is useful when coordinates have different scales or importance. It also changes geometry: with M=diag(4,1), vectors x=(1,1) and y=(1,−4) satisfy ⟨x,y⟩M=4−4=0, although x⊤y=−3. Perpendicularity depends on the chosen inner product.
Functions. In the space C[a,b] of continuous functions on [a,b],
⟨f,g⟩=∫abf(t)g(t)dt.
Positivity uses continuity: if f=0, then f2>0 on some interval and the integral is positive. Among polynomials of degree at most 2 over [−1,1], ⟨1,t⟩=0 and ⟨t,t2⟩=0 because the integrands are odd, but ⟨1,t2⟩=2/3. If you replace t2 by t2−1/3, the list 1,t,t2−1/3 becomes orthogonal: up to scale, these are the first Legendre polynomials. This product opens the door to L2 space and Fourier series.
Matrices: the Frobenius product. In Rm×n,
⟨A,B⟩F=tr(A⊤B)=i=1∑mj=1∑naijbij.
The equality follows from the diagonal: (A⊤B)jj=∑iaijbij, and the trace sums those entries over j. It is the dot product of the two matrices flattened into vectors in Rmn, so it inherits all three axioms. For example, with
Random variables. For variables with finite second moment, ⟨X,Y⟩=E[XY] satisfies the axioms if we identify variables equal with probability 1. For centered variables it is covariance, and this lesson’s geometry becomes statistics: length is standard deviation and cosine is correlation.
In finite dimensions, every inner product is a matrix
Proof
If u=∑iuibi and v=∑jvjbj, bilinearity gives ⟨u,v⟩=∑i∑juivj⟨bi,bj⟩=∑i,juigijvj, the matrix expression. Symmetry of G follows from that of the inner product. And if c=0, vector w=∑icibi is nonzero because the bi are independent, so c⊤Gc=⟨w,w⟩>0.
∎
G is the basis’s Gram matrix, and symmetric matrices with c⊤Gc>0 are positive definite. The takeaway: in finite dimensions, an inner product is a symmetric positive definite matrix in disguise. Choosing an inner product other than the standard one (for example, Mahalanobis distance with M=Σ−1) means choosing that matrix. The orthonormal-basis section asks which basis makes G identity, so everything can be computed as in Rn with the dot product.
Norms
The most used family is the ℓp norms on Rn: for 1≤p<∞,
∥x∥p=(i=1∑n∣xi∣p)1/p,
and ∥x∥∞=maxi∣xi∣. With x=(3,−4,0,1): ∥x∥1=8, ∥x∥2=26≈5.10 and ∥x∥∞=4. The ℓ1 norm sums magnitudes (taxicab distance), ℓ2 is Euclidean, and ℓ∞ only considers the largest coordinate. The name ℓ∞ is justified: ∥x∥∞p≤∑i∣xi∣p≤n∥x∥∞p gives ∥x∥∞≤∥x∥p≤n1/p∥x∥∞, and n1/p→1 as p→∞.
The unit ball is the norm
A norm is determined by its unit ball B={x:∥x∥≤1}. By homogeneity, the ball of radius t is tB, and the norm of x is the smallest scaling factor needed for the ball to reach it: ∥x∥=min{t≥0:x∈tB}. Drawing the ball draws the norm.
Interactiveℓp unit balls and sparsity
Unit ball {x:∥x∥p≤1}
ball of ℓ1
ℓ1, ℓ2, ℓ∞ (reference)
scaled ball through x
Smallest ball touching the line a⊤x=h
line a⊤x=h
contact x∗: minimum ∥⋅∥p
minimum ∥⋅∥2 solution
Constraint line
∥x∥p of the purple point1.500
∥m∥p, with m=21(e1+e2)1.000
Dual exponent q∞
Solution x∗(1.23, 0.00)
Nonzero in x∗1 of 2
∥x∗∥p1.230
The ball touches the line at a vertex: the solution has a zero coordinate.
Left: the unit ball of ∥⋅∥p. Move p from 1/2 to ∞ and the ball changes from star to diamond, circle and square. The midpoint m of e1 and e2 tests convexity: for which p does it leave the ball? Drag the purple point: its norm is the factor needed to scale the ball (purple curve) to reach it. Right: press ‘Inflate the ball’ and see where it first touches the line a⊤x=h. For p≤1 contact lies on an axis, at a point with one zero coordinate; for p=2, at the foot of the perpendicular. Rotate the line: for p=1 contact jumps between vertices and ties only at 45°.
The ball’s shape decides whether the function is a norm. The first two properties can be checked directly; the third has an exact geometric interpretation.
Proof
If N satisfies the triangle inequality and x,y∈B, for t∈[0,1] we have N(tx+(1−t)y)≤tN(x)+(1−t)N(y)≤1, so the segment lies in B. Conversely, let B be convex and let x,y be nonzero (if one is zero there is nothing to prove). Vectors x/N(x) and y/N(y) lie in B, and with t=N(x)/(N(x)+N(y)) their convex combination is
tN(x)x+(1−t)N(y)y=N(x)+N(y)x+y∈B.
By homogeneity, N(x+y)≤N(x)+N(y).
∎
With p<1 the “ball” is a nonconvex star, and the formula for ℓp is no longer a norm. The counterexample is in the interactive: ∥e1∥p=∥e2∥p=1 but ∥e1+e2∥p=21/p>2; with p=1/2 it equals 4. Something similar happens to the so-called “ℓ0 norm”, the number of nonzero coordinates: it satisfies the triangle inequality but is not homogeneous, because ∥2x∥0=∥x∥0. It is a useful measure of sparsity but not a norm.
Why ℓ₁ produces zeros
The right panel solves min∥x∥p subject to a⊤x=h: inflate the ball until it touches the line, and the first contact is the solution. The ℓ1 ball has vertices on the axes, and a line in general position touches it first at a vertex, a point with a zero coordinate. The ℓ2 ball is round and contact is the foot of the perpendicular, x∗=ha/∥a∥22, which generally has no zeros.
In Rn with many linear constraints the same happens on a larger scale: minimizing ℓ1 selects solutions with many zero coordinates. This is the mechanism behind lasso, which penalizes ∥w∥1 and produces models with few nonzero weights, unlike ridge regression, which penalizes ∥w∥22 and shrinks all weights without zeroing them.
Norms induced by an inner product
Every inner product defines a norm, ∥v∥=⟨v,v⟩. Definiteness and homogeneity are immediate; the triangle inequality requires Cauchy–Schwarz, proved in the next section. These norms have a distinctive signature. Expanding by bilinearity gives ∥u±v∥2=∥u∥2±2⟨u,v⟩+∥v∥2. Adding the two versions yields the parallelogram law,
∥u+v∥2+∥u−v∥2=2∥u∥2+2∥v∥2,
and subtracting them yields the polarization identity,
⟨u,v⟩=41(∥u+v∥2−∥u−v∥2).
The parallelogram law says the sum of the squares of a parallelogram’s diagonals equals the sum of the squares of its four sides. Polarization says the norm determines the inner product. The Jordan–von Neumann theorem completes the picture: a norm comes from an inner product if and only if it satisfies the parallelogram law. Among the ℓp, only ℓ2 does.
ProofThe ℓ₁ norm cannot come from an inner product
Prove: There is no inner product on Rn (n≥2) with ⟨x,x⟩=∥x∥12 for every x.
0
Suppose there were. Find two vectors violating an identity satisfied by every induced norm.
Step 1 of 4. What identity does every norm induced by an inner product satisfy?
The Cauchy–Schwarz inequality
Cauchy–Schwarz turns an inner product into geometry: it bounds how closely two vectors can align. Before the statement, try to break it.
InteractiveCauchy–Schwarz live
x
y
unit circle
x−ty, length q(t)
Both sides: x⊤y≤∥x∥∥y∥
∣⟨x,y⟩∣2.940
∥x∥∥y∥4.186
Ratio: ∣cosθ∣=0.7023
q(t)=∥x−ty∥2≥0 for every t
Inner product
∣⟨x,y⟩∣2.940
∥x∥∥y∥4.186
cosθ0.7023
Angle θ45.4°
t∗=⟨x,y⟩/∥y∥20.872
Slack mintq(t)2.635
Strict inequality: slack is positive because x is not a multiple of y.
Try to make the magenta bar, ∣⟨x,y⟩∣, reach the gray one, ∥x∥∥y∥. You will succeed only with collinear vectors (press ‘Align’). Slide ty along the line of y: the purple segment is x−ty and its squared length is q(t), a parabola that never drops below zero. Its minimum at the foot of the perpendicular is the inequality's slack. In ‘Weighted’ mode the unit circle becomes an ellipse: find two vectors orthogonal under ⟨⋅,⋅⟩M and notice they do not form a right angle in the picture.
This is the Cauchy–Schwarz inequality. Its proof uses only the three axioms.
Proof
If u=0 or v=0, both sides are 0 and the vectors are dependent. Otherwise, let u^=u/∥u∥ and v^=v/∥v∥, of norm 1. By positivity and bilinearity,
0≤∥u^∓v^∥2=∥u^∥2∓2⟨u^,v^⟩+∥v^∥2=2∓2⟨u^,v^⟩,
so −1≤⟨u^,v^⟩≤1. Multiply by ∥u∥∥v∥>0 to obtain the inequality. Equality holds if and only if ⟨u^,v^⟩=±1, that is, if ∥u^∓v^∥=0 for one sign, meaning u^=±v^: the vectors are proportional. Conversely, if v=λu, both sides equal ∣λ∣∥u∥2.
∎
The interactive suggests another proof: the parabola q(t)=∥x−ty∥2 cannot be negative, forcing the inequality. Reconstruct it step by step.
ProofCauchy–Schwarz via the discriminant
Prove: For every real inner product, ∣⟨x,y⟩∣≤∥x∥∥y∥, with equality if and only if x and y are collinear.
0
If y=0 both sides are 0. Assume y=0.
Step 1 of 4. Which auxiliary function should we study?
Triangle inequality, angle and cosine similarity
The first consequence completes an earlier loose end: ⟨v,v⟩ is a norm. Indeed,
with equality if and only if one vector is a nonnegative multiple of the other.
The second is the definition of angle in any inner product space. For nonzero u,v, the quotient ⟨u,v⟩/(∥u∥∥v∥) lies in [−1,1], and their angle is the unique θ∈[0,π] with
cosθ=∥u∥∥v∥⟨u,v⟩.
That quotient is cosine similarity. It measures alignment and ignores lengths, and has an exact relationship to Euclidean distance between normalized vectors: if u^ and v^ have norm 1,
∥u^−v^∥2=2−2cosθ.
Distance decreases with cosine, so after normalization, ranking by cosine and by Euclidean distance gives the same order. Without normalization, length enters the distance. That is why most dense retrieval systems normalize embeddings, and why CLIP (Radford et al., 2021) compares images and text by cosine similarity of normalized embeddings.
Equivalent norms, different constants
On Rn all norms are equivalent: for any two norms there exist c,C>0 with c∥x∥a≤∥x∥b≤C∥x∥a for every x (the proof uses compactness of the unit sphere). For the three usual norms the constants are explicit:
∥x∥∞∥x∥1≤∥x∥2≤∥x∥1,≤n∥x∥2≤n∥x∥∞.
The first and last are immediate, and the second follows from (∑i∣xi∣)2≥∑ixi2. The third is Cauchy–Schwarz with sign vector s=sgn(x): ∥x∥1=s⊤x≤∥s∥2∥x∥2≤n∥x∥2, since ∥s∥2 is the square root of the number of nonzero coordinates. Equality holds when all ∣xi∣ coincide.
“Equivalent” means they define the same convergent sequences, not that they are interchangeable: in R768 the constant n is 27.7. Equivalence is a privilege of finite dimensions. In C[0,1], functions fk(t)=tk have max∣fk∣=1 but ∫01∣fk∣=1/(k+1)→0, so no constant bounds the maximum norm by the integral.
The dual norm
Cauchy–Schwarz says y⊤x does not exceed ∥y∥2 when ∥x∥2≤1. If we measure x with another norm, the bound changes, and the optimal bound has its own name.
The supremum is a maximum because the unit ball is compact. It is a norm: homogeneous, satisfies the triangle inequality because the supremum of a sum is at most the sum of suprema, and definite because, if y=0, vector x=y/∥y∥ gives y⊤x>0. Applying the definition to ±x/∥x∥ yields the generalized Hölder inequality, valid for all x,y∈Rn:
y⊤x≤∥x∥∥y∥∗.
Geometrically, ∥y∥∗ is the highest level attained by linear function x↦y⊤x over the ball: its level sets y⊤x=c are lines (hyperplanes in Rn) perpendicular to y, and the last to touch the ball is the supporting line.
InteractiveThe dual norm as a supporting line
unit ball of ℓ1
y
support line y⊤x=∥y∥∗
opposite line, y⊤x=−∥y∥∗
Dual exponent q∞
∥y∥q (formula)1.400
maxy⊤x on the ball (numerical)1.400
Maximizer x∗(1.00, 0.00)
With p=1 the ball is a diamond and contact is a vertex ±ek: ∥y∥∗=maxi∣yi∣=∥y∥∞.
Lines y⊤x=c are perpendicular to y; the magenta one is the last to touch the ball, at level ∥y∥∗. With p=1 contact is a vertex and the level is the largest ∣yi∣; with p=∞ it is a corner and the level is the sum of ∣yi∣. Compare the formula with the numerical maximum. Enable ‘Dual ball’: y always lies on the boundary of the ℓq ball of radius ∥y∥q. With ‘Check Hölder’, drag x and confirm y⊤x never exceeds ∥x∥p∥y∥q.Proof
In each case bound y⊤x on the ball and find an x attaining the bound.
(1) By Cauchy–Schwarz, y⊤x≤∥y∥2 if ∥x∥2≤1, and x=y/∥y∥2 attains it.
(2) If ∥x∥1≤1, y⊤x≤∑i∣yi∣∣xi∣≤maxi∣yi∣∑i∣xi∣≤∥y∥∞, and x=sgn(yk)ek, with k the index of the largest ∣yi∣, attains it: a vertex of the diamond. If ∥x∥∞≤1, y⊤x≤∑i∣yi∣∣xi∣≤∥y∥1, and corner x=sgn(y) attains it.
(3) First Young’s inequality: for a,b≥0, ab≤ap/p+bq/q. With a,b>0 it is concavity of the logarithm, log(ab)=p1logap+q1logbq≤log(pap+qbq), and with a=0 or b=0 it is trivial. For Hölder, homogeneity reduces the proof to ∥x∥p=∥y∥q=1, giving ∑i∣xiyi∣≤∑i(∣xi∣p/p+∣yi∣q/q)=p1+q1=1. The bound is attained at xi=sgn(yi)∣yi∣q−1/∥y∥qq−1: since (q−1)p=q, we have ∑i∣xi∣p=∑i∣yi∣q/∥y∥qq=1 and y⊤x=∑i∣yi∣q/∥y∥qq−1=∥y∥q.
∎
With y=(3,−1,2): on the ℓ1 ball the maximum of y⊤x is 3, at x=e1; on the ℓ∞ ball it is 6, at x=(1,−1,1); on the ℓ2 ball, 14≈3.74. Duality also explains the right panel of the first figure: by Hölder, any x with a⊤x=h satisfies ∣h∣≤∥x∥p∥a∥q, and scaling the maximizer on the supporting line attains equality, so
min{∥x∥p:a⊤x=h}=∥a∥q∣h∣.
The inflated ball’s contact point is, rescaled, the point on the unit ball where a⊤x reaches its maximum: the same picture read backwards.
Two practical uses of the dual norm:
Steepest descent. To take a step d with ∥d∥≤1 that decreases the linear approximation f(x)+∇f(x)⊤d as much as possible, minimize ∇f⊤d on the ball; the minimum is −∥∇f∥∗. In ℓ2 the step is −∇f/∥∇f∥2: gradient descent. In ℓ∞ it is −sgn(∇f), sign descent; with β1=β2=0 and ε→0, Adam’s step is exactly gi/gi2=sgn(gi). Choosing the norm chooses the optimizer, an idea developed in steepest descent in a general norm and extending to spectral-norm descent in modern optimizers.
Adversarial examples. An attacker who can change each pixel by at most ε seeks δ with ∥δ∥∞≤ε. Against a linear score w⊤x, the greatest possible change is ε∥w∥1, attained at δ=εsgn(w). Since ∥w∥1 grows with dimension, in an image with 224×224×3=150528 entries an imperceptible ε accumulates into a large score change. This is the linear explanation of Goodfellow et al. (2014), and εsgn(∇xL) is its fast gradient sign method.
Orthogonality
Orthogonality is perpendicularity without a picture: it works in R768, between functions and between matrices. Its first consequence is Pythagoras: expanding ∥u+v∥2=∥u∥2+2⟨u,v⟩+∥v∥2,
u⊥v⟺∥u+v∥2=∥u∥2+∥v∥2,
and, by induction, ∥∑ivi∥2=∑i∥vi∥2 for any orthogonal list.
Proof
If ∑icivi=0, taking the inner product with vj gives ∑ici⟨vi,vj⟩=cj∥vj∥2=0. Since vj is nonzero, cj=0 for each j.
∎
The converse is false: (1,0) and (1,1) are independent but not orthogonal. A consequence for high dimensions: a space of dimension d can hold at most d exactly orthogonal nonzero vectors.
Orthogonal complement
W⊥ is a subspace (combinations of vectors orthogonal to w remain orthogonal), and W∩W⊥={0}, since a vector in the intersection is orthogonal to itself. Also, if W=span{w1,…,wk}, to lie in W⊥ it suffices to be orthogonal to the generators: linearity does the rest.
Proof
Let w1,…,wk be a basis of W and T:V→Rk the linear map T(v)=(⟨v,w1⟩,…,⟨v,wk⟩). Its null space is exactly W⊥, and by the rank-nullity theorem, dimW⊥=n−rankT≥n−k. Since W and W⊥ share only the zero vector, the sum is direct and dim(W+W⊥)=k+dimW⊥≥n. Hence W+W⊥=V and exactly dimW⊥=n−k. Finally, W⊆(W⊥)⊥ by definition, and both have dimension n−(n−k)=k, so they coincide.
∎
The component w is the orthogonal projection of v onto W, the point in W closest to v. Computing it is the next lesson’s subject and what least-squares regression does.
The four subspaces in pairs
The theorem describes the four fundamental subspaces of A∈Rm×n. Ax=0 means each row satisfies a~i⊤x=0, so x is orthogonal to every row and hence their span. Applying the same to A⊤:
null(A)null(A⊤)=col(A⊤)⊥⊆Rn,=col(A)⊥⊆Rm.
Thus Rn=col(A⊤)⊕null(A) with dimensions r+(n−r): rank-nullity counts dimensions in an orthogonal decomposition. On the output side, Ax=b has a solution if and only if b∈col(A)=null(A⊤)⊥, that is, if b is orthogonal to every y with A⊤y=0. A single y with A⊤y=0 and y⊤b=0 certifies that the system is inconsistent.
InteractiveA subspace and its complement in R3
W=col(A⊤), row space
W⊥=null(A)
rows of A
v=w+w⊥
Rows of A
Dimensions
dimW=rankA2 (plane)
dimW⊥1 (line)
Decomposition
⟨w,w⊥⟩0.000
∥v∥28.750
∥w∥2+w⊥28.750
Aw⊥(0.00, 0.00)
Every row of A is perpendicular to W⊥: therefore Aw⊥=0 and null(A)=col(A⊤)⊥.
W is the row space of A (blue) and W⊥=null(A) its complement (red). Rotate the scene and drag the tip of v, or press ‘Another v’: it always splits into mutually perpendicular w∈W and w⊥∈W⊥, and the readouts confirm Pythagoras and Aw⊥=0. Switch to one row: plane and line exchange roles. Press ‘Dependent rows’: W becomes a line and W⊥ a plane, since their dimensions always sum to 3.
Orthonormal bases
In an arbitrary basis, finding a vector’s coordinates requires solving a system. In an orthonormal basis, inner products suffice.
Proof
Write v=∑jcjqj. The inner product with qi gives ⟨v,qi⟩=∑jcjδji=ci, which is (1). For (2), with u=∑iaiqi, bilinearity gives ⟨u,v⟩=∑i,jaicjδij=∑iaici, and by (1) ai=⟨u,qi⟩ and ci=⟨v,qi⟩. Item (3) is (2) with u=v.
∎
Since qi has norm 1, ⟨v,qi⟩=∥v∥cosθi is the signed length of the shadow of v on the line of qi. The theorem says that in an orthonormal basis, shadows are coordinates. In an arbitrary basis (b1,…,bn) this is not so: if v=∑jcjbj, the product with bi gives ⟨v,bi⟩=∑jgijcj. Calling the shadows si=⟨v,bi⟩, the coordinates solve
Gc=s,
where G is the basis’s Gram matrix. Coordinates equal shadows only when G=I. With an orthogonal but non-unit basis, G is diagonal and division suffices: ci=⟨v,bi⟩/∥bi∥2.
InteractiveCoordinates as shadows
v
⟨v,b1⟩b1
⟨v,b2⟩b2
sum of shadows
Deform the basis
G=[1001]
Gram matrix, gij=⟨bi,bj⟩
Shadows and coordinates
⟨v,b1⟩ and c11.93 | 1.93
⟨v,b2⟩ and c21.31 | 1.31
Error in sum of shadows0.000
Parseval
∥v∥25.440
⟨v,b1⟩2+⟨v,b2⟩25.440
Orthonormal basis: G=I, shadows are coordinates and Parseval holds.
With an orthonormal basis, shadows ⟨v,bi⟩ (orange and aqua bands placed tip to tail) reconstruct v exactly. Rotate the basis from the tip of b1 and drag v: error remains zero and Parseval holds. Now lengthen b2 or move its angle away from 90°: the sum of shadows (magenta point) separates from v and the Gram matrix ceases to be identity. Enable ‘True coordinates’: the oblique parallelogram gives c1 and c2, which no longer match the shadows.
In Rn with the dot product, if Q=[q1⋯qn], orthonormality is Q⊤Q=I, coordinates are Q⊤v and reconstruction is v=QQ⊤v. Inverting Q amounts to transposing it: it is an orthogonal matrix.
What happens to an orthonormal list that is not a basis? Let (q1,…,qk) be orthonormal and r=v−∑i=1k⟨v,qi⟩qi. Then ⟨r,qj⟩=⟨v,qj⟩−⟨v,qj⟩=0 for each j, and Pythagoras gives
∥v∥2=i=1∑k⟨v,qi⟩2+∥r∥2≥i=1∑k⟨v,qi⟩2,
the Bessel inequality, with equality if and only if v lies in the span of the qi. The sum ∑i⟨v,qi⟩qi is the projection of v onto that span and r is the perpendicular component of the preceding decomposition.
Every finite-dimensional inner product space has orthonormal bases; the algorithm constructing them from any basis is Gram–Schmidt orthogonalization. The theorem also works for functions: in C[−π,π] with ⟨f,g⟩=∫−ππfg, functions 2π1, πcoskt and πsinkt are orthonormal, and Fourier series coefficients are exactly shadows ⟨f,qk⟩.
High-dimensional geometry
Pictures in R2 and R3 faithfully depict two or three vectors: they live in a plane or a three-dimensional space within Rd. What does not carry over are claims about many vectors at once or about volumes. Take independent x,y∈Rd with independent components of mean 0 and variance 1, for example x,y∼N(0,Id), and measure.
Lengths concentrate
Since E[xi2]=1, E∥x∥2=d. The terms xi2 are independent, so Var∥x∥2=dVar(x12)=d(E[x14]−1), equal to 2d for the Gaussian, whose fourth moment is 3. Then ∥x∥2/d=1±2/d and, with 1+ε≈1+ε/2,
d∥x∥≈1±2d1,
that is, ∥x∥≈d±1/2.
Absolute fluctuation does not grow with d. In d=768, ∥x∥≈27.7±0.71: a Gaussian vector lives in a thin shell of radius d, even though its density is highest at the origin. There is no contradiction: volume at distance r grows as rd−1, more than compensating for the density’s decline. This is norm concentration.
Angles concentrate around 90°
The product x⊤y is a sum of d independent terms xiyi with mean 0. Try predicting each step:
E[x⊤y]=i=1∑dE[xi]E[yi]=0
Linearity of expectation and independence of xi and yi.
1/4
For Gaussians the result is exact. By rotational invariance, u^=x/∥x∥ is uniform on the sphere. Fix y and rotate axes so it points along e1: the distribution of x is unchanged and cosθ becomes coordinate u^1. Since ∑iu^i2=1 and the d coordinates are exchangeable, E[u^12]=1/d, and by symmetry E[u^1]=0:
Var(cosθ)=d1exactamente.
Since θ=arccos(cosθ)≈90°−π180°cosθ near 90°, the angle’s standard deviation is approximately πd180°. In d=768, the angle between two random vectors is 90°±2.1°. More precisely, the density of θ on [0,π] is proportional to sind−2θ: with d=2 it is uniform, and for large d it is an increasingly narrow bell around π/2. This is near-orthogonality in high dimensions.
InteractiveAlmost everything is orthogonal in high dimensions
Angle between the two vectors in each pair (degrees)
simulation
exact density ∝sind−2θ
Norm divided by d
simulation
exact density (chi with d degrees)
Cosines among 32 random vectors, cosθij
The diagonal is 1: each vector compared with itself. Off the diagonal, grayer means closer to orthogonal.
Standard deviation of cosθ versus d (log-log scale)
prediction 1/d
previous estimates
current d
Components
Simulated pairs2000 / 2000
Mean angle90.26°
Angle standard deviation10.30°
Prediction πd180°10.13°
Standard deviation of cosθ0.1769
1/d0.1768
∥x∥/d: mean, SD0.992, 0.122
1/2d0.125
Max. ∣cos∣ among 32 vectors0.490
Each pair consists of two random vectors in Rd with independent components. Increase d from 32 to 768 (the embedding dimension of small GPT-2) and 4096: the angle histogram narrows around 90°, the ∥x∥/d histogram around 1, and the cosine matrix of 32 vectors approaches identity. Decrease to d=2 or 3 to recover planar and spatial intuition. Each visited d adds a point to the log-log plot, falling on the 1/d line. Switch to ‘Signs ±1’: length no longer fluctuates (it is exactly d), but the angle law is the same.
With signs ±1 the calculation is also exact: ∥x∥=d always, cosθ=x⊤y/d and Var(cosθ)=d/d2=1/d. The law does not depend on Gaussianity, but on summing many independent zero-mean terms.
How many nearly orthogonal vectors fit?
At most d can be exactly orthogonal. Far more can be nearly orthogonal. For a vector uniform on the sphere, the measure of cap {u^1≥ε} is at most e−dε2/2 for 0≤ε<1 (Ball, 1997, lemma 2.2), so P(∣cosθ∣≥ε)≤2e−dε2/2 for two random vectors. With N vectors there are fewer than N2/2 pairs, and the union bound gives
P(∃i=j:∣cosθij∣≥ε)<N2e−dε2/2,
which is less than 1 if N<edε2/4. If failure probability is less than 1, a configuration exists that does not fail: R768 can contain more than 3×107 unit vectors with ∣cosθ∣<0.3 between all of them. The number grows exponentially in d. This geometry underlies the Johnson–Lindenstrauss lemma and the superposition hypothesis, according to which a network can represent far more features than dimensions using nearly orthogonal directions (Elhage et al., 2022).
Volume lives in the shell
The volume of a ball of radius r in Rd is rd times that of the unit ball. The fraction of unit-ball volume in the shell 1−ε≤∥x∥≤1 is
1−(1−ε)d≥1−e−εd.
For d=768 and ε=0.01 it is 0.99956: almost all volume is within 1% of the boundary. The ball occupies a tiny fraction of its containing cube [−1,1]d: 0.79 in the plane, 0.0025 in d=10 and 2.5×10−8 in d=20. Cube corners (±1,…,±1) lie at distance d from the center. Any method that samples a grid or rejects cube points to retain those in a ball soon becomes impractical.
Distances concentrate
Since ∥x−y∥2=∥x∥2+∥y∥2−2x⊤y=2d±O(d), all distances between random points resemble 2d, and the ratio between farthest- and nearest-neighbor distance tends to 1. For unstructured data “nearest neighbor” loses meaning. Neighbor search works with real embeddings because they are not isotropic noise: they concentrate near structures with intrinsic dimension much lower than d.
Why scale by 1/√d?
The Var(x⊤y)=d rule appears whenever a network sums d products:
Attention. Scores q⊤k have standard deviation dk if components are independent with variance 1. Without scaling, for dk=64 logits would have deviation 8, softmax would saturate at the maximum and gradients would be nearly zero. Dividing by dk restores variance 1: this is scaled dot-product attention.
Initialization. A neuron’s preactivation is ∑i=1dinwixi, with variance dinVar(w)Var(x) if everything is independent and centered. To prevent growth or decay across layers, weight variance is proportional to 1/din (for example 2/din in He initialization for ReLU): this is variance propagation.
Normalization.RMSNorm divides each activation by ∥x∥/d, a coordinate’s typical scale, making each component order 1 regardless of d.
Reading similarities. Between random vectors, cosine has deviation 1/d: in d=768, cosine 0.3 is more than 8 deviations from noise. Real embeddings are not isotropic (they often share dominant directions), so typical cosine between unrelated texts may be much greater than 0. Measure the baseline from data.
Implementation from scratch
Start with ℓp norms. The numerical precaution is to avoid raising large numbers to high powers: factor out the maximum, ∥x∥p=m∥x/m∥p with m=∥x∥∞, leaving all terms in [0,1].
[ ]ℓp norms from scratchBrowser
import numpy as np
rng = np.random.default_rng(0)
def lp_norm(x, p):
"""Norma l_p (p >= 1 o np.inf). Factoriza el máximo: no desborda."""
a = np.abs(np.asarray(x, dtype=float))
m = a.max()
if p == np.inf or m == 0:
return float(m)
return float(m * ((a / m) ** p).sum() ** (1 / p))
x = np.array([3.0, -4.0, 0.0, 1.0])
for p in [1, 2, 3, np.inf]:
propia, ref = lp_norm(x, p), np.linalg.norm(x, p)
print(f"p = {p}: propia {propia:.6f} NumPy {ref:.6f}")
# la cadena de desigualdades, en n = 1000
n = 1000
z = rng.standard_normal(n)
n1, n2, ninf = lp_norm(z, 1), lp_norm(z, 2), lp_norm(z, np.inf)
cadena = ninf <= n2 <= n1 <= np.sqrt(n) * n2 <= n * ninf
print("inf <= 2 <= 1 <= sqrt(n)·2 <= n·inf:", cadena)
print(f"norma 1 / norma 2 = {n1 / n2:.1f} (cota sqrt(n) = {np.sqrt(n):.1f})")
The quotient ∥z∥1/∥z∥2 of a Gaussian vector lies near 2n/π≈25.2, below the bound n≈31.6, attained only when all ∣zi∣ are equal. Now for the signature of an inner product: the parallelogram law and polarization.
[ ]Parallelogram and polarizationBrowser
def paralelogramo(x, y, p):
"""Los dos lados de la ley del paralelogramo para la norma l_p."""
izq = lp_norm(x + y, p) ** 2 + lp_norm(x - y, p) ** 2
der = 2 * lp_norm(x, p) ** 2 + 2 * lp_norm(y, p) ** 2
return izq, der
e1, e2 = np.eye(2)
for p in [1, 2, 3, np.inf]:
izq, der = paralelogramo(e1, e2, p)
print(f"p = {p}: {izq:.4f} frente a {der:.4f}")
# la norma euclídea determina el producto escalar
u, v = rng.standard_normal(6), rng.standard_normal(6)
polarizado = (lp_norm(u + v, 2) ** 2 - lp_norm(u - v, 2) ** 2) / 4
print(f"polarización {polarizado:.12f} u @ v {u @ v:.12f}")
The Frobenius product can be calculated in equivalent ways with different costs. tr(A⊤B) forms the entire product A⊤B, of n×n, to keep its diagonal: O(mn2) operations. Summing entrywise products costs O(mn).
[ ]The Frobenius productBrowser
import time
A = rng.standard_normal((400, 300))
B = rng.standard_normal((400, 300))
def cronometra(f, rep=5):
t0 = time.perf_counter()
for _ in range(rep):
r = f()
return r, (time.perf_counter() - t0) / rep
formas = {
# O(m n^2): forma la matriz A.T @ B, de 300 x 300, para sumar su diagonal
"tr(A.T @ B)": lambda: np.trace(A.T @ B),
# O(m n): entrada a entrada
"sum(A * B)": lambda: np.sum(A * B),
"einsum ij,ij->": lambda: np.einsum("ij,ij->", A, B),
# producto escalar de las dos matrices aplanadas
"vec(A) @ vec(B)": lambda: A.ravel() @ B.ravel(),
}
for nombre, f in formas.items():
r, t = cronometra(f)
print(f"{nombre:16s} {r:12.6f} {t * 1e3:8.3f} ms")
All give the same number (up to rounding), and trace is by far the slowest: a classic performance mistake when translating a paper’s formula into code. Finally, the dual norm: the maximum of y⊤x over many points on the ℓp sphere approaches ∥y∥q from below, and the proof’s maximizer attains it.
[ ]The dual norm numericallyBrowser
def exponente_dual(p):
return np.inf if p == 1 else (1.0 if p == np.inf else p / (p - 1))
def maximizador(y, p):
"""Punto de la bola unidad de l_p donde y @ x alcanza su máximo."""
if p == 1:
k = np.argmax(np.abs(y))
x = np.zeros_like(y)
x[k] = np.sign(y[k])
return x
if p == np.inf:
return np.sign(y)
q = exponente_dual(p)
return np.sign(y) * np.abs(y) ** (q - 1) / lp_norm(y, q) ** (q - 1)
def normas_filas(X, p):
if p == np.inf:
return np.max(np.abs(X), axis=1)
return (np.abs(X) ** p).sum(axis=1) ** (1 / p)
y = np.array([3.0, -1.0, 2.0])
X = rng.standard_normal((200_000, 3))
for p in [1, 1.5, 2, 3, np.inf]:
q = exponente_dual(p)
esfera = X / normas_filas(X, p)[:, None] # 200 000 puntos con norma l_p 1
xs = maximizador(y, p)
print(f"p = {p:>4}: máx. muestreado {(esfera @ y).max():.4f}"
f" y @ x* = {y @ xs:.4f} norma l_q = {lp_norm(y, q):.4f}")
Nearest neighbors by cosine similarity
The first lab builds cosine-similarity search over scikit-learn’s 1797 handwritten digits: each 8×8 image is a vector in R64. The recipe is the same as for any vector database: normalize rows once, compute all similarities with one matrix multiplication, and retain the largest k of each row. For that, np.argpartition selects the largest k in linear time without sorting the full row; only those k are then sorted.
[ ]Setup: scikit-learnBrowser
import sklearn # en el navegador, la primera importación tarda unos segundos
print("scikit-learn", sklearn.__version__)
[ ]The data: 1797 vectors in R^64Browser
from sklearn.datasets import load_digits
digitos = load_digits()
E = digitos.data.astype(float) # 1797 x 64, intensidades de 0 a 16
etiquetas = digitos.target
def normaliza_filas(M, eps=1e-12):
n = np.linalg.norm(M, axis=1, keepdims=True)
return M / np.maximum(n, eps) # protege las filas nulas
normas = np.linalg.norm(E, axis=1)
print("forma:", E.shape)
print(f"longitudes entre {normas.min():.1f} y {normas.max():.1f}")
En = normaliza_filas(E)
print("tras normalizar:", np.allclose(np.linalg.norm(En, axis=1), 1.0))
[ ]Cosine-similarity searchBrowser
# 1797 x 1797: todas las similitudes coseno con un solo producto
S = En @ En.T
np.fill_diagonal(S, -np.inf) # nadie cuenta como vecino de sí mismo
def topk(M, k):
"""Índices de los k mayores de cada fila de M, de mayor a menor."""
cand = np.argpartition(-M, k, axis=1)[:, :k] # los k mayores
vals = np.take_along_axis(M, cand, axis=1)
orden = np.argsort(-vals, axis=1) # se ordenan solo esos k
return np.take_along_axis(cand, orden, axis=1)
k = 5
vecinos = topk(S, k)
acierto = (etiquetas[vecinos[:, 0]] == etiquetas).mean()
print(f"el más parecido es el mismo dígito en el {100 * acierto:.1f} %")
print("vecinos de la imagen 0, que es un", etiquetas[0], ":", vecinos[0])
print("sus etiquetas:", etiquetas[vecinos[0]])
# tras normalizar, la distancia ordena igual: |a - b|^2 = 2 - 2 cos
D2 = 2.0 - 2.0 * S # la diagonal pasa a +inf: tampoco cuenta
por_distancia = topk(-D2, k) # los k más cercanos en distancia euclídea
# se comparan similitudes y no índices: hay imágenes repetidas que empatan
s_dist = np.take_along_axis(S, por_distancia, axis=1)
s_cos = np.take_along_axis(S, vecinos, axis=1)
print("mismos k vecinos por distancia que por coseno:",
np.allclose(s_dist, s_cos))
What if vector length changes for a reason unrelated to content? Simulate different brightness in each image by multiplying each row by a random factor between 0.5 and 2. Cosine similarity is invariant to this change; unnormalized Euclidean distance is not.
[ ]Length enters the distanceBrowser
brillo = rng.uniform(0.5, 2.0, size=(len(E), 1))
Eb = E * brillo
def vecino_euclideo(M):
sq = np.sum(M * M, axis=1)
D = sq[:, None] + sq[None, :] - 2.0 * (M @ M.T)
np.fill_diagonal(D, np.inf)
return np.argmin(D, axis=1)
def vecino_coseno(M):
Mn = normaliza_filas(M)
C = Mn @ Mn.T
np.fill_diagonal(C, -np.inf)
return np.argmax(C, axis=1)
for nombre, M in [("original", E), ("con brillo", Eb)]:
ae = (etiquetas[vecino_euclideo(M)] == etiquetas).mean()
ac = (etiquetas[vecino_coseno(M)] == etiquetas).mean()
print(f"{nombre:11s} euclídea sin normalizar {100 * ae:.1f} %"
f" coseno {100 * ac:.1f} %")
iguales = np.array_equal(vecino_coseno(E), vecino_coseno(Eb))
print("el coseno da exactamente los mismos vecinos:", iguales)
Euclidean distance’s accuracy falls by around one percentage point, because shape matters more than brightness for these digits. The danger is that error is silent and grows with length variation (with factors between 0.25 and 4, the rate drops to about 96.5%), while cosine gives exactly the same neighbors.
Concentration in high dimensions
The second lab measures the theory’s predictions: standard deviation of cosine and of ∥x∥/d as d increases, the log-log slope and distance collapse.
[ ]Measuring the 1/sqrt(d) lawBrowser
import matplotlib.pyplot as plt
ds = np.array([2, 4, 8, 16, 32, 64, 128, 256, 512, 1024])
n_pares = 2000
sd_cos, sd_norma = [], []
for d in ds:
X = rng.standard_normal((n_pares, d))
Y = rng.standard_normal((n_pares, d))
nx, ny = np.linalg.norm(X, axis=1), np.linalg.norm(Y, axis=1)
# un coseno por par, sin bucles
cos = np.einsum("ij,ij->i", X, Y) / (nx * ny)
sd_cos.append(cos.std())
sd_norma.append((nx / np.sqrt(d)).std())
pendiente, ordenada = np.polyfit(np.log(ds), np.log(sd_cos), 1)
c = np.exp(ordenada)
print(f"ajuste log-log: desv(cos) ≈ {c:.3f} · d^({pendiente:.3f})")
print("teoría: desv(cos) = 1 · d^(-0.5)")
plt.loglog(ds, sd_cos, "o", label="desv. típica de cos θ (simulada)")
plt.loglog(ds, 1 / np.sqrt(ds), "--", label="1/√d")
plt.loglog(ds, sd_norma, "s", label="desv. típica de ‖x‖/√d (simulada)")
plt.loglog(ds, 1 / np.sqrt(2 * ds), ":", label="1/√(2d)")
plt.xlabel("dimensión d"); plt.ylabel("desviación típica"); plt.legend()
plt.title("Concentración de ángulos y longitudes")
plt.show()
[ ]Distances and shell volumeBrowser
print("(más lejano - más cercano) / más cercano, 1000 puntos:")
for d in [2, 10, 100, 1000]:
P = rng.standard_normal((1000, d))
q = rng.standard_normal(d)
dist = np.linalg.norm(P - q, axis=1)
print(f" d = {d:4d}: {(dist.max() - dist.min()) / dist.min():7.3f}")
print("200 000 puntos uniformes en el cubo [-1, 1]^d:")
print(" d en la bola puntos corteza 0.9-1 teoría 1 - 0.9^d")
for d in [2, 3, 5, 8, 10]:
P = rng.uniform(-1, 1, size=(200_000, d))
r = np.linalg.norm(P, axis=1)
dentro = r <= 1
corteza = (r[dentro] >= 0.9).mean()
print(f" {d:2d} {dentro.mean():10.4f} {dentro.sum():6d}"
f" {corteza:13.3f} {1 - 0.9 ** d:16.3f}")
for d in [768, 4096]:
print(f"d = {d}: fracción de la bola con r < 0.99: {0.99 ** d:.2e}")
In d=10 only 0.25% of cube points lie inside the ball: rejection sampling, which accepts 79% in the plane, is already impractical, so the formula is used thereafter.
The professional version
In practice a library computes norms and similarities. What matters is knowing what each function returns and how it matches the mathematics:
Two details cause silent errors. First, SciPy and scikit-learn’s “cosine distance” is 1−cosθ, not cosine: ascending distance order equals descending similarity order. Second, np.linalg.norm computes x⊤x directly, so squaring may overflow even when the norm is representable. scipy.linalg.norm uses BLAS routine nrm2, which rescales to prevent this. The case relevant to large models is half precision: in float16 the largest finite number is 65504, and a 768-component embedding of tens has ∥x∥2=76800.
[ ]Library equivalents and numerical trapsBrowser
import scipy.linalg
from scipy.spatial.distance import cdist
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import normalize
Q = E[:5]
S_propia = normaliza_filas(Q) @ normaliza_filas(E).T
print("cosine_similarity == la nuestra:",
np.allclose(cosine_similarity(Q, E), S_propia))
print("cdist 'cosine' == 1 - cos:",
np.allclose(cdist(Q, E, "cosine"), 1 - S_propia))
print("normalize == normaliza_filas:",
np.allclose(normalize(E), normaliza_filas(E)))
nn = NearestNeighbors(n_neighbors=6, metric="cosine").fit(E)
_, idx = nn.kneighbors(Q) # el primero es la propia consulta
print("mismos 5 vecinos que nuestro buscador:",
np.array_equal(idx[:, 1:], vecinos[:5]))
with np.errstate(over="ignore"):
grande = np.array([3e200, 4e200])
print("np.linalg.norm: ", np.linalg.norm(grande))
print("scipy.linalg.norm:", scipy.linalg.norm(grande))
print("lp_norm: ", lp_norm(grande, 2))
e16 = np.full(768, 10.0, dtype=np.float16)
print("float16:", np.linalg.norm(e16),
" en float32:", np.linalg.norm(e16.astype(np.float32)))
Practical rule: normalize in float32 even if the model uses float16 or bfloat16, and protect division by the norm with ε (for example, PyTorch’s F.normalize divides by max(∥x∥,ε)). In a vector database with millions of rows, normalizing once at indexing turns cosine similarity into a dot product, which approximate indexes and GPUs compute faster.
Common mistakes
Exercises
QuizWhich are norms?
Which functions are norms on Rn (with n≥2)?
More than one answer may be correct.
QuizWhich matrices define an inner product?
For which matrices M is ⟨x,y⟩=x⊤My an inner product on R2?
More than one answer may be correct.
NumericA Frobenius product
Calculate ⟨A,B⟩F for A=[20−13] and B=[1−242].
NumericMaximum over the ℓ₃ ball
Let y=(3,−1,2). What is the maximum of y⊤x over all x∈R3 with ∥x∥3≤1?
NumericA coordinate without solving systems
In the orthonormal basis q1=31(1,2,2), q2=31(2,1,−2), q3=31(2,−2,1), what is the third coordinate of v=(1,4,−2)?
NumericDimension of a complement
Let W={x∈R5:x1+x2+x3=0,x4=x5}. What is the dimension of W⊥?
QuizOrthogonality and independence
Which statements are true?
More than one answer may be correct.
QuizThe norm determines the step
Let g=0 be the gradient of f at a point. Which step d with ∥d∥∞≤1 minimizes the linear approximation g⊤d, and what is the minimum?
NumericCosine spread in dimension 768
Let x,y∼N(0,I768) be independent. What is the standard deviation of their cosine similarity?
CodeThe k most similar, vectorized
Implement cosine_topk(E, Q, k): E is an (n, d) embedding matrix and Q an (m, d) query matrix. Return an integer array (m, k) containing, for each query, indices of the k rows of E with highest cosine similarity, descending. Rules: a zero vector has similarity 0 to everything (no nan or division warnings); ties put the smaller index first; assume k <= n. No Python loops over rows or queries.
import numpy as np
def cosine_topk(E, Q, k):
# 1. normaliza las filas de E y de Q (cuidado con las filas nulas)
# 2. todas las similitudes con un producto de matrices
# 3. ordena cada fila de mayor a menor, con desempate estable
...
Shift+Enter to run
Summary
Key idea
An inner product is the minimum needed to discuss lengths, angles and perpendicularity; everything deduced from its three axioms (Cauchy–Schwarz, Pythagoras, coordinates as shadows) holds for vectors, functions, matrices and random variables. In high dimensions the same geometry says random vectors have nearly fixed lengths and are almost orthogonal, with deviations of order 1/d.
An inner product is a symmetric positive definite bilinear form; in finite dimensions it is a symmetric positive definite Gram matrix. The Frobenius product, tr(A⊤B)=∑ijaijbij, defines gradients with respect to matrices.
A norm is definite, homogeneous and triangular, and its unit ball determines it: the triangle inequality is equivalent to ball convexity. Vertices of the ℓ1 ball explain why minimizing ℓ1 produces zeros; ℓ0 and ℓp with p<1 are not norms.
Cauchy–Schwarz, ∣⟨u,v⟩∣≤∥u∥∥v∥ with equality only for collinear vectors, gives the triangle inequality, angle and cosine similarity. After normalization, cosine and Euclidean distance yield the same ranking.
The dual norm, ∥y∥∗=sup∥x∥≤1y⊤x, pairs ℓ1 with ℓ∞, ℓ2 with itself and ℓp with ℓq; it determines the steepest descent step and the effect of an attack bounded in ℓ∞.
V=W⊕W⊥ with complementary dimensions; the four subspaces form two pairs of orthogonal complements. In an orthonormal basis coordinates are inner products and Parseval holds; in an arbitrary basis solve Gc=s.
In Rd, ∥x∥≈d±1/2 and cosθ≈0±1/d for random vectors; ball volume lies in the shell and distances concentrate. This explains attention’s 1/dk, initializations with variance ∝1/din and the need to measure a similarity baseline.