Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Retrieval (RAG)AI guideIntermediate#rag#embeddings#retrieval#evaluation
Frame · ai-engineering / rag / 04-choosing-embedding-models.mdGuide 016 / 103

Choosing embedding models

The embedding model decides what "similar" means in your system. Two passages are neighbours in the index only if this model thinks they are. Picking one is mostly a matter of discipline: use public benchmarks to build a shortlist, then let your own queries decide. This doc covers what to look at, how dimensions and Matryoshka truncation change the cost picture, and how to run a quick bake-off.

Why it matters

Swapping embedding models is expensive after launch because every vector in the index has to be recomputed, and vectors from different models are not comparable. So the choice tends to stick. At the same time, models differ a lot on domain text. A model that tops a general leaderboard can lose to a smaller one on your support tickets, legal clauses or code. And the operational differences are real: dimension count drives storage and memory, context length limits your chunk size, and hosting (API versus self-hosted) determines latency, cost and where your data goes.

How it works

An embedding model maps text to a fixed-length vector so that semantically related texts have high cosine similarity. For retrieval you care about a few properties:

  • Retrieval quality on your domain. The only number that really matters.
  • Asymmetric query and document handling. Many models expect a different prefix or input type for queries versus passages (for example a "query:" instruction, or an input_type parameter in some APIs). Using the wrong one quietly hurts quality.
  • Max input length. Text beyond the limit is truncated. Your chunks must fit.
  • Dimensions. More dimensions usually means more nuance and more storage. A float32 vector of 1,536 dimensions is about 6 KB before index overhead, so a 10 million chunk corpus is roughly 60 GB of raw vectors.
  • Multilinguality. If queries and documents can be in different languages, you need a multilingual model trained for cross-lingual retrieval.
  • Dense, sparse or multi-vector output. Some models (BGE-M3 is a well-known open example) produce dense, sparse and multi-vector representations from one model, which simplifies hybrid search.

Leaderboards are a shortlist

The MTEB leaderboard on Hugging Face is the standard public reference. Two cautions. First, the overall average mixes many task types (classification, clustering, STS and more); for RAG, sort by the retrieval task scores. Second, the top of the board changes often and differences of a point or two rarely survive contact with your data. Use it to pick three or four candidates across price points (one hosted API model, one strong open-weight model, one small fast model), not to pick the winner.

Matryoshka embeddings

Matryoshka Representation Learning trains a model so that the first N dimensions of the vector are themselves a usable embedding. OpenAI's text-embedding-3 models expose this through a dimensions parameter, and OpenAI reported that text-embedding-3-large truncated to 256 dimensions still outscored the older text-embedding-ada-002 at 1,536 on MTEB. Many open models support it too, and sentence-transformers can truncate at load time. This enables adaptive retrieval: search a shortlist with short vectors, then rescore the shortlist with full vectors.

Rendering diagram…

Reference architecture

Once chosen, treat the embedding model as a versioned dependency of the index. The embedding service should be the only place that knows the model name, the prefixes and the dimension.

Rendering diagram…

The shadow index is the important part. When you upgrade models, build a new index next to the old one, run your eval set against both, then switch an alias. Never mix vectors from two models in one index.

Code

A small bake-off with sentence-transformers: embed a labeled set with candidate models (and a truncated dimension), and compute recall@5. Swap in your own queries and chunks.

from sentence_transformers import SentenceTransformer

corpus = {
    "c1": "Refunds are processed within 5 business days of approval.",
    "c2": "You can change your shipping address until the order is packed.",
    "c3": "Gift cards cannot be exchanged for cash.",
}
eval_set = [
    ("how long until I get my money back", {"c1"}),
    ("can I update where my parcel goes", {"c2"}),
]

candidates = [
    ("BAAI/bge-m3", None),
    ("BAAI/bge-m3", 256),  # Matryoshka-style truncation test
    ("sentence-transformers/all-MiniLM-L6-v2", None),
]

ids = list(corpus)
for name, dim in candidates:
    model = SentenceTransformer(name, truncate_dim=dim)
    doc_emb = model.encode([corpus[i] for i in ids], normalize_embeddings=True)
    hits = 0
    for query, relevant in eval_set:
        q_emb = model.encode([query], normalize_embeddings=True)
        scores = model.similarity(q_emb, doc_emb)[0]
        top5 = {ids[j] for j in scores.argsort(descending=True)[:5].tolist()}
        hits += len(top5 & relevant) / len(relevant)
    print(f"{name} dim={dim or 'full'} recall@5={hits / len(eval_set):.2f}")

Two caveats on this sketch. Truncating a model that was not trained with Matryoshka loss degrades it badly, so check the model card before trusting a truncated score. And some models need query instructions or prefixes for best results; the model card will say so.

For hosted APIs the equivalent knob is a request parameter, for example client.embeddings.create(model="text-embedding-3-large", input=texts, dimensions=1024) with the OpenAI SDK.

Trade-offs and pitfalls

  • Benchmarks leak. Public datasets may overlap with training data. Your own held-out queries are the only clean test.
  • Toy corpora flatter every model. Run the bake-off on thousands of chunks with realistic distractors, not ten.
  • Normalization matters. If you use dot product in the index, normalize vectors (or use a model that already does). Mismatched distance metrics are a common silent bug.
  • Hosted APIs add a dependency. Every query needs an embedding call, so the provider's latency and availability become yours. Batch at ingestion; cache query embeddings for repeated queries.
  • Self-hosting needs GPUs at scale. Ingesting millions of chunks with a large open model is a real compute job. Plan throughput.
  • Fine-tuning is an option. For specialized domains, a contrastive fine-tune of an open model on your own query-passage pairs can beat a larger general model. Do it after you have an eval set, not before.
  • Do not forget the sparse side. Even the best dense model is weak on exact identifiers. Pair it with BM25 or a sparse model.

Checklist

  • Shortlist candidates from the MTEB retrieval scores, across at least two price or size tiers.
  • Build an eval set of real queries with labeled relevant chunks before choosing.
  • Test with the correct query and passage prefixes or input types for each model.
  • Measure recall@k and latency, and estimate storage at your corpus size and chosen dimension.
  • Consider Matryoshka truncation or quantization to cut storage, and re-measure.
  • Pin model name and version in one embedding service; never mix models in one index.
  • Plan upgrades as a shadow index plus eval plus alias swap.

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.