High-Dimensional Geometry

At 768 dimensions, two random directions have a typical cosine of 0.03. Every document sits at almost the same distance from your query. A quarter of a corpus is nobody’s neighbour. The space has huge room and tiny contrast.

Drag the dimension from 2 to 3,072 and watch three intuitions break at once. Then we build each one from zero: the thin shell, near-orthogonality, random projection, hubs, and the checks you run on a real embedding space.

You need a vector as a list of numbers, the dot product and a little Python. We build the rest from zero.

Turn the dimension dial

50

Your browser samples the cosines and distances live from random Gaussian vectors, 1,200 per setting. The orphan shares come from a seeded numpy run: 1,000 Gaussian points, k = 10, averaged over 3 seeds.

Chapter 0

Three Impossible Things

Read three bug reports from a vector search system and see that each one is a theorem

You run search over one million support articles. An embedding model turned each article into a vector: a list of 3,072 numbers. A query becomes a vector the same way. You return the ten articles that point most nearly in the query’s direction. It works. Then three tickets arrive.

  1. “Every score is the same.” The cosine similarity of two vectors is the cosine of the angle between them: 1 for the same direction, 0 for a right angle. For random pairs of articles it falls inside ±0.05 in 99 cases of 100.
  2. “Near and far are the same distance.” For one query, the closest of the million articles is at distance 74.3 and the farthest at 83.0. The worst match is only 12% farther than the best.
  3. “Article 41,208 is in everything.” One generic page sits in the top ten for a huge share of queries. A quarter of the corpus is in nobody’s top ten.

None of these is a bug. In a plane, two random directions have a typical absolute cosine of 2/π, which is 0.64. At 3,072 dimensions it is 0.014, which is 44 times smaller. Draw some pairs and see it.

Spin two random arrows

Left: the last random pair in a plane. Right: grey bars are absolute cosines in a plane, purple bars in d dimensions. Pick d, then draw more pairs.

Each pair is uniform on the sphere. The exact values come from the closed form for the mean absolute cosine.

One sentence explains all three tickets: in high dimensions, almost every quantity you measure becomes almost constant. A ranking needs differences, and the differences shrink. The name for this is concentration of measure.

Two of the three effects help you. Near-orthogonality gives a vector room for millions of concepts. Concentration makes random projection safe. Only hubness is pure damage. The hero shows the worst case, with independent coordinates. Real embeddings have structure, and that is why search still works.

  1. The thin shell: almost all of a ball’s volume sits near its surface.
  2. Near and far look the same: distances from a query concentrate.
  3. Near-orthogonality: random directions are almost perpendicular, so millions fit.
  4. The Johnson-Lindenstrauss lemma: a random matrix shrinks vectors and keeps distances.
  5. Projection in production: random projection, PCA, Matryoshka and the two-stage funnel.
  6. Hubness: why a few documents appear in everyone’s results.
  7. CSLS and mutual proximity: subtract the head start.
  8. t-SNE and UMAP lie: what a 2D map can and cannot show.
  9. Diagnosing your space: five numbers to measure on a real model.
  10. Field guide: the formulas, the code, the checklist.
Random pairs of documents in a 1,024-dimensional space almost always have a cosine between −0.1 and +0.1. What should you conclude?

Chapter 1

The Thin Shell

Raise a number a little below 1 to a large power and watch the inside of a ball empty out

Hold an orange with a 40 mm radius and a 3 mm peel. The flesh is a ball with 92.5% of the radius. Volume grows with the cube of the radius, so the flesh is 0.925³ = 0.79 of the orange. The peel is 21%. Give the orange 768 dimensions and the same peel, and the peel is all of it.

Scale a shape by a factor s in each of its d directions and its volume scales by s to the d. Double a square and its area grows 4 times. Double a cube and its volume grows 8 times.

Call the number of dimensions d. Call the thickness of the outer layer, as a share of the radius, t. The shell is the region between radius (1 − t) and the full radius.

Say it aloud

The shell share equals one minus, one minus t, to the d.

