# Shrinking vector search: Matryoshka embeddings, binary quantisation and rescoring

Embedding indexes grow fast: 50 million vectors at 1,024 float32 dimensions need about 205 GB. This article explains two techniques that shrink them, Matryoshka truncation and quantisation, works the storage maths, and shows the rescoring step that keeps retrieval quality high.

Every retrieval-augmented generation (RAG) system stores text as embeddings: lists of numbers that place similar meanings close together. A typical modern embedding has 768 or 1,024 dimensions, each stored as a 4-byte float. That is 3 to 4 kilobytes per chunk of text, and the cost adds up quickly. A corpus of 50 million chunks at 1,024 float32 dimensions needs about 205 GB, usually in memory, for fast search.

Two techniques cut this cost sharply. Matryoshka training makes the first part of each embedding useful on its own, so you can drop the rest. Quantisation stores each number in fewer bits, down to a single bit. Combined with a cheap rescoring step, they keep most of the retrieval quality at a fraction of the storage. This article explains how each works, works through the numbers, and shows how to combine them.

## What happened

### Sentence Transformers 6.3.0 is released (11 November 2026)

The Sentence Transformers library, a widely used Python package for embedding models, published version 6.3.0 on PyPI on 11 November 2026, three weeks after 6.2.0. Its current documentation covers both techniques in this article: training with `MatryoshkaLoss` and its two-dimensional variant `Matryoshka2dLoss`, loading a model with `truncate_dim` to produce shorter embeddings, and a `quantize_embeddings` function with binary, unsigned binary and int8 precision. The documentation also describes a demo that searches 41 million Wikipedia texts using a binary index for candidates and int8 embeddings for rescoring.

These tools are not new in themselves, but they have become standard parts of the embedding stack, and some embedding models, such as the nomic-embed-text-v1.5 model used in the documentation's truncation example, are trained for it. The engineering question is how to combine them well.

## How Matryoshka embeddings work

### The idea

Matryoshka Representation Learning (MRL), introduced in a 2022 paper, trains an embedding model so that every prefix of the vector is itself a good embedding. The name comes from Russian nesting dolls: a 768-dimensional embedding contains a good 512-dimensional embedding, which contains a good 256-dimensional one, and so on.

An ordinary embedding model spreads information across all dimensions with no order, so cutting off half the dimensions loses information at random. A Matryoshka model learns to put the most important information first, like a news article written in inverted-pyramid style, where the first paragraph carries the main facts and later paragraphs add detail.

### The training loss

Training is simple. Take your usual loss L, for example a contrastive loss that pulls matching pairs together and pushes others apart. Apply it to the full embedding and to several truncated versions, and add the results:

L_MRL = Σ_m w_m · L(z[1..m])

where z[1..m] is the first m dimensions of the embedding and w_m is an optional weight. In Sentence Transformers this is one line: wrap a base loss in `MatryoshkaLoss` with a list of dimensions such as `[768, 512, 256, 128, 64]`. The `Matryoshka2dLoss` variant also trains the model to work with fewer layers, so you can shorten both the vector and the computation.

### What you gain and what you do not

The documentation reports an experiment with two MPNet-based models trained on natural language inference data, one with and one without the Matryoshka loss, evaluated on the STS Benchmark. At 64 of 768 dimensions, which is 8.3 percent of the full size, the Matryoshka model kept 98.37 percent of its full-size performance, compared with 96.46 percent for the standard model.

The documentation is also clear about the limit: a Matryoshka model is not faster, smaller or more memory-efficient to run. Only the storage and processing of the resulting embeddings become cheaper. At query time you still run the full model, then keep the first m dimensions.

One practical detail matters. After truncation, re-normalise each vector to unit length if you use cosine similarity or dot product on normalised vectors. A prefix of a unit vector is shorter than 1, and its length varies from vector to vector.

## How embedding quantisation works

### Scalar quantisation to int8

Scalar quantisation maps each float32 value to one of 256 integer levels. Sentence Transformers computes the minimum and maximum of each dimension over a calibration set, splits that range into buckets, and assigns each value to a bucket. Storage falls by a factor of 4: in the documentation's example, two 1,024-dimensional embeddings take 8,192 bytes as float32 and 2,048 bytes as int8.

The calibration set matters. With too few embeddings, the ranges are wrong and values cluster in a few buckets. The library warns when it has to compute buckets from very few embeddings, and recommends a large calibration set or precomputed ranges.

### Binary quantisation

Binary quantisation goes further: each dimension becomes one bit, 1 if the value is above zero and 0 otherwise. A 1,024-dimensional embedding becomes 1,024 bits, packed into 128 bytes. That is a 32-fold reduction. Similarity becomes the Hamming distance, the number of bit positions where two vectors differ, which CPUs compute with an XOR and a population count. This is among the cheapest comparisons a computer can do.

The loss of information is large, so binary search on its own ranks documents less accurately. The fix is rescoring.

### Rescoring: shortlist cheaply, rank precisely

