Skip to content

Embeddings: semantic distance, dimensions and what proximity cannot prove

13 min reading

Explain a similarity score without treating it as proof that a passage answers the question.

Page details

GenAI · Lesson 3 of 45 · 1 / 1.1

Sources · 13 min reading · 26 min with practice

Published · Last edited:

More
20px

Progress is saved in this browser when storage is available.

View guided paths and progress

Know first: Tokenization: BPE, WordPiece and SentencePiece; trace a text-to-token example. Optional help: GenAI foundations.

Optional background references

Hypothetical scenario. After checking the complete request budget, Dev needs to choose which permitted passages deserve space in it. An employee asks about borrowing equipment over a weekend. One passage uses those exact words but concerns a different eligibility rule; another describes Friday collection and Monday return.

Maya: “The second passage sounds useful even though it uses different words.”

Dev: “An embedding score could help us find it.”

Priya: “Then show what that score means before treating the nearest passage as the answer.”

Token IDs identify input units; an embedding and scoring rule can supply another matching signal. You will work through vector comparisons and normalization, then test the boundary between similarity and evidence that actually answers the question. A shortlist still needs relevance, freshness and access checks.

Which passage answers the question rather than resembling it?

Hypothetical scenario. A library reader asks how to borrow equipment “over the weekend,” while a handbook section describes “Friday collection and Monday return.” An exact phrase search may miss that section. A learned text representation offers another matching signal, but a high score still cannot establish whether the section is current, applies to the device, or supports the complete answer.

An embedding represents an input as a vector: an ordered list of numbers. In retrieval, an encoder produces vectors that a scoring rule can compare. The useful property is not that text has become numbers; it is that the representation and score help rank evidence for the intended information need.

This chapter builds on vectors and dot products. You will calculate how normalization changes a ranking, distinguish similarity from answer confidence, and reason about a representation upgrade without silently mixing incompatible coordinates.

A map needs a purpose

The phrase “similar meaning” hides several possible tasks. Two passages can discuss the same topic while giving opposite instructions. A question and its answer may be useful matches without being paraphrases. A device identifier can be decisive even when most surrounding words are unrelated. The representation's training objective and evaluation determine which relationships it is useful for.

A convenient picture places each concept in a neat cluster. Real retrieval has overlapping topics, ambiguous language, and task-specific distinctions. Two dimensions in a teaching diagram do not reveal the actual meaning of individual coordinates in a learned representation.

Sentence-BERT, by Nils Reimers and Iryna Gurevych, describes training sentence embeddings that can be compared with cosine similarity. It is a particular method and evaluation, not evidence that any model's nearest passage answers any question. Treat a representation as a component to evaluate rather than an automatic semantic truth detector.

Make vector compatibility visible in the stored record

Hypothetical scenario. Chunk C from document D revision 12 is embedded with encoder E1 and normalization policy N1. Store those identities beside the vector. A query encoded by E2 is not automatically comparable merely because both outputs have the same dimension.

Make vector compatibility visible in the stored record
ArtifactConcrete evidenceDecision boundary
Chunk CD, revision 12, source spanEvidence identity
Vectorencoder E1, normalization N1, dimensionCoordinate-space contract
Queryencoder and score identityCompatible comparison
Versioned transformation: Source chunk C → Encoder E1 / N1.Versioned transformation: Source chunk C → Encoder E1 / N1. Source chunk C to Encoder E1 / N1: versioned transformation; Encoder E1 / N1 to Compatible query space: same scoring contract.Source chunk CEncoder E1 / N1Compatible queryspaceversioned transformationsame scoring contract
Versioned transformation: Source chunk C → Encoder E1 / N1. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

Use one selected score definition consistently for exact reference search and approximate candidates. Dot product, cosine and Euclidean distance impose different assumptions; normalization can change which are equivalent. A high score remains a relevance signal, not evidence of permission, factual support or current applicability. During an encoder migration, build a compatible candidate space, evaluate paired queries and switch readers with version-bound source and ACL evidence. Mixing old and new vectors can create silent ranking errors without any schema failure.

An encoder and a score form a contract