shell
the shell share the share of the ball’s volume in the outer layer, from 0 to 1.
1 − t
one minus t the inner ball’s radius as a share of the full radius. t is the layer’s thickness: 0.05 for the outer 5%.
d
to the d multiply it by itself once for each dimension, d from 1 to 3,072 here.
In plain words

Shrink the radius to 1 − t. Raise it to the power d: that is the share of volume inside. One minus that share is the shell.

With numbers

Take t = 0.05. At d = 100, 0.95100 = 0.0059, so the shell holds 99.4%. At d = 768, 0.95768 = 7.8 × 10−18. The inside is empty.

Slide the mass into the rind

The curve shows how much volume sits at each radius. The warm area is the shell. Raise d and watch the volume crowd against the surface.

10
5%

Exact: the volume at radius r grows like r to the power d − 1, and the shares are closed forms.

Embeddings are not uniform in a ball. Take the cloud our devices use, the isotropic Gaussian: each coordinate is an independent bell-curve draw with mean 0 and variance 1. Its squared length adds d terms that each average 1, so the length is about √d. Each term has variance 2, and that pins the spread of the length near 0.71 at every d.

d√dmeasured mean lengthmeasured spread
21.411.250.66
103.163.080.70
10010.009.990.71
76827.7127.710.70
3,07255.4355.420.71

The mean grows and the spread stands still. The cloud is a soap bubble of radius √d and thickness about 0.7.

The failure. You use the mean embedding as “the typical document”, and it matches nothing. Measure its length: a real 768-dimensional Gaussian vector has length near 27.7, but the mean of 10,000 of them has length near 0.28. Fix it with a real document near the centre (a medoid), or compare directions only.

In d = 200 dimensions, about what share of a ball’s volume lies in the outer 2% of its radius?

Chapter 2

Near and Far Look the Same

Expand one squared distance and find that the spread of distances does not grow while their mean does

Ticket two said the best and worst matches sat at almost the same distance. The bubble explains it: every document lies on the same thin shell, and so does the query.

A squared distance is the query’s squared length, plus the document’s squared length, minus twice their dot product. Over the corpus, the document’s squared length has variance 2d. The dot-product term has variance 4d. So the squared distance averages 2d with variance 6d, and the distance itself has a spread of 0.87 at every d.

Call the spread of the distances divided by their mean the relative spread. It says how much room a ranking has.

Say it aloud

The relative spread equals zero point six one two over root d.

relative spread
relative spread the spread of the distances from one query to all documents, divided by their mean.
0.612
zero point six one two the fixed spread 0.866 divided by √2, which comes from the mean distance √(2d).
√d
root d the square root of the number of dimensions.
In plain words

The spread of distances stays at 0.87. Their mean grows like √(2d). Divide the one by the other, and the relative spread falls like one over root d.

With numbers

At d = 768: 0.612 / 27.71 = 0.022, so distances vary by about 2.2% of their mean. A seeded run with 10,000 documents gives 2.23%. At d = 3,072 it is 1.1%.

Squeeze the distances

Blue bars are the distances from one query to 2,000 documents, divided by their mean. Raise d and watch nearest and farthest close in.

10

Sampled live from Gaussian vectors, the worst case with independent coordinates.

A ranker feels the relative contrast: farthest minus nearest, over nearest. With 10,000 documents it falls from 4.4 at d = 10 to 0.56 at d = 100, 0.19 at d = 768 and 0.087 at d = 3,072. Beyer and coauthors proved the limit in 1999: as the relative spread goes to 0, farthest over nearest goes to 1.

Why does search still work? Real embeddings lie near a curved surface with far fewer degrees of freedom, the intrinsic dimension. Concentration follows the intrinsic dimension, not the storage width.

The failure. A fixed cutoff (“return documents closer than 0.8”) returns everything or nothing. Measure the relative spread on your corpus with the code below. If it matches 0.612/√d, the encoder carries no structure, and the problem is upstream.

pythonimport numpy as np