Rescoring, proposed by Yamada and colleagues in 2021 for binary passage retrieval, works in two stages. First, search the binary index with the binary query and keep `rescore_multiplier × top_k` candidates. Second, compute the dot product between the full float32 query and those candidates' stored embeddings, and re-rank. The query is only one vector, so keeping it in full precision is free. The Sentence Transformers documentation reports that this preserves up to about 96 percent of retrieval performance while cutting memory and disk use by 32 times.

Think of a library. The binary index is the card catalogue: quick to scan, but it only tells you which shelf area to look in. Rescoring is walking to that area and reading the spines carefully.

### A small demonstration

The code below builds a synthetic corpus, searches it with binary codes, and rescores. Synthetic vectors are harder than real embeddings, so the absolute numbers are lower than real models achieve; the point is the mechanism and the trend as the shortlist grows.

```python
import numpy as np
rng = np.random.default_rng(0)
N, D, Q, k = 20_000, 256, 200, 10
proj = rng.normal(size=(32, D))                              # 32 hidden factors
docs = (rng.normal(size=(N, 32)) @ proj + 0.5 * rng.normal(size=(N, D))).astype(np.float32)
docs /= np.linalg.norm(docs, axis=1, keepdims=True)
idx = rng.integers(0, N, Q)
queries = docs[idx] + 0.08 * rng.normal(size=(Q, D)).astype(np.float32)
queries /= np.linalg.norm(queries, axis=1, keepdims=True)

exact = np.argsort(-queries @ docs.T, axis=1)[:, :k]          # float32 ground truth
dbits = np.packbits(docs > 0, axis=1)                         # 256 dims -> 32 bytes
qbits = np.packbits(queries > 0, axis=1)
ham = np.unpackbits(qbits[:, None, :] ^ dbits[None, :, :], axis=2).sum(2)

def recall(found): return np.mean([len(set(f) & set(e)) / k for f, e in zip(found, exact)])
print("binary only:", recall(np.argsort(ham, axis=1, kind="stable")[:, :k]))
for mult in (4, 10):
    cand = np.argsort(ham, axis=1, kind="stable")[:, :k * mult]
    scores = np.einsum("qd,qcd->qc", queries, docs[cand])       # float query vs candidates
    top = np.take_along_axis(cand, np.argsort(-scores, axis=1)[:, :k], 1)
    print(f"rescore x{mult}:", recall(top))
```

On this data, recall at 10 against exact float32 search is 0.32 with binary codes alone, 0.56 after rescoring the top 40, and 0.74 after rescoring the top 100. Each vector takes 32 bytes instead of 1,024. On real embedding models the documented results are much stronger, but the shape is the same: a larger shortlist buys back quality at a small, predictable cost.

## Putting them together: the storage maths

The two techniques multiply. Truncation reduces the number of dimensions; quantisation reduces the bits per dimension. Here is the storage for 50 million vectors under different settings, computed as vectors × dimensions × bits ÷ 8:

| Setting | Bytes per vector | Total for 50 million vectors | Reduction |
|---|---|---|---|
| 1,024 dims, float32 | 4,096 | 204.8 GB | 1× |
| 1,024 dims, int8 | 1,024 | 51.2 GB | 4× |
| 1,024 dims, binary | 128 | 6.4 GB | 32× |
| 256 dims (Matryoshka), int8 | 256 | 12.8 GB | 16× |
| 256 dims (Matryoshka), binary | 32 | 1.6 GB | 128× |

These figures cover raw vectors only; index structures such as HNSW graphs add their own overhead.

The documented Wikipedia demo shows a realistic layout. It keeps a binary index of 41 million embeddings in memory, 5.2 GB, which matches 41 million × 1,024 bits ÷ 8 = 5.25 GB. It keeps int8 embeddings on disk, 47.5 GB, and loads only the 40 candidates per query for rescoring to get the top 10. Total: 5.2 GB of memory and about 52 GB of disk, compared with roughly 200 GB of each for plain float32 search.

### A tiered design

A practical pattern that follows from this:

1. Embed documents once at full size with a Matryoshka-trained model.
2. Store a short binary code (for example the first 256 or 512 dimensions, binarised) in a fast in-memory index.
3. Store int8 or float vectors of the same documents on disk or in cheaper storage.
4. At query time, embed the query at full precision, search the binary index for a shortlist, then rescore the shortlist with the higher-precision vectors.
5. Optionally re-rank the final top results with a cross-encoder for the best quality.

The documentation notes that quantised retrieval combines well with Matryoshka truncation and with retrieve-and-rerank using cross-encoders.

## What it means in practice

For most RAG systems, vector storage and memory are a large share of retrieval cost, and they scale linearly with the corpus. A 32-fold or 128-fold cut changes what hardware you need: an index that required a large memory-optimised server can fit on an ordinary machine, or even on a laptop for development. It also speeds up search, because more of the index fits in fast cache.

The trade-off is a small, measurable loss in ranking quality, mostly recovered by rescoring. The rescoring multiplier becomes a tuning knob like any other: a larger shortlist costs more disk reads and dot products per query but restores more of the exact ranking. Because the loss depends on your model and your data, you need your own evaluation set to choose dimensions, precision and multiplier.

