Embedding Models: Turning Text Into Coordinates
An embedding model compresses an arbitrary piece of text into a fixed-length list of numbers with one property: geometric proximity tracks semantic similarity. Everything downstream â retrieval, clustering, deduplication, recommendation, routing â inherits the quality of that mapping, which makes encoder choice a decision with visible product consequences. This lesson covers what the numbers mean, how similarity is computed and where it misleads, how encoders are trained, and how to evaluate one against your own data before you commit a corpus to it.
What a Good Embedding Promises
Three properties define a usable embedding space. Uniformity: vectors spread out rather than collapsing into a narrow cone, so distances remain discriminative. Isotropy: no single direction carries the bulk of the variance, because a dominant common component makes every pair of points look artificially similar. Compositionality: meaning that should combine â negation, modifiers, domain terms â moves the vector in a predictable way rather than being erased.
Real encoders violate each property to some degree, which is why raw cosine scores are hard to interpret. Many models are trained with a contrastive objective: pull a text and its paraphrase together, push an unrelated text away, and normalize outputs so similarity reduces to a dot product. Instruction-tuned encoders go one step further and expect a prefix such as "Represent this sentence for searching relevant passages:", which lets one model serve distinct roles â queries, documents, and answers â that benefit from slightly different projections.
Computing Similarity and Reading It Honestly
Cosine similarity measures the angle between vectors and ignores magnitude; Euclidean distance measures straight-line separation; the dot product folds both together. For normalized vectors all three order results identically, so the choice matters only when you skip normalization. In practice scores cluster in a narrow band â perhaps 0.35 to 0.75 for an English encoder â and the useful signal is relative ranking, not the absolute number.
import numpy as np
def cosine(a, b):
a, b = np.asarray(a, float), np.asarray(b, float)
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
def euclidean(a, b):
return float(np.linalg.norm(np.asarray(a, float) - np.asarray(b, float)))
rng = np.random.default_rng(3)
base = rng.standard_normal(384)
paraphrase = base + 0.15 * rng.standard_normal(384)
unrelated = rng.standard_normal(384)
print("cosine to paraphrase:", round(cosine(base, paraphrase), 3))
print("cosine to unrelated :", round(cosine(base, unrelated), 3))
print("same score via dot :", round(float(
(base / np.linalg.norm(base)) @ (paraphrase / np.linalg.norm(paraphrase))), 3))
doc = rng.standard_normal(384) * 5.0
print("magnitude ignored by cosine:", round(cosine(base, doc), 3),
" euclidean:", round(euclidean(base, doc), 3))
Build an intuition for your model's score distribution by embedding a few hundred real pairs and plotting them. When you later set a similarity threshold for deduplication or routing, that distribution tells you where to cut it.
How Encoders Learn Their Geometry
Training objectives differ more than architectures do. A siamese or bi-encoder runs two texts through a shared encoder and applies a contrastive loss over a batch, so every in-batch negative is free supervision â which is why large batch sizes measurably improve retrieval models. Triplets add hard negatives that look similar on the surface but differ in meaning. Masked-language pretraining produces general representations that need a second contrastive stage to become retrieval-ready. Synthetic distillation trains a small encoder on judgments produced by a larger model or a generative model, transferring ranking quality at a fraction of the cost.
| Training signal | Supervision cost | Typical strength | Typical weakness |
|---|---|---|---|
| NLI and paraphrase pairs | Moderate, labeled | Strong semantic match | Weak on jargon and IDs |
| Retrieval click logs | Free, implicit | Matches real queries | Biased by position and popularity |
| In-batch contrastive | Free with scale | Broad discrimination | Hardest negatives are random |
| Hard-negative mining | Medium | Sharp decision boundary | Mining errors poison training |
| Synthetic teacher labels | Low per example | Domain adaptation cheaply | Inherits teacher hallucinations |
| Fine-tune on your queries | High, curated | Best in-domain ranking | Overfits without held-out set |
If your domain has a distinctive vocabulary, a small contrastive fine-tune on a few thousand real query-document pairs usually beats moving to a larger general-purpose encoder.
Choosing an Encoder for Production
The decision is a triangle among quality, cost, and control. Hosted APIs give the strongest out-of-box quality with no infrastructure, but they add a network hop, a per-token bill, and a data-handling question. Open-weight models run locally, keep text inside your boundary, and cost only compute, but you own batching, upgrades, and quality regression testing. Dimension is a hidden third axis: a 1,024-dimensional float32 vector costs four times the memory of a 384-dimensional one, multiplied across your entire corpus.
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("all-MiniLM-L6-v2")
corpus = [
"Refunds are processed within 30 days of delivery.",
"Standard shipping arrives in three to five business days.",
"Open a support ticket if your package arrives damaged.",
]
queries = [
"How long until I get my money back?",
"When will my order show up?",
"The box was crushed on arrival.",
]
corpus_emb = model.encode(corpus, normalize_embeddings=True)
query_emb = model.encode(queries, normalize_embeddings=True)
for q, qv in zip(queries, query_emb):
scores = util.cos_sim(qv, corpus_emb)[0]
best = int(scores.argmax())
print(f"{scores[best]:.3f} {q} -> {corpus[best]}")
dims = model.get_sentence_embedding_dimension()
print("dimension:", dims, " float32 per vector:", dims * 4, "bytes")
Run exactly this test with your own corpus and queries. A model that shines on generic benchmarks and mediocre on your phrasing is common, and this script finds out in minutes.
Evaluating on Data You Actually Own
Retrieval quality is measured with ranking metrics over labeled pairs: precision and recall at k, mean reciprocal rank, and normalized discounted cumulative gain. Build the labeled set by sampling real queries and having someone mark which passages are acceptable answers â a few hundred queries with multiple relevant passages each is enough to rank candidate encoders reliably. Include adversarial cases: queries that share vocabulary with the wrong document, queries with no match, and abbreviations your users type.
Two additional checks catch problems the aggregate score hides. Cluster your corpus by embedding and read the clusters; near-duplicate documents inflating recall and domain topics bleeding into each other both show up visually. And track index freshness: an encoder upgrade means every stored vector must be recomputed, so record the model identifier with each embedding or you will silently mix incompatible spaces in one index.
Traps That Bite in Deployment
The classic failure is embedding queries and documents with models that were not trained as a pair, or with different prefixes, which yields vectors in effectively different spaces. Second is truncation: many encoders cap at 256 or 512 tokens, so long documents are silently clipped and their endings never indexed â chunk before embedding, always. Third is threshold drift after a model upgrade, where a fixed similarity cutoff stops meaning what it used to. Fourth is cost underestimation, since embedding a ten-million-document corpus through an API is a real line item, and re-embedding after a schema change doubles it.
Guard all four with the same discipline: a staging index built from a sample of production documents, a labeled query set replayed against it before any cutover, and a recorded decision about which encoder version is live. The rebuild itself is mechanical â embed, verify counts, switch the read path, keep the old index for a rollback window â so the only interesting question is whether the metrics held, and that question needs evidence you collected beforehand.
â ī¸Never mix encoder versions in one index
Common Mistakes
Setting a similarity threshold from intuition
Fix: Sample real pairs, plot score distributions, and cut where positive and negative scores separate
Embedding documents longer than the model maximum
Fix: Split on structure first, then embed, and verify no chunk is clipped
Comparing cosine scores across models
Fix: Absolute values are model-specific; compare rankings on a labeled set instead
Evaluating only on public benchmarks
Fix: Label a few hundred of your own queries â domain phrasing decides real performance
Forgetting to re-embed after fine-tuning an encoder
Fix: Treat the corpus and the encoder as a versioned pair with an atomic rebuild
Key Takeaways
- Embeddings trade magnitude for direction, so normalized vectors make cosine a dot product
- Contrastive training with in-batch negatives is the standard way retrieval encoders learn
- Absolute scores are hard to calibrate; ranking metrics on your own queries decide quality
- Hosted versus open-weight is a trade of cost, latency, and data control, not raw quality
- Chunk, normalize, version, and re-embed deliberately â most failures are pipeline issues