Embeddings: Search by Meaning
To answer a question from your own documents, a program first has to find the passages that bear on it. Searching for the question's words is the obvious way, and it often fails, because people ask with different words than the author wrote. Embeddings turn each text into a list of numbers that captures what it means, so a program can measure how close two texts are in meaning and pick the passages nearest to a question, even when they share no word with it.
When the words do not match
Imagine a staff handbook split into short passages, and someone asks: "How do I get my money back for a train ticket?" The passage that answers it says: "Travel expenses are reimbursed when you submit the claim form with your receipt."
Put the two side by side and look for a common word. There is none. The person said money back, the author wrote reimbursed; the person said train ticket, the author wrote travel expenses. A search that counts the question's words in each passage gives the right passage a score of zero.
Worse, a passage that happens to reuse the question's words can win while being about something else:
| Passage | Words shared with the question | Answers it? |
|---|---|---|
| Train new staff before they get access to the ticket system. | train, get, ticket | no |
| Travel expenses are reimbursed when you submit the claim form with your receipt. | none | yes |
This is called vocabulary mismatch: a question and the passage that answers it often describe the same thing in different words. A search that matches words is called lexical search or keyword search, and a synonym, an abbreviation, a different phrasing or a misspelling is enough to hide a passage from it. To find the reimbursement passage, a search has to compare what the texts mean, not which letters they contain.
True or false?
A passage that contains more of the question's words is more likely to answer it.
False. Shared words show the texts mention the same terms, not that they are about the same thing. The decoy above shares three words and answers nothing; the right passage shares none.
An embedding: a text as a point
An embedding is a list of numbers that stands for a text. Every text gets a list of the same length, whether it is three words or a whole paragraph, and the numbers are chosen so that texts with similar meaning get similar lists.
A list of numbers can be read as a position. Two numbers place a point on a flat map; three place it in a room. Real embeddings have hundreds of numbers, so the space they place texts in has hundreds of directions, which nobody can draw. The idea survives in two dimensions, though: texts about the same thing land near each other, and texts about different things land far apart.
dimension 2 against dimension 1
- texts
In this sketch the question sits beside the reimbursement passage and the passage about hotel receipts, because all three are about getting costs paid back. The decoy that shares the words train, get and ticket sits elsewhere: it is about training people, and its position says so. That is what makes embeddings useful for search: the distance between two points tells you how close the texts are in meaning, and the words they happen to use do not decide it.
The individual numbers have no meaning a person can name. There is no "money" dimension. What carries information is where a text sits relative to other texts placed by the same model.
The model that produces embeddings
An embedding model is a neural network trained to produce these lists of numbers. During training it saw a very large number of pairs of texts known to mean similar things, such as a question and its answer, and it was adjusted until such pairs came out close together and unrelated texts came out far apart. That training is where its sense of meaning comes from, which is why reimbursed and money back end up near each other although they share no letters.
- Text any length
- Tokens word pieces, up to a limit
- Trained network
- Vector always the same length
- Text to Tokens
- Tokens to Trained network
- Trained network to Vector
Two numbers describe every embedding model, and both are fixed when the model is trained:
- The output dimension: how many numbers each embedding has. Every text the model encodes gets exactly this many. Embeddings from two different models cannot be compared with each other, whether their dimensions differ or the models were simply trained differently.
- The maximum input length: how much text the model reads. It is counted in tokens, the word pieces the model splits text into (a common word is one token, a rare word may be several), not in words or characters. Anything past the limit is cut off and never reaches the model.
- Travel
- expenses
- are
- reimbursed
- when
- you
- submit
- the
- claim
- form
- with
- your
- receipt
Real limits are larger, typically a few hundred tokens. The documentation of Sentence Transformers, a Python library for embedding models, gives 512 tokens, about 300 to 400 English words, as a common value for one widely used family of models, and some small models stop at 256.
The consequence is the same at any size: a passage longer than the limit is embedded from its beginning only, so a fact near its end cannot be found through its embedding. This is one reason to keep passages short. Many models were also trained on short texts, so even within the limit they represent a sentence or a short paragraph better than a long page.
Small embedding models run comfortably on an ordinary processor, with no graphics card and no account. In Python, the Sentence Transformers library downloads an open model on first use and encodes texts with it. One of the small models used in the library's own examples produces 384 numbers per text and reads up to 256 tokens:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
print(model.get_embedding_dimension()) # 384
print(model.max_seq_length) # 256
vectors = model.encode([
"The weather is lovely today.",
"It's so sunny outside!",
"He drove to the stadium.",
])
print(vectors.shape) # (3, 384)encode takes a list of texts and returns one row of numbers per text, so three sentences give an array of shape (3, 384). The model runs on the computer itself, so the same text always gives the same embedding.
True or false?
If a passage is longer than the model's maximum input length, its embedding still reflects the whole passage, only less precisely.
False. The text past the limit is cut off before the model sees it. The embedding describes the first part only, and the rest cannot be found through it.
A small embedding model can turn text into vectors on an ordinary laptop processor.
True. Small models need no graphics card. When none is available, the library uses the processor.
Measuring closeness with the angle
To rank passages, a program needs one number that says how close two embeddings are. The usual choice is cosine similarity. Picture each embedding as an arrow from the origin, the point where every number is zero, to the embedding's own point. Cosine similarity looks only at the angle between two arrows: the smaller the angle, the more the two texts point in the same direction of meaning.
- reimbursement passage
- question
- printer passage
- small angle: high similarity
- wide angle: low similarity
The cosine of an angle turns it into a score. Written out for two vectors \(A\) and \(B\), it is their dot product (multiply the numbers at the same position and add the results) divided by the product of their lengths:
Cosine similarity
| Cosine similarity | Angle | What it says |
|---|---|---|
| 1 | 0 degrees | the arrows point the same way |
| 0 | 90 degrees | the directions have nothing in common |
| -1 | 180 degrees | the arrows point in opposite directions |
Scores run from -1 to 1. With text embeddings, unrelated texts usually land a little above zero rather than at it, and what counts as a high score depends on the model. In the library's own example, "The weather is lovely today." and "It's so sunny outside!" score 0.6660 against each other. Against "He drove to the stadium." they score only 0.1046 and 0.1411. The numbers are best read as a ranking: higher means closer in meaning.
Dividing by the lengths is what makes the score depend on direction alone. A vector's length is not part of a text's meaning, and the division removes it. That gives a useful shortcut. If every vector is first normalised, scaled so that its length is exactly 1, the denominator becomes \(1 \times 1\) and cosine similarity is just the dot product:
For vectors of length 1
A dot product is cheaper than a full cosine, and with normalised vectors it gives exactly the same scores and the same ranking. Some embedding models normalise their output already; with Sentence Transformers, model.encode(texts, normalize_embeddings=True) guarantees it, since the option is off by default. Without normalisation the two measures differ, because a dot product also grows with the length of the vectors.
True or false?
Cosine similarity always lies between 0 and 1.
False. It lies between -1 and 1. Only vectors with no negative numbers stay above 0, and embedding numbers can be negative.
For two vectors of length 1, the dot product and the cosine similarity are the same number.
True. The cosine divides the dot product by the product of the lengths. When both lengths are 1, that divides by 1.
Doubling every number in an embedding makes it more similar to the question under cosine similarity.
False. Doubling the numbers makes the arrow longer without turning it. The angle stays the same, so the cosine stays the same.
Ranking every passage against the question
With embeddings and a similarity score, search by meaning, called semantic search, takes three steps:
- Embed every passage once, ahead of time.
- When a question arrives, embed it with the same model.
- Score the question against every passage and keep the k passages with the highest scores, where k is a small number you choose, such as 3 or 5. This is called top-k search.
The scores below are made up to show the shape of a typical result: a few passages clearly ahead, then a long tail of unrelated ones.
- Travel expenses reimbursed 0.62
- Hotel costs need a receipt 0.48
- Mileage for own car 0.41
- Train new staff 0.22
- Guest Wi-Fi password 0.08
- Printer needs toner 0.05
With k = 3, the three highlighted passages are returned and the rest are dropped. The reimbursement passage comes first although it shares no word with the question: its embedding points in nearly the same direction, because the model learned that money back and reimbursed, train ticket and travel expenses, are used for the same things. The decoy that shares three words ranks low, because its meaning points elsewhere.
In Python, the whole search fits in a few lines. model.similarity computes cosine similarity between the question and every passage, and torch.topk keeps the k best:
import torch
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
passages = [
"Travel expenses are reimbursed when you submit the claim form with your receipt.",
"Train new staff before they get access to the ticket system.",
"The printer on the second floor needs new toner.",
]
passage_vectors = model.encode(passages)
question = "How do I get my money back for a train ticket?"
question_vector = model.encode(question)
scores = model.similarity(question_vector, passage_vectors)[0]
best = torch.topk(scores, k=2)
for score, index in zip(best.values, best.indices):
print(f"{score:.3f} {passages[index]}")Passages are embedded once and reused for every question; only the question is embedded each time. Because the question is scored against every passage, nothing is skipped: the k passages returned are the true best ones under this score.
The question must go through the same model as the passages. Each model places texts in its own space, and a vector from one model next to a vector from another is like comparing map coordinates from two different maps: the numbers can be computed, but they mean nothing. Even when two models have the same output dimension, their scores against each other are noise.
A top-k search also always returns k passages. It ranks what exists; it never says that nothing fits. If the documents hold no answer, the k best passages are simply the least unrelated ones.
True or false?
Passages can be embedded with one model and questions with another, as long as both produce vectors of the same length.
False. Each model has its own space. Equal lengths make the arithmetic possible, but the scores no longer measure meaning.
A top-k search returns k passages even when none of them answers the question.
True. It keeps the k highest scores, however low they are. Getting results is no evidence that an answer exists.
Semantic search can find a passage that shares no word with the question.
True. It compares the directions of the embeddings, which the model learned from meaning, so different words for the same idea still score high.