Skip to content

Embeddings Put Similarity into Numbers

By Maksym Kuzmitskyi
6 min read
Embeddings Put Similarity into Numbers

Embeddings Put Similarity into Numbers

One document says "human sign-off." The question asks about "approval." A literal word match may miss the connection even though a reader wouldn't.

Embeddings offer a way to search beyond the exact words. They also introduce a number that is easy to treat as more authoritative than it is.

I want to understand that number before putting it between a question and a policy answer. Calling it semantic similarity shouldn't make the mechanism feel mystical.

A representation learned for a purpose

An embedding is a numerical representation of an input. For text retrieval, an embedding model maps a query or passage into a vector: an ordered list of numbers.

The dimensions are coordinates in that representation. They are usually not individually labelled concepts such as approval, production and danger. Reading a coordinate as a human-interpretable fact is generally the wrong mental model.

Training determines which relationships the representation tends to preserve. Two passages can become close because the model learned useful associations in its training tasks. That is different from proving that one passage answers a particular question correctly.

The Sentence Transformers retrieval guide describes separately encoding queries and passages for efficient comparison. This is often called a bi-encoder arrangement. Some models expect different query and document prefixes or modes, so "same model" alone is not the entire encoding contract.

The space must match

If one document was encoded with model A and the query with model B, equal vector lengths do not make their coordinates comparable. The representation space can differ even when the dimensions look identical.

I would identify an embedding space with the model revision, dimensionality and preprocessing conventions that matter for that integration. Changing those can require re-embedding the corpus, the collection of searchable documents.

Truncation also belongs in that contract. A passage longer than the encoder's accepted input may be rejected or shortened. Either way, I want to know whether the paragraph containing the exception was represented at all.

I would record whether vectors are normalized, meaning scaled to a defined magnitude, and whether a query-specific instruction was applied before encoding. Reproducing only the model name can miss both. A different prefix or normalization convention may change the comparisons even when the stored text is identical.

A model upgrade therefore needs a migration plan. Keep old and new representations distinguishable while rebuilding, and compare retrieval on the same labelled cases before switching traffic. Mixing half a newly encoded corpus with queries from the old contract makes a bad migration look like an unexplained search-quality regression.

Our TypeScript example attaches an explicit space label to tiny invented vectors. It is arithmetic, not an embedding model:

type Embedding = { space: string; values: readonly number[] }; function cosine(left: Embedding, right: Embedding): number { if (!left.space.trim() || left.space !== right.space) throw new Error('Embedding space mismatch'); if (left.values.length === 0 || left.values.length !== right.values.length) { throw new Error('Dimension mismatch'); } if (![...left.values, ...right.values].every(Number.isFinite)) throw new Error('Invalid coordinate'); const leftNorm = Math.hypot(...left.values); const rightNorm = Math.hypot(...right.values); if (![leftNorm, rightNorm].every((norm) => Number.isFinite(norm) && norm > 0)) { throw new Error('Cosine needs nonzero finite vectors'); } const similarity = left.values.reduce( (sum, value, index) => sum + (value / leftNorm) * (right.values[index] / rightNorm), 0, ); return Math.max(-1, Math.min(1, similarity)); }

Cosine similarity compares directions after accounting for vector length. The norm is the vector's magnitude. Dividing by each norm makes a longer copy of the same direction comparable to its shorter version.

For these mathematical vectors, cosine ranges from minus one to one. The final clamp handles small floating-point excursions. It does not turn the result into a probability. A score of 0.9 is not a statement that the answer is 90 percent likely to be true.

Keep the made-up numbers visibly made up

These coordinates were chosen by hand so the arithmetic is easy to inspect:

const query: Embedding = { space: 'toy-v1:2d', values: [1, 0] }; const approval: Embedding = { space: 'toy-v1:2d', values: [3, 0] }; const unrelated: Embedding = { space: 'toy-v1:2d', values: [0, 2] }; const opposite: Embedding = { space: 'toy-v1:2d', values: [-1, 0] }; const sameDirection = cosine(query, approval); const perpendicular = cosine(query, unrelated); const oppositeDirection = cosine(query, opposite);

The results are one, zero and minus one. The variable names are labels on this fixture, not evidence that an actual model places approval and unrelated content at those coordinates. No text was encoded and no model endpoint was called.

The tests also reject zero vectors, mismatched dimensions, invalid numbers and mismatched space labels. Those checks prevent meaningless arithmetic from quietly entering a ranking.

Real embeddings usually have far more dimensions. The reason for this example is to understand a comparison, not recommend a handwritten cosine loop for a large production corpus. Established numerical and database tools should do that work at scale.

Similar doesn't mean interchangeable

Two policies can discuss the same subject and disagree. An obsolete policy and its replacement may be extremely similar because only one important sentence changed.

Likewise, negation matters. "Approval is required" and "approval is not required" share most of their words and subject matter. Whether a chosen model separates the relevant distinction well enough is an evaluation question, not something the embedding abstraction guarantees.

I would test actual query/document pairs from the intended domain, including exact identifiers, exceptions, old versions and negative statements. A few appealing nearest neighbors are a demonstration, not a retrieval-quality result.

Distance choice matters too. Cosine, inner product and Euclidean distance behave differently unless the representation and normalization make particular relationships hold. I would follow the chosen model's documented recommendation rather than mix a familiar metric with an arbitrary encoder.

The embedding doesn't replace the source

A vector should retain a link to the source text, revision and permitted audience. It is not a reversible document backup, and it doesn't tell the application which user may read the original.

When the source changes, the old representation can become stale. When the embedding model changes, even unchanged text may need a new representation. Those are data-lifecycle decisions we will return to after building the retrieval path.

For now, the useful achievement is modest: content has a comparable representation under a known contract. The next step is finding nearby representations efficiently while remembering that nearby is only a candidate relationship.

Which pair of almost-identical documents would expose a bad embedding choice in your domain? I'd include that pair before trusting an attractive similarity score.

A note from the author

I’m Maksym Kuzmitskyi, a senior software developer working mainly with React and TypeScript. I build frontend applications and design workflows for working with AI in software delivery. If this article connects with something you’re working on, I’d love to hear from you.

Telegram

More than a blog post

I share frontend news and the reasoning behind it throughout the day. Pick the language that feels natural to you.

Need to discuss your project? Get in touch.