def concentration_report(X, n_probe=200, seed=0):   # X: (n, d) embeddings
    rng = np.random.default_rng(seed)
    n, d = X.shape
    rel = []
    for i in rng.choice(n, n_probe, replace=False):
        dist = np.delete(np.linalg.norm(X - X[i], axis=1), i)   # (n-1,)
        rel.append(dist.std() / dist.mean())
    return {"relative_spread": float(np.median(rel)),
            "noise_prediction": 0.612 / np.sqrt(d)}          # far larger = real structure
You widen your embeddings from 384 to 768 numbers, but the data’s intrinsic dimension stays the same. What happens to distance concentration on your corpus?

Chapter 3

Near-Orthogonality

Derive the spread of a random cosine in one line, then count how many almost-perpendicular directions fit

A 768-wide vector has exactly 768 perpendicular directions. Yet a sentence encoder keeps millions of topics apart. It does not need exact right angles, only angles close enough to 90° that one direction does not leak into another.

Take two random unit vectors (length 1). Rotate the space so the first one points along the first axis. Now their cosine is the second vector’s first coordinate. Its d squared coordinates add to exactly 1, and by symmetry each square averages 1/d.

Call the cosine between two random directions cos θ, and its standard deviation over many pairs its spread.

Say it aloud

The spread of cos theta equals one over root d.

sd(cos θ)
the spread of cos theta the standard deviation of the cosine between two random unit vectors.
1 / √d
one over root d one divided by the square root of the number of dimensions.
In plain words

The d coordinates share the total squared length, 1. Each gets 1/d on average. So a typical coordinate, and so a typical cosine, has size one over root d.

With numbers

At d = 768: 1/27.71 = 0.036. A seeded run of 20,000 pairs gives 0.0359. At d = 3,072 the spread is 0.018.

Narrow the cosines, count the room

Purple is the exact distribution of a random cosine. Red marks pairs more aligned than your tolerance ε. Try d = 2, then 3, then 768.

10
0.30

The curve is the exact density, proportional to (1 − t²) to the power (d − 3)/2. The count uses the union bound below with δ = 0.01.

How many directions fit if every pair must stay within ε of perpendicular? Draw them at random. One pair fails with chance at most 2e−dε²/2, and N vectors make fewer than N²/2 pairs. Call the count N and the allowed chance that any pair fails δ.

Say it aloud

N is at most root delta times e to the d epsilon squared over four.

N
N how many random directions you can draw so that every pair has an absolute cosine of at most ε.
√δ
root delta the square root of the allowed failure chance; δ = 0.01 means it works 99 times in 100.
edε²/4
e to the d epsilon squared over four the exponential of d times ε squared, divided by 4; ε is the tolerance, such as 0.3.
In plain words

Multiply d by ε squared and divide by 4. Raise e to that power and multiply by root δ. That many random directions all stay within ε of perpendicular, with chance 1 − δ.

With numbers

d = 768, ε = 0.3, δ = 0.01: dε²/4 = 17.28, e17.28 = 3.2 × 107, times 0.1 is 3.2 million directions. At d = 1,536 it is 1014.

The price is superposition: many features share one space. If k features are active at once, reading one picks up k − 1 random cosines, a noise of √((k − 1)/d). At d = 768 that is 0.07 for 5 active features and 0.36 for 100. A vocabulary can be huge if few features fire at once.

The failure. Random pairs average a cosine of 0.6, not 0. That is anisotropy: every vector shares a large common part, so the vectors crowd into a narrow cone and the counts above do not apply. Measure the mean cosine over 10,000 random pairs. Fix: centre (Chapter 7), then remove the top shared directions (Chapter 9).

A colleague says a 768-wide model can cleanly hold at most 768 concepts, because there are only 768 perpendicular directions. What is wrong?

Chapter 4

The Johnson-Lindenstrauss Lemma

Multiply every vector by a random matrix and measure how little the distances move

Your index holds a million vectors of 3,072 float32 numbers: 12.3 GB. You want shorter vectors. How short can they get before the distances change?