The document side converts searchable text into vectors. The query side converts the request into a compatible representation. Some systems use the same encoder on both sides; others use different encoders trained to work together. Compatibility means that the two outputs and the scoring rule have a shared intended interpretation. Equal vector lengths alone do not establish that. Dense Passage Retrieval, by Vladimir Karpukhin and colleagues, is a concrete example with distinct question and passage encoders trained for a shared retrieval score.

Two inputs must meet in a compatible scoring space The query and document follow their own preprocessing and encoder paths. Their vectors enter the same declared scoring rule. Ranking is evaluated against relevance judgments; a score is not itself an answer-support probability. Query text+ preprocessingDocument text+ preprocessingQuery encodervector qDocument encodervector dDeclared scorethen rank

The contract includes more than a model name: record the revision, input formatting, truncation behavior, pooling if applicable, dimension, normalization, and scoring convention. A model may require different query and document prefixes. Follow the chosen model's documented contract rather than assuming every encoder uses identical inputs.

Dot product multiplies corresponding coordinates and adds the products. Cosine similarity divides that dot product by the product of the vector lengths. For nonzero vectors it compares direction; a zero vector has no defined cosine under that formula and needs explicit handling. The vector-space scoring discussion develops the mathematical basis in a lexical representation. The same geometry does not imply the same training process or relevance behavior for dense learned representations.

Normalization can reverse a ranking

Hypothetical scenario. Use deliberately small vectors so every step is visible. Let the query be q = (1, 0), document A = (2, 0), and document B = (3, 4). These are invented coordinates, not outputs from a real embedding model.

The raw dot products are q·A = 1 × 2 + 0 × 0 = 2 and q·B = 1 × 3 + 0 × 4 = 3. If larger dot product ranks first, B wins. Vector lengths are ||q|| = 1, ||A|| = 2, and ||B|| = √(3² + 4²) = 5.

Cosine(q, A) = 2/(1 × 2) = 1. Cosine(q, B) = 3/(1 × 5) = 0.6. Under cosine, A wins. B's greater raw dot product did not mean its direction was closer. Choosing the score is part of the model/index contract, not an interchangeable implementation detail.

Normalize each nonzero vector to unit length: q stays (1, 0), A becomes (1, 0), and B becomes (0.6, 0.8). Their dot products with q are now 1 and 0.6, equal to the original cosine scores. Squared Euclidean distances are 0 for A and (1 − 0.6)² + (0 − 0.8)² = 0.16 + 0.64 = 0.8 for B.

For unit vectors u and v, expanding the square gives ||u − v||² = ||u||² + ||v||² − 2u·v = 2 − 2u·v. Thus minimizing squared distance and maximizing dot product give the same ranking under these unit-length assumptions and consistent tie handling. Without those assumptions, do not silently substitute one score for another.

Finally, cosine 0.6 is not a 60% probability that B is relevant. The calculation contains no relevance labels or probability-calibration procedure. A threshold must be assessed against the actual task and its false-match and missed-match costs.

In the wild: Embeddings and Similarity: Why “Close” Is Not the Same as “Right”

Sentence-BERT, by Nils Reimers and Iryna Gurevych: Sentence-BERT trains sentence representations compared with cosine similarity.

What the representation preserves can matter more than its size

A larger vector may preserve useful distinctions, but dimension alone does not prove better retrieval. Compare candidate encoders with representative queries, including rare identifiers, negations, ambiguous names, and the languages the collection actually contains. Keep the relevance rule fixed and inspect which cases change.

Input limits also matter. If the encoder truncates a long passage before its exception, the resulting vector cannot represent the excluded text through that input. This is one reason chunking, preprocessing, and representation selection interact. Record what text actually reached the encoder, not merely which source document it came from.

Query and document roles may be asymmetric. A short question and a long answer passage differ in form. Using a compatible trained pair can address that distinction; requiring identical encoders in every design would be too strong. Conversely, independently selecting two popular models with the same output dimension does not establish compatibility.

For a model upgrade, create a distinct representation version and evaluate it with its corresponding query path. Keep enough source lineage to rebuild vectors. Compare against the old route before switching, and define a rollback path. The right migration mechanics depend on how much duplicate storage, rebuilding time, and update lag the application can tolerate.

