Sub topic 2
What an embedding is: text as a point in vector space
This chapter explains what a text embedding is and why distance between embeddings tracks similarity in meaning. It assumes you know basic Python, can read NumPy code, and know what a vector, a dot product, and a vector length are. It also assumes you have a general idea of what a neural network does and how keyword search works. You don't need to know how embedding models are trained yet. A later chapter covers that.
The core idea
An embedding is a list of numbers, a vector, that represents a piece of text. The text can be a word, a sentence, a paragraph, or a whole page. An embedding model produces the vector. Every input, whatever its length, produces a vector with the same fixed number of entries. That number is the model's dimensionality.
You can read a vector with d entries as the coordinates of a point in a d-dimensional space. In two dimensions, a vector like [0.3, 0.8] is a point on a plane. In 384 dimensions, you can't picture the point, but the arithmetic works the same way. The model places texts so that texts with similar meaning land near each other and unrelated texts land far apart.
This turns a language problem into a geometry problem. "Find documents that mean something similar to this query" becomes "find the points closest to this point". Computers do the second task quickly.
In the diagram, the first two texts share almost no words, but their points end up close together. The third text ends up far from both. Keyword search can't produce that result, because it looks at which words appear and not at what the text means.
A toy example with hand-made vectors
Real embeddings are learned, and you can't design them by hand. A small hand-made example still shows how distance acts as a stand-in for meaning. Here each vector has three entries, which we label as animal-ness, vehicle-ness, and food-ness. A real model has no labeled axes like these. The example only shows the geometry.
import numpy as np
# Hand-made 3-d vectors. Axes: (animal-ness, vehicle-ness, food-ness).
vectors = {
"cat": np.array([0.90, 0.00, 0.10]),
"kitten": np.array([0.85, 0.00, 0.10]),
"truck": np.array([0.00, 0.95, 0.00]),
"pizza": np.array([0.00, 0.00, 0.90]),
}
def distance(a, b):
return float(np.linalg.norm(a - b))
for word in ["kitten", "truck", "pizza"]:
d = distance(vectors["cat"], vectors[word])
print(f"cat -> {word}: {d:.3f}")Running it prints:
cat -> kitten: 0.050
cat -> truck: 1.312
cat -> pizza: 1.204"kitten" sits almost on top of "cat". "truck" and "pizza" are both far away. A learned model does the same thing in hundreds of dimensions, and it assigns the coordinates automatically from training data.
What the numbers mean (and what they don't)
Beginners often try to interpret individual entries of an embedding. Don't. In a trained model, dimension 17 does not mean "is about animals". The meaning is spread across all dimensions together. A direction in the space can correspond to a concept, such as the difference between formal and casual text. But no single coordinate does, and you can't read a concept off the vector.
Several consequences follow:
- Only relationships between vectors carry information. A single vector, looked at alone, tells you almost nothing.
- Vectors from different models can't be compared. Each model builds its own space. A 384-number vector from one model and a 384-number vector from another use unrelated coordinate systems, even when the sizes match.
- Queries and documents must come from the same model. If you embed documents with model A and a query with model B, the distances are meaningless.
Dense versus sparse vectors
Keyword search also turns text into vectors, and the contrast helps. A bag-of-words or TF-IDF vector has one entry per vocabulary word, so it may have 50,000 or more entries. Nearly all of them are zero. This is a sparse vector. Two texts are close only if they share words.
An embedding is a dense vector. It is much shorter, typically 384 to 3072 entries, and almost every entry is nonzero. Because the entries encode learned features and not individual words, texts with no words in common can still be close. That is the main advantage over keyword matching.
| Property | Sparse (keyword) vector | Dense (embedding) vector |
|---|---|---|
| Typical length | Vocabulary size, tens of thousands or more | 384 to 3072 |
| Nonzero entries | Very few | Nearly all |
| What an entry means | One specific word | Nothing on its own |
| Matches synonyms | No | Often yes |
| Matches exact rare terms | Yes | Sometimes poorly |
The last row matters. Dense vectors are not strictly better. A product code like XJ-4471 or an unusual name can be matched exactly by keywords, while an embedding may blur it with similar-looking strings. A later chapter covers combining both approaches in hybrid search.
Size, memory, and storage
Embeddings are usually stored as 32-bit floats, so each entry costs 4 bytes. A 384-dimensional vector takes 384 × 4 = 1,536 bytes. A collection of one million such vectors takes about 1.5 GB, before any index overhead. A 1536-dimensional model quadruples that to about 6 GB for the same million texts.
The dimension is therefore a practical choice and not only a quality setting. Higher dimensions can hold more information, but they cost more memory and make each comparison slower. Chapter material on approximate indexes and vector stores returns to this cost.
What an embedding captures and what it loses
An embedding is a lossy summary. The model compresses a text into a fixed number of values that are useful for judging similarity. Several kinds of information survive poorly:
- Exact wording. Two paraphrases get nearby vectors, so you can't recover the original sentence from the vector.
- Negation and fine logic. "The drug is safe" and "The drug is not safe" use nearly the same words and topic, so their vectors are often close. Embeddings capture topic well and logical polarity less well.
- Rare identifiers. Codes, serial numbers, and uncommon names carry little learned meaning.
- Text beyond the model's input limit. Each model reads only a maximum number of tokens. Most models silently truncate longer input, so the tail of the text has no effect on the vector.
Context also matters. The word "bank" in "river bank" and in "bank account" gets different representations when it is part of a sentence, because the model reads the whole input. This differs from older word-vector methods, which gave each word one fixed vector regardless of context.
Seeing the shape of the space
For intuition, you can view a space as groups of points. Texts about the same topic form a loose cluster. Related topics sit nearer to each other than unrelated ones. A query is embedded into the same space, and its nearest points are the best candidate answers.
Two points about this picture are worth keeping in mind:
- Closeness is relative. There is no universal distance that means "similar". You compare distances for one query against each other, and you rank the results. A raw score that looks high with one model may be ordinary with another.
- High dimensions behave differently from 2-D or 3-D intuition. In hundreds of dimensions, most random points are roughly equally far from each other. Learned embeddings avoid this by pulling related texts together, but it is why a dimension-reduced 2-D plot of embeddings is only a rough picture and can mislead you about real distances.
Common mistakes at this stage
- Treating a single dimension as a feature with a name.
- Comparing vectors from two different models, or from two versions of the same model.
- Assuming that a short distance proves the texts agree. It shows only that they are about similar things.
- Forgetting that the input length limit truncates text silently.
- Planning storage from the number of documents without multiplying by dimensions and bytes per entry.
The next chapter defines the three standard ways to measure closeness (cosine similarity, dot product, and Euclidean distance) and shows how to choose among them.
Exercise
A team embeds 2 million product descriptions with a model that outputs 768-dimensional float32 vectors. (a) How much memory do the raw vectors need? (b) A colleague proposes embedding the documents with model A but embedding user queries with model B because B is faster. Why is this a problem even if both models output 768 dimensions?
Show answer
(a) Each vector takes 768 × 4 = 3,072 bytes. For 2,000,000 vectors that is 6,144,000,000 bytes, about 6.1 GB, before any index overhead. (b) Each model builds its own vector space, so coordinates from model B have no relationship to coordinates from model A. Matching dimension counts only means the arrays have the same shape. Distances between a B query vector and A document vectors are meaningless, so search results would be essentially random. Queries and documents must be embedded with the same model.
Exercise
In the toy example, add a vector "dog" = [0.88, 0.00, 0.05] and compute its Euclidean distance to "cat". Is it closer to "cat" than "truck" is? Explain what this tells you about how embeddings represent meaning.
Show answer
The difference is [-0.02, 0.00, 0.05], so the distance is sqrt(0.0004 + 0.0025) = sqrt(0.0029), about 0.054. That is far smaller than the cat-to-truck distance of 1.312, so "dog" is much closer to "cat". Related meanings sit near each other in the space, and unrelated meanings sit far apart. Meaning is represented by position relative to other points, not by any single coordinate.