In 1984 Johnson and Lindenstrauss showed that a random matrix, one that never saw your data, keeps every pairwise distance close. Build a matrix R with k rows. Fill it with draws of mean 0 and variance 1/k. Map each vector x to Rx. Each output has variance equal to x’s squared length over k, so the k squared outputs add back to that squared length on average.

Call the new width k. For one pair, call the new squared distance divided by the old one, minus 1, its error.

Say it aloud

The typical error equals the square root of two over k.

typical error
typical error the standard deviation, over many pairs, of the error on a squared distance.
√(2/k)
root of two over k 2 is the variance of one squared bell-curve draw; k is the new width.
In plain words

The new squared distance is the old one times an average of k squared bell-curve draws. That average has mean 1 and variance 2/k. Take its square root.

With numbers

k = 128: √(2/128) = 0.125, so 12.5%. k = 768: 5.1%. A seeded run takes 300 points from 1,000 dimensions to k = 768. It measures 5.2%, but the worst of its 44,850 pairs is off by 25%.

Project with a random matrix

Pink bars are new over old squared distance for all 3,160 pairs of 80 points. The band is ±√(2/k). Red marks the worst pair. Change k.

64

Live: 80 Gaussian points in 400 dimensions, projected by a fresh Gaussian matrix in your browser.

That worst pair is why the lemma has a logarithm: it promises every pair. Call the number of points n, and the largest error you allow on any squared distance ε.

Say it aloud

k is at least four log n, over epsilon squared over two minus epsilon cubed over three.

k
k the new width that guarantees every pair.
ln n
log n the natural logarithm of the number of points.
ε²/2 − ε³/3
epsilon squared over two minus epsilon cubed over three from the tail of a sum of squared draws (Dasgupta and Gupta, 2003). ε is between 0 and 1.
In plain words

Take the log of n and multiply by 4. Divide by a term that shrinks like ε squared. The original width does not appear.

With numbers

n = 106, ε = 0.1: 4 × 13.82 = 55.26 and 0.005 − 0.00033 = 0.00467, so k ≥ 11,842: more than the 3,072 you started with. At ε = 0.3, k ≥ 1,536.

So use √(2/k) to choose k, then measure recall. Use the bound only when every pair must hold. Over a million points the worst pair sits about 7.3 standard deviations out.

The failure. A near-duplicate rule (“merge if the squared distance is under 0.1”) wrongly merges pairs after projection. Measure the 99th percentile and the maximum error on 20,000 sampled pairs, not the median. Fix it by checking full vectors before any hard threshold.

You project from 3,072 to 256 numbers and measure a typical error of 9%. A colleague says the lemma is wrong, since a million points at ε = 0.09 need about 14,500 numbers. Who is right?

Chapter 5

Projection in Production

Choose between random projection, PCA and Matryoshka, then cost a two-stage search funnel

Three methods make a vector shorter. They differ in when they look at your data.

methodlooks at datayou storeits strength
Random projectionneverone seeda guarantee on any data; no drift
PCAonce, after traininga matrix of D × k numbersbest fit when few directions dominate
Matryoshkaduring trainingnothing extratruncate to any k with a slice

PCA (principal component analysis) keeps the k directions with the most variance. Take a toy cloud whose eight variances are 4, 2, 1, 0.5, 0.25, 0.125, 0.0625 and 0.0625. Keep three: PCA keeps 7/8 = 87.5% of the variance, while a random projection to 3 has a typical error of √(2/3) = 82%. Make all eight variances equal and PCA keeps only 3/8.

Matryoshka representation learning (Kusupati et al., 2022) trains the encoder so that its first k coordinates are already a good embedding, for several k at once.

Then the two-stage funnel. Stage 1 scores every document with short vectors and keeps a shortlist. Stage 2 rescores the shortlist with full vectors. Projection to width k adds noise of about √(1/k) to a cosine near 0: 0.0625 at k = 256. A true neighbour at 0.5 survives that. The order inside the top ten does not.

Size the funnel

