Matryoshka Embeddings Explained: Shrinking Vectors Without Retraining Your Search
Matryoshka-trained embedding models let you keep only the first few hundred numbers of each vector. Learn how the training works, how to truncate and re-normalize correctly, and how to use short vectors for cheap two-stage search.
Embedding vectors are the hidden line item in most retrieval systems. A model that emits 1,024 or 3,072 floats per chunk looks harmless in a notebook, but multiply that by tens of millions of chunks and the vector index becomes the most expensive part of the stack: more RAM, bigger disks, slower similarity scans and pricier managed vector databases. Matryoshka embeddings offer a way out that does not require switching models: you simply keep fewer numbers from each vector.
This guide explains what Matryoshka Representation Learning (MRL) actually changes during training, why chopping off the tail of an ordinary embedding usually hurts while chopping a Matryoshka one mostly does not, how to truncate correctly, and how to turn shorter vectors into a cheap two-stage search pipeline.
The idea behind the nesting dolls
The technique comes from the 2022 paper Matryoshka Representation Learning by Kusupati and colleagues. The name refers to Russian nesting dolls: one large representation contains a series of smaller, still-useful representations, each one a prefix of the next. The first 64 numbers form a coarse embedding, the first 128 a sharper one, and so on up to the full width.
A normally trained model has no reason to arrange information this way. Its loss only ever looks at the complete vector, so useful signal can be spread evenly across all coordinates. Cut such a vector in half and you throw away half of the signal at random. A Matryoshka model is pushed during training to pack the most important information into the leading coordinates, so a prefix behaves like a compressed version of the whole.
What changes in training
The training change is small. Instead of computing the contrastive or similarity loss once on the full embedding, you compute it on several prefixes, for example 768, 512, 256, 128 and 64 dimensions, and add the results together, optionally with a weight per size. Every prefix has to work on its own, which forces the model to rank its features by importance. According to the Hugging Face introduction to the topic, this adds no notable training time, and the paper describes the change as a minimal modification to existing pipelines.
In the sentence-transformers library this is a wrapper loss. You keep whatever loss you already use and wrap it:
from sentence_transformers import SentenceTransformer
from sentence_transformers.losses import MultipleNegativesRankingLoss, MatryoshkaLoss
model = SentenceTransformer("microsoft/mpnet-base")
inner = MultipleNegativesRankingLoss(model)
loss = MatryoshkaLoss(model, inner, matryoshka_dims=[768, 512, 256, 128, 64])
# pass `loss` to SentenceTransformerTrainer exactly as you would pass `inner`Note the list of dimensions. Those are the sizes the model is explicitly optimized for, so they are also the sizes you should plan to truncate to later. Picking an arbitrary width in between, such as 300, usually still works, but it is not what the model was trained to support.
Which models already support it
You often do not need to train anything. OpenAI states that text-embedding-3-small (1,536 dimensions by default) and text-embedding-3-large (3,072 by default) were trained with this technique, and its API accepts a dimensions parameter to return shorter vectors directly. OpenAI reports that on the MTEB benchmark a text-embedding-3-large vector shortened to 256 dimensions still beats a full 1,536-dimension text-embedding-ada-002 vector. Several open models, including nomic-embed-text-v1.5, are also trained this way, and the Sentence Transformers documentation shows how to load them truncated.
Before truncating any model, check its model card or documentation for an explicit statement that it was trained with MRL. If it was not, a prefix is just a damaged embedding.
Truncating correctly: slice, then re-normalize
Truncation itself is a slice: keep the first d values. The step people forget is normalization. Most retrieval code assumes unit-length vectors so that a dot product equals cosine similarity. A unit vector stops being unit length the moment you drop coordinates, so you must divide each prefix by its own L2 norm again. Both the OpenAI guide and the Hugging Face write-up call this out. Skip it and a dot-product index will quietly favor documents whose leading coordinates happen to be large.
Some models add one more requirement. The Hugging Face article notes that nomic-embed-text-v1.5 expects a layer normalization over the full vector before slicing. Read the model card, because the correct recipe is model-specific.
With sentence-transformers, the truncate_dim argument does the slicing for you, and normalize_embeddings handles the rescaling:
from sentence_transformers import SentenceTransformer
# Load a Matryoshka-trained model and keep only the first 64 dimensions
model = SentenceTransformer("tomaarsen/mpnet-base-nli-matryoshka", truncate_dim=64)
embeddings = model.encode([
"How do I reset my router?",
"Steps to restart a home Wi-Fi router",
"Best pasta recipes for a weeknight",
], normalize_embeddings=True)
print(embeddings.shape) # (3, 64)
print(model.similarity(embeddings[0], embeddings[1:]))With the OpenAI API, prefer passing dimensions in the request rather than slicing locally; OpenAI recommends it, and you transfer fewer bytes.
A worked example: storage math and two-stage search
Shorter vectors shine in a shortlist-then-rerank pattern, which the Hugging Face article also suggests. Search every document with small vectors to get a few hundred candidates fast, then rescore only those candidates with the full vectors. You keep most of the full-size accuracy while the expensive scan runs over a quarter, or less, of the data.
The script below implements both stages with NumPy and prints the memory needed for 20,000 vectors at different widths. It uses random vectors so it runs without downloading a model; random data has no Matryoshka structure, so treat it as a demonstration of the mechanics, not of retrieval quality.
import numpy as np
def truncate(vectors, dim):
"""Keep the first `dim` coordinates and rescale each row to unit length."""
cut = vectors[:, :dim]
norms = np.linalg.norm(cut, axis=1, keepdims=True)
return cut / np.where(norms == 0, 1, norms)
def two_stage_search(query, corpus, coarse_dim=256, shortlist=100, k=10):
"""Shortlist with short vectors, then rerank the shortlist at full size."""
q_small = truncate(query[None, :], coarse_dim)[0]
c_small = truncate(corpus, coarse_dim)
rough = c_small @ q_small
candidates = np.argpartition(-rough, shortlist)[:shortlist]
q_full = truncate(query[None, :], corpus.shape[1])[0]
exact = truncate(corpus[candidates], corpus.shape[1]) @ q_full
return candidates[np.argsort(-exact)[:k]]
rng = np.random.default_rng(0)
corpus = rng.normal(size=(20_000, 1024)).astype(np.float32)
query = corpus[42] + 0.1 * rng.normal(size=1024).astype(np.float32)
print("top hit:", two_stage_search(query, corpus)[0])
for dim in (1024, 256, 64):
mb = corpus.shape[0] * dim * 4 / 1e6
print(f"{dim:>5} dims -> {mb:6.1f} MB as float32")Running it prints a top hit of 42, the document the query was derived from, followed by 81.9 MB at 1,024 dimensions, 20.5 MB at 256 and 5.1 MB at 64. The arithmetic scales linearly: ten million 1,024-dimension float32 vectors need about 41 GB before any index overhead, while their 256-dimension prefixes need about 10 GB. In production you would typically put only the short vectors in the approximate nearest neighbor index and fetch full vectors for the shortlist from cheaper storage.
Choosing a dimension: a quick checklist
- Confirm the model was trained with MRL and note which dimensions it was trained on.
- Build a small evaluation set of real queries with known relevant documents from your own data.
- Measure recall@10 or nDCG at the full size, then at each trained prefix size.
- Pick the smallest size whose quality loss you can accept, or use it as the shortlist stage and rerank at full size.
- Re-normalize after truncating and re-run the evaluation whenever you change the model or the chunking.
Published numbers are a starting point, not a guarantee. The Hugging Face experiment, which reports that a Matryoshka model kept about 98 percent of its STS benchmark score at roughly 8 percent of its original width, used a single base model and dataset. Your domain may degrade faster or slower.
Common mistakes
- Truncating a model that was never trained with MRL and assuming the quality holds.
- Forgetting to re-normalize, so dot-product scores are no longer cosine similarities.
- Mixing widths in one index, for example storing 256-dimension documents and querying with 1,024-dimension vectors. Query and documents must be cut to the same size by the same recipe.
- Expecting faster encoding. The model still computes the full vector; only storage and search get cheaper.
- Taking a prefix from the end instead of the start. The useful information lives in the leading coordinates.
When not to bother
If your corpus fits comfortably in memory at full size and latency is already fine, truncation adds an evaluation burden for little gain. Matryoshka embeddings are also not the only compression tool: scalar and binary quantization reduce bytes per coordinate rather than the number of coordinates, and the two approaches can be combined. Finally, if recall is your bottleneck rather than cost, shrinking vectors moves you in the wrong direction; a better model, better chunking or a reranker will help more.
Key takeaways
Matryoshka training orders an embedding's information from most to least important, which turns the vector's prefixes into usable smaller embeddings. Use it only with models trained for it, slice from the front, re-normalize, measure on your own queries, and consider spending the savings on a two-stage search that keeps full-size accuracy where it matters.
Enjoyed this?
Get the next deep dive in your inbox. No spam — just the stories worth reading.
Subscribe to the newsletter