rumblr Work in progressWIP

● The AI Primer · Lesson 27 · Part 4: embeddings and search

Making embeddings smaller

dimensions and compression: smaller vectors, same neighbours

This lesson covers How to store millions of embeddings in a fraction of the memory without losing your neighbours

Members · open during launch 23 min7 figures and diagrams7 interactive

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

  1. 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.
  2. 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.
  3. The cost of any compression is its recall@k: the share of the exact search's top k that the compressed search still finds.
  4. 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.
  5. 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.

Try each way on one vector of 16 numbers, and watch the bytes it saves and how far the vector turns.

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

384 768 1024 1536 3072 dimensions per vector 1 0 0 1 0 1 1 0 2 GB for 10 million vectors (log scale) Raw vector storage float32 int8 binary

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

Reading it: each group of bars is one common embedding size, from 384 to 3,072 dimensions, and its three bars are float32, int8 and binary storage for ten million vectors. The scale is logarithmic: each gridline is ten times the one below. At 3,072 dimensions, float32 needs over 120 GB of memory; the same vectors as bits fit in under 4 GB.

In code: storage_bytes is the sum, and hnsw_link_bytes adds the graph's links. View source

Do the sum for a collection of your own, and see which formats fit in the memory you have.

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

Reading it: one text, one encoder, one vector, scored several times. Each prefix of the vector is judged by the usual contrastive loss, and the model is trained on the sum. The model itself is unchanged; only the grading of its output is new.

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

0 50 100 150 200 250 dimension number 1 0 − 5 1 0 − 4 1 0 − 3 1 0 − 2 1 0 − 1 variance along that dimension (log scale) Where the information lives importance order (principal directions) random order

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

Reading it: the horizontal axis numbers the 256 dimensions. The vertical axis, on a log scale, is how much the collection varies along each one: its variance, the average squared distance from the mean. In importance order the first few dimensions carry most of the variation and the rest fall away, so cutting from the end loses little. In random order every dimension carries a similar share, so every cut costs about the same.

Figure 4 · Chart

4 8 16 32 64 128 256 dimensions kept (of 256) 0.0 0.2 0.4 0.6 0.8 1.0 recall@10 Truncation only works when importance comes first importance order (Matryoshka-like) random order 32 dims → shortlist 100 → re-score

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

Reading it: the horizontal axis is how many leading dimensions are kept, of 256. The vertical axis is recall@10: of each query's true 10 nearest documents, the share the shortened search still finds. In importance order, 32 dimensions (one eighth) find about 93% of them; in random order, about 44%. The star uses the first 32 numbers only to pick a shortlist of 100 candidates, then re-ranks those 100 with the full vectors, and it finds all of them.

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

Back to the four-number vector: cut it with its important numbers first, then last, and watch how far the short vector turns from the full one.

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

Step through the queries one at a time, and compare what a search on the first few numbers finds with the true 10.

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

−0.075 −0.050 −0.025 0.000 0.025 0.050 0.075 0.100 value One vector, first 40 numbers original float32 int8, decoded 0 5 10 15 20 25 30 35 40 dimension −0.0005 0.0000 0.0005 rounding error

The decoded int8 steps track the first 40 numbers of the vector almost exactly; the rounding error never exceeds half of one step

Reading it: the line is the first 40 numbers of one vector from the test collection, and the steps are the same numbers after rounding to 256 levels and decoding. The two almost coincide: the rounding error, in the bottom panel, never exceeds half a mark. Over the whole collection, int8 search finds about 98% of the true neighbours.

In code: search_int8 measures lo and hi on the documents, rounds every vector and searches the decoded ones. View source

Drag x along the ruler from the example, and watch which mark it is stored as and how far that mark is from x.

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

Flip a few numbers or bits, and watch the count of differences change.

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

Reading it: the cheap form does the big job, scanning every document, and the expensive form does the small one, ordering 100 candidates. The bits live in fast memory. The full vectors can sit somewhere slower, because only a hundred are read per query.

Figure 7 · Chart

float32 (exact) int8 binary binary → re-score 100 32 dims → re-score 100 0.0 0.2 0.4 0.6 0.8 1.0 recall@10 Crude first pass, exact second pass 1.00 0.98 0.54 0.97 1.00

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

Reading it: each bar is one way of storing the documents, scored by recall@10 against exact float32 search. int8 alone keeps about 98%, and binary alone about half. Used for a shortlist and re-scored with the full vectors, binary climbs back to about 97%, and a shortlist from the first 32 Matryoshka dimensions reaches 100%.

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

Set the length of the shortlist, and watch the second, exact look bring the neighbours back.

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

Kusupati et al., Matryoshka Representation Learning (2022)

Trained embeddings whose every prefix is a usable embedding, by summing the loss over nested prefix lengths.

Read on rumblr →The paper

Researcher'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.