One million documents of 3,072 numbers. Grey is brute force at full width. Pink is the funnel. Both axes are logarithmic.

64
500

Arithmetic only: memory is documents × width × bytes; work counts multiply-adds per query. Full vectors stay on disk and are read only for the shortlist.

The failure. Recall drops to near zero after you add projection. Compare the query path with the write path: the query used another seed or skipped centring. Fix it by storing the seed and the mean with the index version, and applying the same transform in both paths.

The top 50 of your 768 principal directions hold only 12% of the variance, and the corpus grows by a million documents a week. Which reduction do you try first?

Chapter 6

Hubness

Count how often each document lands in other documents’ top lists, and find who wins

Back to ticket three. The k-occurrence of a document is how many other documents have it among their k nearest neighbours. A hub has a large k-occurrence. An orphan has k-occurrence 0: no document’s neighbour list ever reaches it.

Every document hands out exactly k votes. So the votes add up to n times k, and the average k-occurrence is k in every space. Hubness is never about the average. It is about shape: a few winners take votes from many losers.

A toy on paper: A sits at (0, 0), and B, C, D, E sit at distance 3 on the four compass points. Each outer point is 3 from A and 4.24 from its side neighbours, so its nearest neighbour is A. A has a four-way tie; break it toward B. With k = 1 the counts are 4, 1, 0, 0, 0. They add to 5, which is n times k. Their skewness (the mean cubed deviation over the cubed spread) is 1.29, and above about 1 counts as real hubness.

Grow a hub

Left: each of 200 points by its distance from the centre and its k-occurrence. Right: the counts. Yellow marks the top hubs, red the orphans. Raise d.

2
5

Live: Gaussian points, exact nearest neighbours by Euclidean distance.

Why can a plane not grow big hubs? If two points both pick the same nearest neighbour, the angle between them at that neighbour is at least 60°. The most directions that keep 60° apart is the kissing number: 6 in a plane, 12 in 3D, 196,560 in 24 dimensions. In high dimensions there is no ceiling.

Who wins? Split each squared distance around the cloud’s centre into three parts. The first is the query’s distance from the centre. The second is the document’s distance from the centre. The third compares their directions. The middle part ignores the query. Over the corpus it carries variance 2d against 4d for the cross term, so one third of the ranking ignores the query. Documents near the centre win every near-tie.

dskewnessbusiest documentorphanslink to centre
2−0.3317 lists0.1%−0.22
100.8737 lists3.3%−0.88
202.5391 lists7.1%−0.82
1004.25191 lists16.9%−0.73
7687.05354 lists26.4%−0.65

Seeded numpy, 1,000 Gaussian points, k = 10, mean of 3 seeds. The last column is the correlation between k-occurrence and distance from the centre.

The failure. One generic page shows up everywhere and some pages are never found. Measure the orphan fraction and list the ten worst hubs with the code below. Read them first: they are often empty templates, navigation menus or chunks under 30 tokens. Delete or re-chunk them before you try any algorithm.

pythonfrom scipy.stats import skew

def hubness_report(X, k=10):                       # X: (n, d) embeddings
    Xn = X / np.linalg.norm(X, axis=1, keepdims=True)
    S = Xn @ Xn.T                                      # (n, n) cosine
    np.fill_diagonal(S, -np.inf)                      # a point is not its own neighbour
    nbrs = np.argpartition(-S, k, axis=1)[:, :k]      # (n, k)
    Nk = np.bincount(nbrs.ravel(), minlength=len(X))
    assert Nk.sum() == len(X) * k                       # the votes always add to n times k
    return {"skew": float(skew(Nk)), "orphans": float((Nk == 0).mean()),
            "hub_ids": np.argsort(-Nk)[:10].tolist()}    # go and read these documents
Your report shows a mean k-occurrence of 10 and a skewness of 5.2. A teammate wants to “normalize so the average comes down”. What is wrong?

Chapter 7

CSLS and Mutual Proximity

Estimate each document’s head start and subtract it from the score

