What this is
What is embedding compression?
Embedding compression shrinks the lists of numbers an AI search system keeps for each text, so that millions of them fit in memory. Those lists are called embeddings: texts with similar meanings get similar lists, and a search returns the closest ones. Ten million lists of 1,536 numbers take 61 GB, and a fast search holds all of it in memory. A list can be made smaller by keeping only its first numbers, by rounding each number, or by keeping one bit per number. Each way is judged by how many of the true closest matches a search still finds.
Why it matters: You need it the day a search index outgrows the machine it runs on, or its memory bill outgrows the budget. Rounding each number to one byte makes each embedding four times smaller, and one bit per number makes it 32 times smaller.
At a glance
Key takeaways
- Storage is vectors × numbers per vector × bytes per number: ten million vectors of 1,536 float32 numbers take 61 GB, before the index adds its own.
- A Matryoshka model is trained to put the important information in its first numbers, so its vectors can be cut short and rescaled to length 1.
- The cost of any compression is its recall@k: the share of the exact search's top k that the compressed search still finds.
- int8 rounds each number to one of 256 levels: 4× smaller, with recall@10 of 0.98 on the test collection. Keeping only signs is 32× smaller, with recall@10 of 0.54.
- Bits make a good shortlist: re-ranking their top 100 with the full vectors brings recall@10 back to 0.97.
How it works, from scratch
A search system keeps an embedding for every document. There are three ways to make each embedding smaller: keep fewer of its numbers, store each number more roughly, or keep only whether each number is positive. Each one saves memory and moves the vector a little away from where it pointed, so a search with it misses some of the right neighbours. Even the roughest form is good enough to make a shortlist, which the full vectors then put in order.
Chapter 1
Counting bytes
A dimension is one number in the vector. A 32-bit float, the usual format, takes 4 bytes, so one vector of 1,536 dimensions takes 1,536 × 4 = 6,144 bytes. A number stored as a one-byte integer (int8) takes 8 bits, and a single bit takes 1. A collection of n vectors of d numbers, at b bits each, takes:
The formula and its symbols
Symbols
| Symbol | Meaning here | Example value |
|---|---|---|
| n | number of vectors | 10,000,000 |
| d | dimensions per vector | 1,536 |
| b | bits per number | 32 (float32), 8 (int8), 1 (binary) |
| b / 8 | bytes per number (8 bits in a byte) | 4, 1, or 1/8 |
In words: storage is the number of vectors, times the numbers in each, times the bytes per number.
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
On the example: 10,000,000 × 1,536 × 32/8 = 61,440,000,000 bytes ≈ 61 GB. As int8 it's 15.4 GB; as bits, 1.9 GB.
In Python:
n, d = 10_000_000, 1536
# float32, int8, binary
for b in (32, 8, 1):
# bytes = n × d × b/8
size = n * d * b // 8
print(b, size, round(size / 1e9, 1), "GB") # → 32 61440000000 61.4 GB 8 15360000000 15.4 GB 1 1920000000 1.9 GB
# HNSW: 2·M ids of 4 bytes each, M = 16, in GB
n * 2 * 16 * 4 / 1e9 # → 1.28
The index adds its own overhead. An HNSW graph (Vector indexes) stores about 2·M neighbour ids per vector at 4 bytes each: with M = 16 that is 10M × 32 × 4 = 1.28 GB more. Fast indexes such as HNSW keep every vector in RAM, so this sum tells you how big a machine the index needs.
Figure 1 · Chart
Ten million 3,072-dimension vectors take 123 GB as float32, 31 GB as int8 and under 4 GB as binary; smaller dimensions shrink each bar in proportion
In code: storage_bytes is the sum, and hnsw_link_bytes adds the
graph's links. View source
Chapter 2
Matryoshka embeddings: fewer numbers
The number of vectors is set by the collection, but the other two factors in the sum can shrink. The first is d, the numbers in each vector. Keep only the first m of them, rescale what is left to length 1, and the vector is d/m times smaller. Whether it still finds the right neighbours depends on what the dropped numbers held.
Take the vector (0.9, 0.4, 0.1, 0.05), whose numbers shrink in importance. Keep the first two, (0.9, 0.4), and divide by their length, √(0.81 + 0.16) = 0.985, to get (0.914, 0.406). The dropped numbers were small, so the direction barely moves: the cosine with the full, normalized vector is 0.994.
The formula and its symbols
Symbols
| Symbol | Meaning here | Shape |
|---|---|---|
| v | the full embedding | d numbers |
| m | how many leading numbers we keep | 1 to d |
| v₁ … vₘ | the first m numbers | m numbers |
| ‖·‖ | length (norm) | one number |
| v₍:ₘ₎ | the truncated, re-normalized vector | m numbers, length 1 |
In words: keep the first m numbers and rescale them to length 1.
On the example: m = 2: (0.9, 0.4) / 0.985 = (0.914, 0.406).
In Python:
import math
v = [0.9, 0.4, 0.1, 0.05]
m = 2
# (v_1, ..., v_m)
prefix = v[:m]
# ‖(v_1, ..., v_m)‖
length = math.sqrt(sum(v_i ** 2 for v_i in prefix))
round(length, 3) # → 0.985
# rescale to length 1
v_m = [v_i / length for v_i in prefix]
[round(v_i, 3) for v_i in v_m] # → [0.914, 0.406]
full = math.sqrt(sum(v_i ** 2 for v_i in v))
# cosine with the full, normalized vector
round(sum(a * b / full for a, b in zip(v_m, v)), 3) # → 0.994
Cutting works only when the important numbers come first. In a model not trained for it, the information is spread across all the numbers. A Matryoshka embedding is trained to put it first. It is named after the Russian nesting dolls: its first 64 numbers are a usable embedding, its first 256 a better one, and the full vector the best. Training applies the usual contrastive loss (Training embedding models) to several prefixes at once (the first 64, 128, 256, … numbers) and adds the losses up, so each prefix must work on its own.
Figure 2 · Diagram
flowchart LR T[Text] --> E[Encoder] --> V["full vector (d numbers)"] V --> P64["first 64"] --> L64[loss] V --> P256["first 256"] --> L256[loss] V --> PD["all d"] --> LD[loss] L64 & L256 & LD --> S["sum: every prefix<br/>must work on its own"]
The charts that follow measure this on a made-up test collection: 5,000 documents and 100 queries, each a vector of 256 numbers, with every query's true 10 nearest documents found by an exact search. Instead of training a model, the vectors are rotated onto their principal directions, the directions along which the collection varies most (found with the SVD; see Math notation, from zero). That puts the most informative number first, as a Matryoshka model would. The control is the same vectors in a random order.
Figure 3 · Chart
In importance order variance drops steeply, the first 16 of 256 dimensions holding 96% of it; in random order it stays in a narrow band with no standouts
Figure 4 · Chart
Keeping 32 of 256 dimensions finds 93% of true top-10 neighbours in importance order but 44% in random order; re-ranking a 100 shortlist finds all
In code: matryoshka_order puts the principal directions first,
random_order is the control, and search_truncated searches with the first
m numbers. View source
Chapter 3
Measuring the cost: recall@k
Each Matryoshka cut was scored by how many of the true neighbours it still found. That score is recall@k, and every method from here on is measured with it. An exact search with the full vectors gives each query's true top k. The compressed search gives its own top k. Recall@k is the share of the true ones that the compressed search also found:
The formula and its symbols
Symbols
| Symbol | Meaning here | Example |
|---|---|---|
| k | how many results we look at | 10 in this lesson; 3 in the example |
| foundₖ | the k results the compressed search returned | (3, 4, 1) |
| trueₖ | the k results an exact, full-precision search returns | (1, 2, 3) |
| ∩ | "items in both" | {1, 3} |
| |·| | count the items | 2 |
In words: the share of the true top k that the compressed search also found.
On an example: true (1, 2, 3), found (3, 4, 1): two of the three appear, so recall@3 = 2/3 ≈ 0.67.
In Python:
true_k = {1, 2, 3}
found_k = {3, 4, 1}
k = 3
# ∩: the items in both
found_k & true_k # → {1, 3}
# |found ∩ true| / k
round(len(found_k & true_k) / k, 2) # → 0.67
To judge a compression for your own index, run both searches on a sample of your own queries.
In code: recall_at_k averages this share over every query, and
make_corpus builds the test collection. View source
Chapter 4
Scalar quantization: one byte per number
Matryoshka shrinks d. Scalar quantization keeps every number and shrinks b, the bits each one takes, from 32 to 8. Each number is rounded to one of 256 marks on a ruler that runs from the smallest to the largest value seen in its dimension across the documents. One byte can number 256 marks, so the mark is stored as a one-byte integer (int8), a quarter of a float's 4 bytes.
Take a dimension whose values run from lo = −1 to hi = 1. Its 256 marks are 2/255 = 0.00784 apart. The value 0 sits at (0 − (−1)) / 2 × 255 = 127.5 marks, rounds to mark 128, and decodes back to −1 + 128/255 × 2 = 0.00392. That is off by 0.00392, half a mark, the most rounding can be off.
The formula and its symbols
Symbols
| Symbol | Meaning here | Range |
|---|---|---|
| x | one number in a vector | between lo and hi (clipped if outside) |
| lo, hi | smallest and largest value of this dimension across the documents | calibrated once |
| (x − lo)/(hi − lo) | where x sits between lo and hi, as a fraction | 0 to 1 |
| × 255 | stretch to the 256 marks 0 … 255 | 0 to 255 |
| round | nearest whole number | |
| code | the stored byte | 0 to 255 |
| x̂ (x-hat) | the value decoded back | within half a mark of x |
In words: find where x sits between the dimension's minimum and maximum, turn that into one of 256 whole-number marks, and store the mark; to decode, walk back from the mark to the value.
On the example: x = 0, lo = −1, hi = 1: code = round(0.5 × 255) = round(127.5) = 128; x̂ = −1 + (128/255)·2 = 0.00392.
In Python:
x, lo, hi = 0, -1, 1
# round(127.5): ties go to the even mark
code = round((x - lo) / (hi - lo) * 255)
code # → 128
# decode: walk back from the mark
x_hat = lo + code / 255 * (hi - lo)
round(x_hat, 5) # → 0.00392
Figure 5 · Chart
The decoded int8 steps track the first 40 numbers of the vector almost exactly; the rounding error never exceeds half of one step
In code: search_int8 measures lo and hi on the documents, rounds every
vector and searches the decoded ones. View source
Chapter 5
Binary quantization: one bit per number
int8 still spends 8 bits on each number. The roughest form spends one.
Signs and the Hamming distance
Binary quantization keeps a single bit for each number: 1 if the number is positive, 0 if not. Two vectors are then compared by their Hamming distance, the number of positions where their bits differ.
The eight values (0.3, −0.2, 0.0, 5, −1, 2, −3, 0.1) become the bits 1 0 0 1 0 1 0 1, packed into one byte: 0b10010101 = 149. Compare it with 0b00010100: they differ in the first and last positions, so the Hamming distance is 2.
The formula and its symbols
Symbols
| Symbol | Meaning here | Range |
|---|---|---|
| xᵢ | the i-th number of the vector | any real number |
| [ condition ] | 1 if the condition is true, 0 if not | 0 or 1 |
| bitᵢ | the stored bit for position i | 0 or 1 |
| a, b | two bit codes being compared | d bits each |
| aᵢ ≠ bᵢ | the two codes disagree at position i | |
| Σ | add up over all d positions | |
| hamming(a, b) | number of positions that disagree | 0 to d |
In words: keep one bit per number that says whether it was positive, and measure distance as the number of positions where two codes disagree.
On the example: 149 = 10010101 vs 20 = 00010100: positions 1 and 8 differ, so the distance is 2. A computer does this with one XOR, which marks the differing bits, and one popcount, which counts them. That is why a search over bits is fast.
In Python:
x = [0.3, -0.2, 0.0, 5, -1, 2, -3, 0.1]
# bit_i = [x_i > 0]
a = [int(x_i > 0) for x_i in x]
a # → [1, 0, 0, 1, 0, 1, 0, 1]
# packed into one byte
int("".join(map(str, a)), 2) # → 149
# 0b00010100 = 20
b = [0, 0, 0, 1, 0, 1, 0, 0]
# hamming(a, b) = Σ [a_i ≠ b_i]
sum(a_i != b_i for a_i, b_i in zip(a, b)) # → 2
# the computer's way: XOR, then count the 1s
bin(149 ^ 20).count("1") # → 2
In code: binary_quantize packs the signs 8 to a byte, and
hamming_distances counts the differing bits. View source
Shortlist, then re-score
Bits alone rank poorly: on the test collection, a search by Hamming distance finds 54% of the true top 10. They are good enough to find candidates, though. A search can scan every document's bits for a shortlist of 100, then re-rank only those 100 with the full float vectors. That brings recall back to 97%, while reading only 100 full vectors per query.
Figure 6 · Diagram
flowchart LR
Q[Query] --> B["Stage 1: bits + Hamming<br/>scan all 5,000 docs<br/>(32× smaller, very fast)"]
B --> S[Shortlist of 100]
S --> F["Stage 2: full float vectors<br/>exact dot product on 100 only"]
F --> T[Top 10]
STORE[("bits for every doc (RAM)<br/>floats for every doc (disk or RAM)")] --> B
STORE --> F
Figure 7 · Chart
Recall@10: int8 keeps 0.98 and binary alone only 0.54, but binary re-scored over 100 candidates recovers 0.97 and a 32-dimension shortlist reaches 1.00
In code: search_binary_then_rescore shortlists by Hamming distance and
re-ranks with the full vectors; search_truncated_then_rescore does the same
with the first m numbers. View source
Test yourself
4 questions
Answer each one out loud or on paper before you open it.
Question 1Q: How much memory do ten million 1,536-dimension float32 vectors need?Think it through, then reveal
10,000,000 × 1,536 × 4 bytes = 61.4 GB of raw vectors, plus index overhead (e.g. ~1.3 GB of HNSW links at M = 16).
Question 2Q: What makes Matryoshka embeddings truncatable, and how do you use that?Think it through, then reveal
They're trained with the loss applied to several prefixes at once, so the first m numbers form a good embedding by themselves. Search with short vectors for speed and memory, then re-score the top candidates with the full vectors.
Question 3Q: Scalar vs. binary quantization: what do you give up?Think it through, then reveal
int8 rounds each number to 256 levels, 4× smaller with a small recall loss. Binary keeps only signs, 32× smaller, but recall drops a lot on its own; it works as a first-stage shortlist followed by full-precision re-scoring.
Question 4Q: Why not just use as many dimensions as possible?Think it through, then reveal
Gains flatten out while storage, memory and search time grow linearly. A smaller model trained for your domain often beats a bigger generic one, so benchmark on your own queries.
Primary sources
The papers behind this lesson
Trained embeddings whose every prefix is a usable embedding, by summing the loss over nested prefix lengths.
Read on rumblr →The paperResearcher's shelf
Further reading
- Hugging Face, Embedding Quantization (binary and int8 with re-scoring): https://huggingface.co/blog/embedding-quantization
- Hugging Face, Introduction to Matryoshka Embedding Models: https://huggingface.co/blog/matryoshka
- Faiss wiki, Guidelines to choose an index: https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index
About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.