Embeddings
An embedding model turns text into a fixed-length vector so that similar meanings land close together; compare vectors with cosine similarity to search, cluster, classify or deduplicate by meaning instead of keywords.
Analogy: GPS coordinates for meaning: every text gets a point on a map with hundreds of dimensions, and "how related are these?" becomes "how far apart are these points?"
How it works
- An encoder model outputs one dense vector per text, typically 384 to 3,072 floats.
- Contrastive training on pairs like (question, answer) puts "reset my password" near "I can't log in" without shared keywords.
- Normalize vectors once: cosine then equals dot product and L2 ranks the same, so use cheap dot product.
- Vectors from different models are not comparable: switching models means re-embedding everything.
- Embeddings blur exact tokens like SKUs and error codes, so production search also runs BM25.
Check yourself
Answer to mark it learned; your answers aren't scored.
You moved help-center search from BM25 to embeddings. Paraphrased queries now work, but "error E-4012" ranks the exact article below generic error pages. Best fix?
Go deeper
Full explanation
An embedding is a dense vector, typically 384 to 3,072 floats, that an encoder model produces from a piece of text (or an image). The model is trained, usually with contrastive learning on pairs like (question, answer), so that texts with similar meaning get vectors pointing in similar directions. "Reset my password" and "I can't log in" share no keywords but land close together.
You compare vectors with a similarity metric:
- Cosine: angle between vectors, ignores length. The default for text.
- Dot product: angle and magnitude; cheapest to compute.
- Euclidean (L2): straight-line distance.
If you normalize vectors to unit length, cosine equals dot product and L2 gives the same ranking, so most systems normalize once and use dot product. Use the metric the model was trained with.
Typical uses: semantic search and RAG retrieval (via Vector databases and ANN indexes: HNSW, IVF, PQ), topic clustering, classification with a small model on top of the vectors, near-duplicate detection, recommendations and Semantic caching.
Two rules: vectors from different models are not comparable, so changing models means re-embedding everything; and embeddings blur exact tokens (SKUs, error codes, names), which is why production search adds BM25 via Hybrid search & RRF.
Code Embed and rank by cosine similarity with sentence-transformers
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2") # 384 dims, small and fast; any embedding model
docs = [
"How do I reset my password?",
"Steps to recover access to your account",
"Our office is closed on public holidays",
]
query = "I forgot my login credentials"
# Unit-length vectors: cosine similarity becomes a plain dot product
D = model.encode(docs, normalize_embeddings=True) # shape (3, 384)
q = model.encode(query, normalize_embeddings=True) # shape (384,)
scores = D @ q # cosine similarities in [-1, 1]
for i in np.argsort(-scores):
print(f"{scores[i]:.3f} {docs[i]}")
# The general formula, for vectors that are not normalized
def cosine(a: np.ndarray, b: np.ndarray) -> float:
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
# Near-duplicate check: threshold must be calibrated per model on labeled pairs
is_dup = cosine(D[0], D[1]) > 0.9Real example
An internal help-center search fails on "my laptop won't turn on" because the right article says "notebook does not power up": no shared keywords, so BM25 never surfaces it. You embed 200k article chunks with a 768-dim model: 200k × 768 × 4 bytes ≈ 0.6 GB of float32, which fits in RAM. At query time you embed the question and take the top 10 by cosine; the article now ranks first. Then "error E-4012" fails the other way, ranked below generic error pages, because embeddings blur exact codes. That's the cue for Hybrid search & RRF.
Trade-offs +3 · −3
+ You gain
- Matches meaning across paraphrases, synonyms and, with a multilingual model, languages.
- Compute once offline; query-time comparison is a fast vector operation.
- One representation serves search, clustering, classification and dedup.
− You pay
- Weak on exact tokens, negation and numbers: "not refundable" sits close to "refundable".
- Locked to one model: an upgrade means re-embedding and re-indexing the whole corpus.
- Memory adds up: 1M vectors × 1,536 dims in float32 ≈ 6 GB before index overhead.
Use it when
Whenever the same idea shows up in different words: semantic search and RAG retrieval, clustering feedback, few-label classification, dedup, recommendations. The default for any "find similar" feature over unstructured text.
Avoid it when
Exact lookups (IDs, SKUs, error codes, names), structured filters, or logic such as negation and date ranges. Use keyword search, SQL, or a cross-encoder or LLM on top.
Numbers to know 4
- Common dims: 384 (all-MiniLM-L6-v2), 768 (BERT-base class), 1,024, 1,536 and 3,072 (OpenAI text-embedding-3-small / -large).
- Storage: dims × 4 bytes per float32 vector; 1M × 1,536 ≈ 6.1 GB. int8 is 4× smaller, binary 32×.
- Unit vectors: cosine = dot product, and L2² = 2 − 2·cosine, so all three rank identically.
- Max input: text-embedding-3 takes 8,192 tokens; all-MiniLM-L6-v2 truncates at 256 word pieces.
Common pitfalls 4
- Mixing vectors from two models or versions in one index: similarities become meaningless and nothing errors.
- Silent truncation: text past the model's max input is dropped, so that content becomes unsearchable.
- Reusing a similarity threshold across models: score ranges differ widely, so calibrate on labeled pairs per model.
- Skipping the query/document prefixes that asymmetric models such as E5 expect ("query: ", "passage: ").
Interview questions 2
Answer out loud first, then reveal.
Cosine, dot product or Euclidean distance: which would you use?Show answer
Whatever the model was trained with, which for most text models is cosine. In practice I normalize every vector to unit length at write time; then cosine and dot product are identical and Euclidean gives the same ranking, so I use dot product because it's the cheapest and every vector database optimizes it. The case to watch is a model trained with unnormalized dot product, where magnitude carries signal: normalizing would throw that away, so I check the model card first.
We want to switch to a better embedding model. What does that involve?Show answer
A migration, not a config change. Vectors from different models live in different spaces, so I re-embed the whole corpus into a new index. First I prove the gain on our own labeled queries, recall@10 on our data rather than a leaderboard score. Then I backfill the new index in parallel, dual-write new documents, shadow or A/B the traffic, and cut over keeping the old index for rollback. The API bill is usually small: 100M chunks × ~500 tokens at ~$0.02 per 1M tokens is ~$1,000. The real cost is reindex time and eval work.