Chapter 6 found the cause: a part of the score that depends only on the document gives the same documents a head start on every query. The cure is to estimate each head start and subtract it.

First, the free fix: centring. Subtract the corpus mean from every vector and from every query. Take a seeded cloud of 800 vectors in 100 dimensions with a shared part. Random pairs averaged a cosine of 0.39, with skewness 2.79 and 7.9% orphans. After centring: skewness 0.24 and no orphans.

CSLS, cross-domain similarity local scaling (Conneau et al., 2018), asks how similar a point is to things in general. Call r(y) the mean cosine between a point y and its own K nearest neighbours. A hub in the crowded middle has a large r.

Say it aloud

CSLS of x and y equals two cos of x and y, minus r of x, minus r of y.

CSLS(x, y)
C-S-L-S of x and y the corrected score of candidate y for query x.
2 cos(x, y)
two cos of x and y twice the raw cosine between query and candidate.
r(x)
r of x the query’s baseline: its mean cosine to its own K nearest neighbours.
r(y)
r of y the candidate’s baseline, computed the same way; large for a hub.
In plain words

Take the raw cosine twice. Subtract how similar the query is to its own neighbours, and how similar the candidate is to its own. What is left is the similarity that the crowd does not explain.

With numbers

With made-up numbers and r(x) = 0.50: hub A has cosine 0.72 and r = 0.79, so 1.44 − 0.79 − 0.50 = 0.15. Page B has cosine 0.70 and r = 0.60, so 0.30. B moves from second place to first.

Rescore the same cloud

Left: k-occurrence with raw distance. Right: the same 200 points with CSLS. Raise d to make hubs, then compare the tails.

100
10

Live: Gaussian points, k = 10, similarity is minus the Euclidean distance.

In a seeded run (800 points, 100 dimensions, k = 10), the busiest point fell from 164 lists to 50, and orphans from 19.1% to 0.9%. On a cloud without hubs, CSLS raised skewness from 0.29 to 0.48: it adds noise where there is nothing to fix.

Mutual proximity (Schnitzer et al., 2012) asks whether y is close to x by x’s standards and also by y’s. With made-up numbers, a hub whose mean distance is 12.0 sits at 12.5 from the query, and a page whose mean is 14.0 sits at 12.8. Raw distance picks the hub. Mutual proximity gives the hub 0.29 and the page 0.78.

The failure. You add CSLS over the top 10 results and nothing changes. CSLS can only promote what is in the pool, so over-retrieve 10 to 20 times what you return. Recalibrate thresholds too, because CSLS scores are not cosines.

You apply CSLS to the 10 results your index returns, and hubness does not change. What is the most likely cause?

Chapter 8

t-SNE and UMAP Lie

See which properties of an embedding survive the trip to a 2D picture, and which the method never tries to keep

A slide shows your embeddings in 2D: four neat blobs, one large and spread out. The caption says the large category varies most, and the three close blobs are related. The picture cannot support either claim.

No flat map can be faithful. In m dimensions, at most m + 1 points can all sit at the same distance from each other: 3 in a plane, 4 in 3D. A 768-dimensional space holds 769, and millions within a few percent. Twenty evenly spread topics have no honest 2D drawing.

t-SNE (van der Maaten and Hinton, 2008) turns distances into neighbour probabilities and matches them in 2D. It gives each point its own bandwidth, tuned so that every point has the same effective number of neighbours, the perplexity. That step erases density, so blob size carries no information.

It then minimises the KL divergence: a sum over pairs of p times log(p/q). Here p is the true neighbour probability and q is the map’s. The two mistakes cost different amounts:

mistaketrue pmap qcost
neighbours torn apart0.010.0001+0.046
strangers placed close0.00010.01−0.00046

Tearing a neighbourhood costs 100 times more. Fake closeness is almost free. So the loss never scores gaps, positions or sizes.

Tell the same data twice

At 0% you see the true layout: A and B close, C large, D a small satellite of A. Slide toward the 2D story, then try a new seed.

0%