A partial upgrade can produce plausible but meaningless scores

Hypothetical scenario. A team updates only the query encoder. Its document vectors remain in the older space. Requests still return numeric scores because the dimensions match; no type error exposes the mismatch. Search results change unexpectedly.

A tiny coordinate example shows why there is no general “scores become zero” rule. Suppose old document vectors are A = (1, 0) and B = (0, 1). An old query q = (1, 0) scores A at 1 and B at 0. If the query representation alone changes to q′ = (0, 1), the scores become 0 and 1. The ranking reverses; it does not collapse to all zeros.

This example does not model a particular real upgrade. It establishes that matching shapes cannot prove semantic compatibility. Check representation revisions, preprocessing, and query/document pairing before tuning thresholds. Then evaluate the complete replacement route on held-out cases rather than assuming the old cutoff has retained its meaning.

Four misleading readings of a vector

“A close passage must agree with the question.” Topic similarity can bring a denial or exception close to the statement it qualifies. Read the evidence before deriving an answer.

“Each coordinate is a named concept.” Unless the representation explicitly provides that interpretation, the coordinate is a component of a learned space, not a documented topic label.

“A score threshold transfers between models.” Score distributions and task behavior may change with the representation, normalization, collection, or query population. Reassess the decision boundary.

“A stronger embedding replaces permissions and source checking.” Similarity does not decide authorization, source freshness, or answer support. Those remain separate application responsibilities.

Use embeddings for a measured matching gap

Learned representations are useful candidates when wording differs but relevant relationships can be learned and evaluated. They can support retrieval, clustering, or duplicate-candidate discovery. Each task still needs its own definition of a useful match.

Exact identifiers, structured fields, and narrow deterministic rules may be better served by lexical search or a database query. Combining signals is reasonable when evaluation shows complementary cases; it is additional design work rather than a universal requirement.

Start with a transparent baseline and a fixed relevance set. If the nearest permitted source is wrong even under exhaustive vector scoring, an approximate index is not the first suspect. Investigate representation, source coverage, preprocessing, and the relevance definition before spending effort on search acceleration.

Limits of Embeddings and Similarity: Why “Close” Is Not the Same as “Right”

Vector geometry and training objectives constrain what a similarity score means. Exact nearest-neighbor scoring does not establish task relevance. Preserve the chosen model, normalization and source representation when comparing results or building a replacement collection.

Test the chunk c boundary

An encoder swap preserves dimension and improves a demonstration. What is missing before cutover?

Reveal the design reasoning

An independently labeled relevance set, paired ranking evidence, source/permission completeness and a rollback plan that keeps spaces compatible. Matching vector length cannot establish semantic compatibility.

Decision: Treat embedding space as a versioned index contract, separate from authorization.

Check yourself: test the score's interpretation

A unit query has dot product 0.8 with a document of length 2. What is their cosine similarity, and is it an answer-confidence estimate?

Cosine is 0.8/(1 × 2) = 0.4. It is a geometric score. No answer-confidence probability follows without an additional evaluated relationship between scores and labeled outcomes.

A new query encoder produces the same number of coordinates as the stored document encoder. Is that enough to switch it on?

No. Verify that the encoders are a compatible pair and that preprocessing and scoring match their intended contract. Evaluate the new route. Equal dimensions establish that arithmetic is possible, not that the resulting ranking is useful.

Exhaustive cosine search consistently misses an exact equipment identifier, while lexical search retrieves the right record. Should you first increase approximate-search effort?

No approximate search is involved in that exhaustive result. Investigate the representation and input handling, and consider the lexical signal for this task. Increasing an ANN parameter cannot repair a ranking that is already wrong under the chosen exact scoring rule.

Northwind decision log

Use similarity to propose evidence.
Test relevance against labeled questions.
Keep permissions separate from distance scores.

Go deeper into geometry and learned similarity

Carry the decision forward

The representation and scoring rule help Northwind propose evidence; neither proves the answer. Page 04 moves inside the model: how does a token’s representation change when the surrounding question and policy text change?