Embeddings, explained.
All five chapters, including the worked answers and static lab comparisons. This edition loads no JavaScript.
01
A place in space
An embedding turns an input into coordinates. The useful part is what those coordinates let us compare.
From a sentence to a vector
A help center contains a passage titled “Charging.” A visitor asks, “My device will not turn on.” The wording differs, but the passage might still help. How could a search system compare more than the words they share?
One approach gives each text a numerical representation: an embedding. A vector is an ordered list of numbers. An encoder is the function that produces that vector from an input. Text-retrieval models can encode questions and passages this way. Dense Passage Retrieval is one concrete example.
Let be an input text, its encoder, and its embedding. If the encoder produces coordinates, we write:
Here means “a list of real numbers.” Fixed-length means that this encoder's representation has that coordinate count; it does not mean every input sentence has the same number of words.
Read the list as a place
We will use a small help center throughout. For the battery passage B, invent the vector . These are hand-authored 2D toy coordinates, not values produced by an actual text model.
Hand-authored 2D example. The coordinate list and the point are two views of the same numbers; x₁ and x₂ are not named semantic features.
The first coordinate moves 0.8 units along the first axis; the second moves 0.2 units along the second. You can draw the result as a point or as an arrow from the origin to that point. Both depict the same vector.
The axes are coordinate 1 and coordinate 2—not “battery” and “display.” A dimension is not automatically a named human concept. Indeed, rotating an entire vector space together can change its coordinates without changing its distances or dot products.
A representation is not an ID
A document ID tells us which record to fetch. Its numeric difference from another ID need not tell us anything useful. Embedding coordinates instead participate in a comparison rule: we can ask about their directions, lengths, or distances.
That is the promise, not yet the explanation. Our invented coordinates make geometry easy to inspect. In a learned system, what gives the coordinates a useful arrangement?
02
Learning the map
Training gives a representation a purpose. It does not label every axis with a concept.
Teach a relation, not a dictionary of coordinates
Imagine training examples that pair “My device will not turn on” with a useful charging passage. Other passages compete for the same query. The training task can reward the encoder for assigning the useful pair a higher score.
This is the idea behind the objective in Dense Passage Retrieval: encourage the relevant passage to score above selected negative passages. A negative here is a competing training example, not a negative numerical coordinate.
Schematic learning objective, not a recorded training run. A useful match and a competitor are defined by the training task; the arrows are not literal trajectories every optimizer must follow.
The pull/push picture is schematic. It describes a desired relation, not a measured training trajectory. An objective does not guarantee that every update improves every example, or that the trained model will rank every future query correctly.
Three things called an embedding
“Embedding” can refer to different stages. Keep these three apart:
- Token lookup. A token ID selects a row from an embedding table. With the table fixed, the same ID retrieves the same row. See the embedding-table definition.
- Contextual token states. Further processing lets each token's representation depend on surrounding tokens. In BERT, this uses bidirectional Transformer processing. A word may occupy several tokens.
- One vector for a text. An aggregation step, often called pooling, can combine token states. Sentence-BERT studies pooling together with sentence-level training. Pooling alone is not a guarantee of useful similarity.
Another way to learn: predict nearby words
Skip-gram learns word representations by predicting surrounding words from a target word. This is one historical method, not a universal recipe. Sharing a context is not the same as being a synonym.
Using the map is not redrawing it
After training, we can keep an encoder's parameters fixed and run a new text through it. That is inference: computing a representation with the learned function. Encoding a query need not update the function.
The design implication is important: ask similar for which task? Matching a useful answer, sharing a topic, and expressing the same claim are different goals. Next, we need the numerical rule that turns two vectors into a score.
03
What “near” means
The same points can produce different winners. A similarity rule decides what counts.
Start with the arrow
Let be a query vector and a passage vector. Their coordinates have no physical units here. A vector's norm is its length from the origin:
The dot product multiplies matching coordinates and adds the results. It is sensitive to both direction and magnitude:
Direction, product, or endpoint distance?
Cosine similarity divides the dot product by both lengths. For nonzero vectors, it compares direction; higher is more aligned. Its range is −1 to 1, not a probability or confidence scale. See the metric definitions.
Euclidean distance measures the gap between the arrow endpoints. Lower is nearer:
Our rankings use higher cosine, higher dot product, or lower Euclidean distance. These are different instructions, not interchangeable names for “relevance.”
Keep the documents fixed. Change the question.
This lab uses hand-authored 2D toy vectors. No model reads the passage text or embeds a typed query. The controls directly set the query arrow's angle and length; the five document vectors stay fixed.
Change the query. Watch the ranking.
Hand-authored 2D toy vectors · no text encoder runs here
Make a prediction (optional)
△ Query q○ Passage A–E◉ First-ranked
- 1A · Charging1.000
Connect the charger to restore power.
- 2B · Battery0.970
Improve battery life by reducing background activity.
- 3E · General guide0.800
A general guide to power, display, setup, and care.
- 4D · Repair0.447
A cracked screen can be replaced by the repair team.
- 5C · Display0.000
Adjust the screen brightness in display settings.
q = [1.000, 0.000]. A ranks first at 1.000. Larger score ranks first. Changing only positive query length leaves every cosine score unchanged.
The x₁/x₂ axes are coordinates, not named topics. E’s length is stipulated, not inferred from the length of its text. Cosine is undefined for a zero vector, so query length stays above zero. Scores are rounded to three decimals; ranking uses full precision with a 10−12 tie tolerance. Ties share a rank and use ID order.
Static comparisons and exact coordinates
All scores below are derived from the fixed, hand-authored coordinates. These snapshots remain available without scripts.
| Passage | Coordinates | Cosine ↑ | Dot ↑ | Distance ↓ |
|---|---|---|---|---|
| A | [1, 0] | 1.000 | 1.000 | 0.000 |
| B | [0.8, 0.2] | 0.970 | 0.800 | 0.283 |
| C | [0, 1] | 0.000 | 0.000 | 1.414 |
| D | [0.4, 0.8] | 0.447 | 0.400 | 1.000 |
| E | [2.4, 1.8] | 0.800 | 2.400 | 2.280 |
Cosine selects A; dot product selects E. For q = [0, 1] with cosine, C ranks first at 1.000. The corpus did not move—the query or scoring rule changed.
First change only query length. Positive rescaling leaves cosine unchanged. It multiplies every dot score by the same factor, so dot-product order stays unchanged. Euclidean order can change because the query endpoint moves.
Now reset and switch from cosine to dot product. At , A has cosine 1 and dot product 1. E has cosine 0.8 and dot product 2.4. A wins cosine; E wins dot. Here the difference comes from the candidates' different magnitudes. E's length was stipulated—not inferred from its passage length.
When the rules agree
Normalize a nonzero vector by dividing it by its norm. If every compared vector has unit length, cosine and dot product coincide, and their rankings agree with Euclidean distance:
The condition matters: normalize all compared vectors, not just the query. A metric choice only makes sense alongside the representation it is meant to compare.
04
From query to results
A search system uses vectors to choose candidates. The passage—not its coordinate—is what the reader needs.
Prepare the passages; then receive a query
Return to the help center. We have five passages, each with an ID and source text. A retrieval system can prepare their embeddings ahead of time. When a visitor asks a question, it computes a query embedding and compares it with those prepared vectors.
Let encode a document passage , giving . Let encode the incoming query text , giving . The two paths must produce compatible representations, but need not have identical weights: DPR jointly trains separate query and passage encoders.
Conceptual retrieval flow. Query and document encoders may be the same suitable model or a deliberately compatible pair; matching dimensions alone is not enough.
Equal coordinate counts are not enough. Two maps can each have 100 coordinates while assigning different meanings to their directions. Use a suitable encoder or deliberately compatible pair, together with its intended preprocessing and scoring rule.
Score → rank → inspect
The score produces an ordering of candidate passages. Each result still needs its record ID so that the system can return the original text, title, and source—not merely a list of coordinates.
In our toy example, assign the query . With cosine, passage A comes first, and its record gives us “Connect the charger to restore power.” With raw dot product, E comes first instead. This is the geometry from the previous chapter, not a measured search result for the visitor's wording.
Ranking first does not establish that a passage is correct, current, or sufficient to solve the visitor's problem. A similarity score compares representations; it does not check the passage's claims. DPR likewise separates retrieval from the downstream step of extracting an answer.
Where does retrieval end?
It ends, for our purposes, with an ordered set of source passages. A separate step can inspect them, check their applicability, extract an answer, or decide that none helps. Returning a plausible candidate and establishing a supported answer are different accomplishments.
We now have a complete path: text becomes a vector, a rule compares vectors, and a rank selects candidates to read. What can that path—and its attractive geometry—leave out?
05
What a vector cannot say
A representation is useful because it preserves selected relationships. It is limited for the same reason.
A high score is not a verdict
“The charger is compatible” and “The charger is not compatible” discuss almost the same topic but make opposite claims. We have not measured either sentence's embedding here. The point is about the task: related subject matter is not the same as agreement, and agreement is not the same as truth.
A good retrieval evaluation therefore needs representative questions and judgments about which passages actually help. Geometry can generate candidates; the returned text and its provenance remain essential evidence.
A picture can hide a difference
Our lab is genuinely two-dimensional. To draw a higher-dimensional vector as a point in a 2D plot, we need a mapping to two coordinates. Consider the deliberately simple projection that drops the third coordinate:
Constructed dimension-drop example—not a projection of real embedding data. A picture can hide separation that still exists in the original space.
The original points and are 4 units apart. Both become on the page, so their displayed distance is zero. This counterexample does not condemn every projection. It shows why a 2D picture is not automatically evidence about original-space distances.
Try a fresh pair
Take , , and . Which candidate wins under cosine, dot product, and Euclidean distance? What changes if you normalize every vector first?
Work through the answer
has norm 1 and has norm 5. They point in the same direction, since . Both cosine scores are 0.6: a tie. Their dot products are 0.6 and 3, so dot product prefers V.
Euclidean distance prefers U. After normalization, V becomes U; q and U already have unit length. All three rules then tie the two candidates. None of these numbers tells you whether either passage is true.
Take the map—not the illusion
Keep three questions: What was this representation trained to preserve? Which comparison rule does it expect? Does the retrieved source actually help?
An embedding gives you coordinates for a task. The coordinates make comparison possible; the task, scoring rule, and evidence make the comparison meaningful.
Glossary
- Embedding
- A numerical vector representation of an input; not a guarantee of lossless meaning or factual correctness.
- Encoder
- The function that maps an input, such as text, to its representation.
- Dimension
- The number of coordinates in the vector—not automatically the number of human-readable concepts.
- Norm
- The length of a vector from the origin. This guide uses the Euclidean, or L2, norm.
- Normalization
- Dividing a nonzero vector by its norm to give it unit length.
- Dot product
- The sum of products of matching coordinates. Raw scores retain magnitude effects.
- Cosine similarity
- A comparison of nonzero vectors' directions, ranging from −1 to 1. It is not a probability.
- Euclidean distance
- The straight-line distance between vector endpoints; smaller values rank nearer.
- Pooling
- An aggregation step that combines several representations, such as token states, into one.
- Retrieval
- Selecting candidates from a corpus for further inspection or use.
- Projection
- A mapping to a displayed or lower-dimensional space that may discard distinctions.
Sources
- PyTorch 2.8 — Embedding
Lookup-table weights and input/output shapes. Used to distinguish a token-ID lookup from contextual processing.
- Distributed Representations of Words and Phrases and their Compositionality
Mikolov et al. (2013), §2. One historical context-prediction objective, not a universal embedding recipe.
- BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
Devlin et al. (2019), §3. Input representations and contextual token states.
- Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
Reimers and Gurevych (2019), §§3–4. Pooling, sentence-level training, and task-specific evaluation.
- Dense Passage Retrieval for Open-Domain Question Answering
Karpukhin et al. (2020), §§2–3. Compatible query/passage encoders, candidate scoring, and the retrieval objective.
- Faiss — MetricType and distances
Cosine, inner product, L2, and normalized-ranking equivalence. The lab displays Euclidean distance, not squared L2.