An illustrative cartoon of what neighbour embeddings tend to do: equal blob sizes, equal gaps, a layout that changes with the seed. It does not run t-SNE.

UMAP (McInnes et al., 2018) is faster and in the same family. Kobak and Linderman (2021) showed that most of its better global layout comes from its start; t-SNE started from PCA does about as well.

The failure. A decision rests on a blob’s size or a gap. Measure neighbourhood preservation: the share of each point’s 10 true neighbours that stay among its 10 map neighbours. Print it under the figure. Fix: start from PCA, try three perplexities and three seeds, and test any claim with a classifier in the original space.

pythonfrom sklearn.manifold import TSNE, trustworthiness
from sklearn.neighbors import NearestNeighbors

Y = TSNE(n_components=2, init="pca", perplexity=30, random_state=0).fit_transform(X)

def preservation_at_k(X, Y, k=10):
    a = NearestNeighbors(n_neighbors=k+1).fit(X).kneighbors(return_distance=False)
    b = NearestNeighbors(n_neighbors=k+1).fit(Y).kneighbors(return_distance=False)
    return np.mean([len(set(u[1:]) & set(v[1:])) for u, v in zip(a, b)]) / k

print(preservation_at_k(X, Y), trustworthiness(X, Y, n_neighbors=10))
On a t-SNE plot, cluster A is tight and cluster B covers four times the area. What does that say about their spread in the original space?

Chapter 9

Diagnosing Your Embedding Space

Measure the noise floor, the cone, the effective rank, the intrinsic dimension and the hubs of a real model

A new embedding model arrives. Before you trust one of its scores, measure its space on a sample of 5,000 vectors. Start with the noise floor. Sample 10,000 random pairs. Call the mean of their cosines μ0 and their standard deviation σ0.

Say it aloud

z equals cos of q and y minus mu-nought, over sigma-nought.

z
z how many noise spreads a match stands above random pairs.
cos(q, y)
cos of q and y the raw cosine between query q and document y.
μ0
mu-nought the mean cosine of random pairs in this space.
σ0
sigma-nought the standard deviation of random-pair cosines.
In plain words

Subtract the random-pair mean from the score. Divide by the random-pair spread. The result counts how far the match stands above noise.

With numbers

With made-up models: model X has μ0 = 0, σ0 = 0.036, and a match at 0.31 gives z = 8.6. Model Y has μ0 = 0.62, σ0 = 0.11, and a match at 0.71 gives z = 0.82. For about 1 false alarm in 1,000, cut at z = 3.1: 0.11 on X, 0.96 on Y.

A μ0 far above 0 is anisotropy, a narrow cone. Ethayarajh (2019) found it severe in the top layers of contextual models. The repair (Mu and Viswanath, 2018): subtract the mean, then remove the top few principal directions, about d/100 of them.

Next, how many directions the data uses. Centre the vectors and take the variance along each principal direction, the eigenvalues λ of the covariance.

Say it aloud

P-R equals the sum of lambda, squared, over the sum of lambda squared.

PR
P-R the participation ratio, or effective rank: how many directions the data uses.
Σ λ
the sum of lambda add the variances along all d principal directions: the total variance.
Σ λ²
the sum of lambda squared square each variance first, then add.
In plain words

Add the variances and square the total. Divide by the sum of the squared variances. Equal variances give d; one dominant direction gives 1.

With numbers

Variances 4, 2, 1, 0.5, 0.25, 0.125, 0.0625, 0.0625: 8² / 21.34 = 3.0. A 1/j spectrum at d = 768 gives 7.22² / 1.644 = 31.7. You store 768 numbers to carry about 32 directions.

Read the instrument panel

Decay makes the variances fall off. Cone adds a shared direction to every vector. Watch the spectrum, the noise floor and the orphans, then read the verdict.

0.0
0.00

Live: 220 synthetic vectors in 64 dimensions. The spectrum panel draws the designed variances; the page measures the cosines and hubs on the sample.

