Embeddings and their geometry
How a sentence becomes a point, and what "near" means.

Type “How can I recover access to my account?” into a good help-centre search and the first result is likely to be an article called “Resetting your password”. The two share no words that matter. Keyword search, which looks for the words you typed, has nothing to go on. And yet the match is obviously right.
The demo above does exactly this, over a small set of made-up help-centre sentences. Every score in it is a single number computed between two lists of 768 numbers, one list for the query and one for each sentence. For the pair above, that number is 0.44. For the query and “Our office is closed on Monday”, it is 0.19. For a close paraphrase, “How do I get back into my account?”, it is 0.77.
This post is about where those lists of numbers come from and why comparing them works. It is the first in a short series on text embeddings; in a future post we’ll look at what the numbers give away. No machine-learning background is assumed. The section below gives the background in brief and points to some well-illustrated introductions; if you have met vectors before, the sections after it will be quick, and the part about many dimensions is where the surprises are.
Text as numbers
Computers compare numbers, so any system that works with language has to turn text into numbers somehow. The oldest way is to count words. Give every word in the vocabulary its own position in a very long list, and record which words a document contains. Keyword search works like this, and it is exactly why it fails on our example: in a list like that, “recover” and “resetting” are simply two different positions, no more related than “recover” and “bicycle”.
Embeddings take a different approach. They describe a piece of text with a much shorter list of numbers, chosen so that texts with similar meanings get similar numbers. The idea behind them is older than the computers that could use it. In 1957 the linguist J. R. Firth put it as “You shall know a word by the company it keeps”: words that appear in similar contexts tend to mean similar things.1 Coffee and tea both turn up near “cup”, “hot” and “drink”, so a model that learns to predict a word’s neighbours ends up giving coffee and tea similar numbers.
That is roughly what word2vec did in 2013. Trained to predict which words appear near which across a very large amount of text, it produced a vector for every word, and the vectors had structure nobody had programmed in. The famous example: take the vector for “king”, subtract “man”, add “woman”, and the nearest word is “queen”.2 The real picture is a little less tidy. The standard way of computing these analogies isn’t allowed to answer with any of the words it started from, and without that rule the nearest word is often one of the starting words again.3
Modern models embed whole sentences and passages rather than single words, and learn from far more data, but the principle is the same. Where a piece of text lands is learned from how language is used.
Why this matters now
Embeddings sit underneath much of what is now called AI. The very first thing a large language model does with a prompt is turn each token into a vector, and everything after that is arithmetic on vectors.4 When a chat assistant answers questions about a company’s documents, it usually works by embedding the documents in advance, embedding the question, and handing the closest passages to the language model to read. This is called retrieval-augmented generation, and the vector databases built to serve it have become standard infrastructure. The same kind of vectors power recommendations, duplicate detection, clustering, and the long-term “memory” of AI agents.
So embeddings have quietly become one of the most common ways that text is stored in modern software. They are much less often examined than the text itself, which is the reason for this series.
If you’d like a gentler start
This post concentrates on the geometry and moves quickly past everything else. For a slower, more visual introduction, these are all excellent:
- Jay Alammar, The Illustrated Word2vec. An illustrated walkthrough of how word embeddings are learned, starting from a five-number “personality” vector.
- 3Blue1Brown, Transformers, the tech behind LLMs. An animated lesson; its section on word embeddings shows how directions in the space can carry meaning.
- Simon Willison, Embeddings: What they are and why they matter. Practical and written for engineers: related content, semantic search and clustering, with code.
- Vicki Boykis, What are embeddings?. A free, book-length deep dive covering the history, the engineering and recommender systems.
The Python cells are live. Press Run to try one, or Edit to change it. They share one session, like a notebook, so run them in order. Python downloads the first time you press Run, and nothing you type leaves your browser.
From text to a vector
An embedding model takes a piece of text and returns a fixed-length list of numbers, called its embedding or vector. The model behind the demo is GTR-base, an openly available model built for search.5 Everything it produces has 768 numbers, whether the input is one word or a paragraph.
It gets there in three steps.
First, the text is split into tokens: whole words, or pieces of words for anything less common. GTR splits our query like this, with ▁ marking the start of a word:
▁How ▁can ▁I ▁recover ▁access ▁to ▁my ▁account ?
and turns “Unlocking your account after too many sign-in attempts” into ▁Un lock ing ▁your ▁account ▁after ▁too ▁many ▁sign - in ▁attempts. Splitting rare words into familiar pieces means the model never meets a word it can’t represent.
Second, the model reads all the tokens together and produces one vector of 768 numbers for each of them. Each token’s vector depends on the tokens around it, so “account” in “bank account” and “account” in “an account of the war” come out differently. How the model does this is a large topic of its own, and not one we need here.
Third, those per-token vectors are combined into one, here simply by averaging them coordinate by coordinate. This step is called pooling.6
In symbols: a sentence
goes in, the model runs, and a vector comes out,The notation is worth keeping in mind for one reason. A vector only means something relative to the model
that made it. Two different models give the same sentence completely different numbers, and comparing their coordinates directly tells you nothing: for models with different architectures, the cosine between their vectors for the same text is close to zero, no better than chance.7The shapes of the two spaces are another matter. A 2025 study called vec2vec found that quite different models arrange texts in such similar ways that one model’s space can be translated into another’s without a single matched example to learn from, only a large collection of vectors from each. Translated vectors reached cosine similarities as high as 0.92 with the true vectors in the other model’s space.7 The authors read this as evidence that models learn a largely shared geometry of meaning. It also has a privacy side, which we’ll return to in future posts: keeping secret which model produced a set of vectors is not, on its own, much protection.
Dot products, lengths and angles
To compare two vectors we need a way to say how much they point the same way. Start in three dimensions, where you can picture it.
The dot product of two vectors multiplies them coordinate by coordinate and adds up the results:
For
and , that is .The length of a vector, also called its norm, comes from the dot product of a vector with itself, by Pythagoras:
. Here and .The dot product mixes up two things: how long the vectors are and which way they point. Dividing out the lengths leaves only the direction. What remains is the cosine of the angle
between them:This is cosine similarity, the score in the demo.8 It is 1 when two vectors point the same way, 0 when they are perpendicular, and −1 when they point in opposite directions. For our pair it is
, an angle of about 39°.import math
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def norm(a):
return math.sqrt(dot(a, a))
def cosine(a, b):
return dot(a, b) / (norm(a) * norm(b))
a = [2, 1, 0]
print(round(cosine(a, [4, 2, 0]), 4)) # same direction, twice as long
print(round(cosine(a, [1, -2, 0]), 4)) # perpendicular
print(round(cosine(a, [1, 1, 1]), 4)) # the example aboveThe first line matters most for search. Doubling a vector’s length changes its dot products but not its cosine. Models like GTR are trained so that only direction carries meaning, and their vectors are scaled to length 1 before they’re compared.
Length 1, and why the choices agree
Most search models work this way, though not all: some are trained with a raw dot product, and for those the length means something.9 For the rest, systems scale every vector to length 1 before storing it. This is called normalising. Once both vectors have length 1, the denominator in the cosine formula is 1, and cosine similarity is just the dot product.
It also settles a question that vector databases leave you to answer: should search use cosine similarity, the dot product, or ordinary straight-line (Euclidean) distance? For vectors of length 1, expand the squared distance:
The distance goes down exactly when the dot product goes up. All three choices put the results in the same order.
import random
def unit(v):
n = norm(v)
return [x / n for x in v]
a = unit([random.gauss(0, 1) for _ in range(768)])
b = unit([random.gauss(0, 1) for _ in range(768)])
distance_squared = sum((x - y) ** 2 for x, y in zip(a, b))
print(round(distance_squared, 6))
print(round(2 - 2 * dot(a, b), 6))Run it a few times. The two numbers always agree, for any pair of vectors of length 1.
How the space gets its shape
Nothing so far explains why “recover access to my account” should point in nearly the same direction as “resetting your password”. The arithmetic would work on any list of numbers. The meaning comes from how the model was trained.
Search models like GTR learn from pairs of texts that are known to belong together: a question and the passage that answers it, a search query and a passage someone judged relevant. GTR’s authors trained it first on about two billion question–answer pairs collected from forums and question-and-answer sites such as Reddit and Stack Overflow, then on a much smaller set of search queries paired with relevant passages, annotated by people.5
Training takes a batch of pairs at a time. For each question, the model is rewarded when its vector points towards its own answer and away from every other answer in the batch. A common way to write that down, for the
-th question and its answer , iswhich is small when the right answer has a much higher dot product than all the wrong ones. The temperature
controls how sharply the model is pushed; GTR used 0.01, with 2,048 pairs per batch. Repeat this over billions of pairs and related texts end up pointing in similar directions. This style of training is called contrastive.Three consequences follow, and they all matter later.
“Related” means whatever the training pairs made it mean. A model trained on questions and answers learns that a question is near its answer. A model trained on paraphrases learns something slightly different. That is why the same pair of sentences gets different scores from different models, and why a score from one model can’t be compared with a score from another.
The scores are relative. With GTR, even unrelated sentences score a little above zero: the query and “Our office is closed on Monday” get 0.19, and in the demo most unrelated sentences land between 0.05 and 0.3. What matters is how the right answer compares with everything else, not whether it crosses some fixed line.
The coordinates have no labels. Nobody chose what the 412th number means, and in general it doesn’t mean any one thing. There is no “health” coordinate or “billing” coordinate you can read off. Meaning is spread across many coordinates at once. That said, researchers do find directions in these spaces that line up with particular concepts, found by training a small model to look for them. This is where geometry turns into a privacy question. If a simple model can find a direction for “health” in a space nobody labelled, it may also be able to read a sensitive fact straight out of a stored vector, without ever recovering the sentence it came from. Privacy researchers call this attribute inference, and it is one of the threads we’ll follow in future posts.
Geometry in many dimensions
Everything above was drawn in two or three dimensions. GTR works in 768, and high-dimensional space behaves in ways that intuition from the physical world gets wrong. Two facts matter for embeddings.
Random directions are nearly perpendicular
Pick two directions at random in two dimensions, and the angle between them could be anything. Pick two directions at random in 768 dimensions, and they are almost always very close to perpendicular. The cosine between two random directions in
dimensions averages 0 with a spread of exactly , which for is about 0.036.def random_unit(d):
return unit([random.gauss(0, 1) for _ in range(d)])
for d in [2, 10, 100, 768]:
cosines = [dot(random_unit(d), random_unit(d)) for _ in range(1000)]
mean = sum(cosines) / len(cosines)
spread = math.sqrt(sum((c - mean) ** 2 for c in cosines) / len(cosines))
biggest = max(abs(c) for c in cosines)
print(f"d = {d:>3} spread {spread:.3f} 1/sqrt(d) {1 / math.sqrt(d):.3f} largest seen {biggest:.2f}")In two dimensions, random pairs land all over the place. In 768, a thousand random pairs rarely get past about 0.15 in either direction. There is so much room that almost nothing points the same way by accident.
This puts the demo’s numbers in perspective. A cosine of 0.44 sounds modest. Measured against chance, it is enormous: more than ten times the spread you would see from random directions. Real embeddings don’t spread out evenly the way random vectors do, which is why unrelated sentences still score 0.1 or 0.2 with GTR, but the point stands. In this space, pointing even roughly the same way is meaningful.
Small noise barely changes direction
The second fact is a consequence of the first. Suppose you add a little random noise to every coordinate of a vector of length 1. In three dimensions, a small nudge stays small. In 768 dimensions, small nudges to every coordinate add up: noise of 0.01 per coordinate moves the vector a distance of about
, more than a quarter of its own length.And yet the direction barely changes. The noise is random, so it points in a random direction, and by the first fact a random direction is almost perpendicular to the vector. Moving sideways tilts a vector much less than moving it forwards or backwards would.
v = random_unit(768)
for size in [0.01, 0.03, 0.1]:
noisy = [x + random.gauss(0, size) for x in v]
moved = norm([x - y for x, y in zip(v, noisy)])
print(f"noise {size}: moved {moved:.2f}, cosine with the original {cosine(v, noisy):.2f}")The same holds for real search. I took the demo’s sentence vectors, added random noise to each, and reran all ten queries, two hundred times at each noise level:
| Noise per coordinate | Cosine with the original, on average | Queries with the same top result |
|---|---|---|
| 0.01 | 0.96 | 98% |
| 0.02 | 0.88 | 94% |
| 0.05 | 0.59 | 81% |
| 0.10 | 0.34 | 63% |
At 0.05, a stored vector has drifted far from where it started, and four out of five searches still return the same answer. Search is remarkably tolerant of noise.
That tolerance is usually treated as good news, and for search it is. Adding noise is one of the most common ways people try to make stored embeddings safer, and its appeal is exactly this table: search keeps working. Whether the noise also stops someone from learning what the vectors say is a separate question, and one we’ll come back to in a future post.
How much a vector can hold
An embedding is always the same size, whatever went in. A three-word query and a fifty-page report both become 768 numbers, so for long texts the vector is a heavy squeeze: most of the wording has to be thrown away, and many different texts end up pointing almost the same way.
Short texts are a different matter. A support message of a sentence or two holds very little information, and 768 numbers have room for quite a lot, even after allowing for the fact that most of their precision is noise. The vector isn’t too small to hold such a sentence.
That is not evidence that the sentence can be read back out. The model was never trained to preserve wording; it was trained to make related texts point the same way. Room to hold information is an upper bound, not a measurement.
But it does make the question a fair one. If the vector for “I started chemotherapy in March” is good enough that a search for “customers struggling to pay because of illness” finds it, how much of the original survives inside those 768 numbers? We’ll explore that in a future post.
Finding neighbours quickly
One last practical piece. To search, you compare the query vector with every stored vector and keep the closest. With the demo’s 28 sentences, that is 28 dot products of 768 numbers each, which takes a browser well under a millisecond.
With a hundred million stored passages, comparing against every one becomes too slow. Vector databases therefore use approximate nearest-neighbour indexes. One widely used design, HNSW, links each vector to a few of its neighbours in a layered graph and walks the graph towards the query, visiting only a small fraction of the stored vectors.10 The answer is occasionally not the true nearest neighbour, in exchange for being much faster.
Whatever the index, a vector database rarely stores the vector alone. Alongside each one it keeps an ID, the document it came from, its position within that document, and often the original text. That surrounding information turns out to matter as much as the vectors, and we’ll see why in a future post.
Back to the query
“How can I recover access to my account?” becomes ten tokens, then ten vectors of 768 numbers, then one vector by averaging. “Resetting your password” goes through the same steps. The two final vectors point in directions 0.44 apart in cosine terms, far more alike than chance would allow, because GTR was trained on enough questions and answers to put them there.
That is the whole mechanism: text to tokens, tokens to a vector, vectors to directions, directions to a similarity score. It is useful precisely because the vector keeps a great deal of what the text was about.
Footnotes
-
J. R. Firth, “A Synopsis of Linguistic Theory, 1930–1955”, in Studies in Linguistic Analysis, Blackwell, 1957. ↩
-
Tomas Mikolov, Kai Chen, Greg Corrado and Jeffrey Dean, Efficient Estimation of Word Representations in Vector Space, 2013. ↩
-
Malvina Nissim, Rik van Noord and Rob van der Goot, Fair Is Better than Sensational: Man Is to Doctor as Woman Is to Doctor, Computational Linguistics, 2020. ↩
-
Grant Sanderson (3Blue1Brown), Transformers, the tech behind LLMs, Deep Learning chapter 5. ↩
-
Jianmo Ni, Chen Qu, Jing Lu, Zhuyun Dai, Gustavo Hernández Ábrego, Ji Ma, Vincent Zhao, Yi Luan, Keith Hall, Ming-Wei Chang and Yinfei Yang, Large Dual Encoders Are Generalizable Retrievers, EMNLP 2022. The demo uses the openly available
sentence-transformers/gtr-t5-baseweights. ↩ ↩2 -
The released GTR model adds one more learned layer after averaging, then scales the result to length 1. The demo stops at the average, the way the Vec2Text inversion study does, which keeps these vectors directly comparable with that research. ↩
-
Rishi Jha, Collin Zhang, Vitaly Shmatikov and John X. Morris, Harnessing the Universal Geometry of Embeddings, NeurIPS 2025. Comparing raw vectors across models with different architectures gave cosines between −0.03 and 0.04; models fine-tuned from the same base model were partly compatible even without translation. Translation quality varied by model pair, and training was not always stable. ↩ ↩2
-
Nils Reimers and Iryna Gurevych, Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks, EMNLP-IJCNLP 2019, popularised comparing sentence embeddings with cosine similarity. ↩
-
Vladimir Karpukhin, Barlas Oğuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen and Wen-tau Yih, Dense Passage Retrieval for Open-Domain Question Answering, EMNLP 2020. DPR scores passages with an unnormalised dot product, so a passage vector’s length affects how highly it ranks. Normalising its vectors, or switching to cosine, changes the results. ↩
-
Yu. A. Malkov and D. A. Yashunin, Efficient and Robust Approximate Nearest Neighbor Search Using Hierarchical Navigable Small World Graphs, IEEE Transactions on Pattern Analysis and Machine Intelligence, 2020. ↩
Responses
No responses yet. You could be the first.
Comments couldn’t be loaded right now.