Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← FoundationsAI guideBeginner#foundations#embeddings#vectors#similarity
Frame · ai-engineering / foundations / 05-embeddings-and-similarity.mdGuide 005 / 103

Embeddings and similarity

An embedding is a fixed-length list of numbers that represents the meaning of a piece of text (or an image, or audio). Texts with similar meaning land close together in that vector space, so "how do I reset my password" and "forgot login credentials" end up near each other even though they share almost no words. Embeddings are the engine behind semantic search, retrieval-augmented generation, deduplication, clustering and recommendation.

Why it matters

Generation models are expensive per token and limited by context. Embeddings are cheap, fast, and let you search millions of items in milliseconds. In most production LLM systems, the quality of the answer is capped by the quality of retrieval, and retrieval quality starts with the embedding model and how you chunk and compare. If you understand what a similarity score does and does not mean, you avoid a whole class of "the bot ignored the right document" bugs.

How it works

An embedding model is a neural network trained (usually contrastively) so that related pairs, like a question and its answer passage, produce vectors pointing in similar directions, while unrelated pairs point apart. You call it once per document at index time, store the vectors, then embed each query at search time and look for the nearest stored vectors.

Rendering diagram…

Similarity measures

  • Cosine similarity is the dot product divided by the product of the vector lengths. It measures the angle between vectors and ranges from -1 to 1.
  • Dot product equals cosine when vectors are normalized to unit length. Many providers return normalized vectors, which lets you use the cheaper dot product, but check your model's docs before assuming.
  • Euclidean distance is also used. For unit vectors it ranks results the same way as cosine.

A similarity score is relative, not absolute. A cosine of 0.8 might be a great match for one model and mediocre for another. Calibrate thresholds per model on your own data, and never compare scores across models.

Dimensions and truncation

Vectors typically have hundreds to a few thousand dimensions. OpenAI's text-embedding-3 models accept a dimensions parameter that returns shorter vectors (the small model defaults to 1536). This works because of Matryoshka-style training, where the first dimensions carry the most information. Shorter vectors cut storage and speed up search at some quality cost, so test retrieval quality at the size you pick.

Picking a model

The MTEB leaderboard on Hugging Face benchmarks embedding models across retrieval, classification, clustering, reranking and similarity tasks, and the top spot changes frequently. Filter to the retrieval tab if you are building search, then test the top few candidates on your own corpus. Domain-specific text (legal, medical, code, non-English) often reorders the leaderboard. Open-weight embedding models are strong enough that self-hosting is a real option when data residency matters.

Reference architecture

A minimal semantic search service separates indexing from querying and keeps the model version attached to every vector.

Rendering diagram…

Code

This Python snippet embeds a few documents with OpenAI's API, normalizes them, and ranks them against a query with cosine similarity in NumPy. For a few thousand items, brute force like this is perfectly fine.

import numpy as np
from openai import OpenAI

client = OpenAI()
MODEL = "text-embedding-3-small"

docs = [
    "To reset your password, open Settings and choose Security.",
    "Our refund policy allows returns within 30 days.",
    "Two-factor authentication can be enabled from the Security page.",
    "We ship to over 40 countries worldwide.",
]

def embed(texts: list[str]) -> np.ndarray:
    response = client.embeddings.create(model=MODEL, input=texts)
    vectors = np.array([item.embedding for item in response.data])
    return vectors / np.linalg.norm(vectors, axis=1, keepdims=True)

doc_vectors = embed(docs)
query_vector = embed(["I forgot my login credentials"])[0]

scores = doc_vectors @ query_vector  # cosine, since vectors are unit length
for i in np.argsort(scores)[::-1]:
    print(f"{scores[i]:.3f}  {docs[i]}")

You should see the password and two-factor passages rank above refunds and shipping. Swap in a different model and the absolute scores will shift while the ranking hopefully stays similar.

Trade-offs and pitfalls

  • Mixing models. Query and document vectors must come from the same model and the same dimension setting. Store the model name with each vector and re-embed everything on upgrade.
  • Chunking dominates. Chunks that are too large blur topics together; chunks that are too small lose context. Start with passages of a few hundred tokens with light overlap, then tune.
  • Lexical gaps. Embeddings can miss exact identifiers, part numbers and rare names. Hybrid search (BM25 plus vectors) usually beats either alone.
  • Asymmetric tasks. Some models expect different prefixes or input types for queries and documents. Read the model card.
  • Thresholds are model specific. Do not hard-code a magic 0.75 from a blog post.
  • Index cost. Approximate nearest neighbor indexes (HNSW and friends) trade recall for speed and memory. Measure recall at your chosen settings.
  • Privacy. Embeddings can leak information about the source text. Treat them as sensitive as the text itself.

Checklist

  • One embedding model and dimension per index, recorded with every vector.
  • Candidate models tested on your own queries, not just the leaderboard average.
  • Chunk size and overlap chosen by measuring retrieval recall.
  • Hybrid lexical plus vector search considered for identifier-heavy content.
  • Similarity thresholds calibrated per model on labeled examples.
  • A re-embedding plan exists for model upgrades.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.