Two more checks. The two-NN estimator (Facco et al., 2017) measures intrinsic dimension. For each point, take the log of its second-nearest distance over its nearest. Divide the number of points by the sum of those logs. In a seeded test it read 1.9, 5.1 and 9.7 for true values 2, 5 and 10, but 32 for 50. Read anything above 20 as “at least 20”. Then run the hubness report from Chapter 6.

The failure. Recall is fine offline and poor in production. Check that the index and the scorer use the same metric. For unit vectors, squared distance is 2(1 − cos), so the two rank the same; for raw vectors they disagree. Normalise at write time.

Your panel reads: width 1,024, effective rank 27, two-NN intrinsic dimension 11, μ0 = 0.05, orphans 3%. What is the most useful conclusion?

Chapter 10

Field Guide

Keep the formulas, the numbers, the checklist and the code in one place

High-dimensional space has huge room and tiny contrast. It holds millions of distinguishable directions, and it makes every distance look about the same. Each technique here buys back contrast without giving up room.

effectformulaat d = 768friend or enemy
thin shellinside 0.95R = 0.95d7.8 × 10−18the setting
norm concentrationmean √d, spread 0.7127.7 ± 0.7the setting
distance concentration0.612/√d2.2%enemy: kills contrast
near-orthogonalityspread of cos = 1/√d0.036friend: room
capacity√δ edε²/43.2 million at ε = 0.3friend
superposition noise√((k − 1)/d)0.36 with 100 activethe price of room
projection error√(2/k)5.1% at k = 768friend
JL budget4 ln n / (ε²/2 − ε³/3)1,536 for 106 points at ε = 0.3friend
hubnessone third of ranking ignores the query26% orphans at k = 10enemy

The checklist for a new model or corpus

  1. Measure μ0 and σ0 on 10,000 random pairs. Threshold z-scores, never raw cosines.
  2. If μ0 is well above 0, centre, then remove the top d/100 directions.
  3. Compute the effective rank. If it is small, truncate and measure recall at each k.
  4. Run the hubness report. Read the ten worst hubs and fix the data first.
  5. Apply the same normalisation, mean, seed and metric on the write path and the query path.
  6. Rerank compressed results with full vectors. Put CSLS on an over-retrieved pool.

The core, as code

pythonimport numpy as np
from scipy.stats import skew

def embedding_panel(X, k=10, n_pairs=20000, seed=0):   # X: (n, d), sample about 5,000 rows
    rng = np.random.default_rng(seed)
    n, d = X.shape
    Xn = X / np.linalg.norm(X, axis=1, keepdims=True)
    i, j = rng.integers(0, n, (2, n_pairs))
    c = (Xn[i] * Xn[j]).sum(1)[i != j]                     # random-pair cosines
    lam = np.linalg.svd(X - X.mean(0), compute_uv=False)**2 / n   # eigenvalues
    S = Xn @ Xn.T; np.fill_diagonal(S, -np.inf)
    Nk = np.bincount(np.argpartition(-S, k, 1)[:, :k].ravel(), minlength=n)
    return {"mu0": c.mean(), "sd0": c.std(), "cutoff": c.mean() + 3.1 * c.std(),
            "effective_rank": lam.sum()**2 / (lam**2).sum(), "width": d,
            "hub_skew": skew(Nk), "orphans": (Nk == 0).mean()}

Where it stops being true

Every formula here assumes independent coordinates, the worst case. Real corpora have clusters, curved low-dimensional support and correlated coordinates. That structure is why retrieval works, and why you measure instead of assume. Approximate indexes add their own geometry, so audit them against exact search on a sample.

Keep going

Sources

The habit to keep. Never report a similarity without its baseline. “0.71” is not a measurement; “0.71, where random pairs score 0.62 ± 0.11” is.
Which of these effects is pure damage, with no upside for search?

Now press Present or Teach and explain from memory. Why is the shell thin? Why do random cosines shrink like one over root d? What do √(2/k) and the JL bound each promise? How do hubs form, and how do you remove them? Then go back to the dial and say which chapter explains each panel.

High-Dimensional Geometry
Next: Vector databases · Back to Gleams