The [embedding space simulation](/ai-simulations/embedding-space) shows how similar texts cluster, and the [HNSW simulation](/ai-simulations/hnsw-vector-search) shows how graph indexes find neighbours quickly, which is complementary to shrinking the vectors. For the retrieval side of RAG, the [reranking simulation](/ai-simulations/rag-rerank) shows how a second-stage scorer reorders a shortlist.

## What to do now

1. **Measure your baseline.** Build a labelled retrieval set from real queries and record recall at 10 and your current storage per vector before changing anything.
2. **Check whether your model supports truncation.** Use a model trained with Matryoshka loss if you plan to truncate; truncating an ordinary model loses more quality.
3. **Re-normalise after truncation.** Divide each truncated vector by its length before cosine or dot-product search.
4. **Calibrate int8 on real data.** Compute per-dimension ranges from a large, representative sample of your corpus, not from a handful of vectors.
5. **Start with binary plus rescoring.** Try a binary index with a rescore multiplier of 4, then raise it until recall stops improving enough to justify the cost.
6. **Keep the query in full precision.** Quantise only the stored documents; rescoring with a float32 query costs almost nothing.
7. **Separate memory and disk tiers.** Keep the small binary index in memory and the larger int8 or float vectors on disk, loading only shortlisted rows.
8. **Re-evaluate after model changes.** When you switch embedding models, recheck calibration ranges and the best dimension and multiplier, since they are model-specific.

## Risks and open questions

**Quality loss is data-dependent.** Published retention figures come from specific models and benchmarks. Domain-specific corpora, such as legal or code search, may lose more.

**Calibration drift.** int8 buckets computed on last year's corpus may fit new content poorly. Ranges should be recomputed when the data changes.

**Vector database support varies.** Not every database supports binary or int8 vectors, Hamming distance, or two-stage rescoring natively, which can force custom code.

**Truncation without Matryoshka training is risky.** Cutting dimensions from an ordinary model works poorly; the gains in this article assume a model trained for it.

**Watch next:** native support for binary-plus-rescore pipelines in vector databases, and whether new embedding models ship with documented quality figures at each truncation size and precision.

## Frequently asked questions

### What is a Matryoshka embedding?

It is an embedding trained so that its first m dimensions are a good embedding on their own, for several values of m. You can truncate it to save storage and compute while keeping most of its quality.

### Does Matryoshka training make the model faster?

No. The model runs at the same speed and size. Only storing, comparing and searching the shorter embeddings is cheaper, unless you also use a variant that trains for fewer layers.

### How much quality does binary quantisation lose?

On its own, quite a lot of ranking precision. With rescoring of a shortlist using the float32 query, the Sentence Transformers documentation reports keeping up to about 96 percent of retrieval performance while using 32 times less memory.

### Why is the query kept in full precision?

There is only one query per search, so its size does not matter. Comparing a float32 query with stored int8 or binary-shortlisted documents recovers more accuracy than quantising both sides.

### Can I combine these with an HNSW index?

Yes. Truncation and quantisation shrink each vector, while HNSW and similar indexes reduce how many vectors you compare. Many systems use both, plus a cross-encoder reranker at the end.

## Summary

Embedding storage grows linearly with your corpus, and at full float32 precision it quickly reaches hundreds of gigabytes. Matryoshka training puts the most important information in the first dimensions, so vectors can be truncated with little loss. Scalar quantisation stores each value in 8 bits, and binary quantisation in 1 bit, compared with Hamming distance. Combined, they shrink a 1,024-dimension float32 vector from 4,096 bytes to 32 bytes, a 128-fold saving, and a rescoring step with the full-precision query restores most of the ranking quality. Measure on your own data, tune the truncation size and rescore multiplier, and keep a cheap index in memory with richer vectors on disk. For more, see the [embeddings](/tools/embeddings), [FAISS](/tools/faiss) and [cross-encoder reranking](/tools/cross-encoder-reranking) pages and the [RAG and grounding topic](/topics/generative-ai-llms/rag-and-grounding).

## Sources

- [arXiv: Matryoshka Representation Learning](https://arxiv.org/abs/2205.13147)
- [arXiv: Efficient Passage Retrieval with Hashing for Open-domain Question Answering (Yamada et al.)](https://arxiv.org/abs/2106.00882)
- [GitHub: Sentence Transformers Matryoshka Embeddings guide](https://github.com/huggingface/sentence-transformers/blob/master/examples/sentence_transformer/training/matryoshka/README.md)
- [GitHub: Sentence Transformers Embedding Quantization guide](https://github.com/huggingface/sentence-transformers/blob/master/examples/sentence_transformer/applications/embedding-quantization/README.md)
- [Hugging Face Blog: Introduction to Matryoshka Embedding Models](https://huggingface.co/blog/matryoshka)
- [Hugging Face Blog: Binary and Scalar Embedding Quantization](https://huggingface.co/blog/embedding-quantization)
- [PyPI: sentence-transformers release history](https://pypi.org/project/sentence-transformers/#history)
