HAMZA KAREEM / CONCEPTS hamzawi.dev

Lesson 1342 min read

Matryoshka Embeddings

Chop the Vector, Keep the Meaning

AI engineeringAI engineering / embeddings & retrieval

Build it in 5 lines

full  = embed(docs)            # (N, 3072) text-embedding-3-large
small = full[:, :256]          # 1) just slice it
small /= np.linalg.norm(small, axis=1, keepdims=True)   # 2) renormalize
cand  = (small @ q_small).argsort()[-100:]               # 3) cheap shortlist
best  = cand[(full[cand] @ q_full).argsort()[-10:]]      # 4) rescore full-dim

Line 5 is the one you don't write: no retraining, no new index type.

What each line teaches

1️⃣ The slice is only legal for some models.

Normally embedding dims are an unordered soup — dim 7 is no more important than dim 2000, so truncating destroys the vector. Matryoshka Representation Learning changes the loss: during training the model is scored on cosine loss at 64, 128, 256, 512, 1024… dims simultaneously. That forces an importance ordering — the first 256 dims must work as a standalone embedding. Nesting dolls.

2️⃣ Renormalize or your scores quietly lie.

Chopping dims shortens the vector, so ‖v‖ < 1. If your store assumes unit vectors (dot product == cosine), you've just introduced a length bias that favors whichever docs happened to keep more magnitude in the first 256 dims. One line. Most commonly skipped one.

3️⃣4️⃣ Adaptive retrieval.

Shortlist wide and cheap at 256 dims, rescore ~100 survivors at 3072. You pay full-dim accuracy only on 100 vectors instead of 1,000,000.

The numbers that justify it

  • 1M × 3072 dims × 4 bytes = 12.3 GB → at 256 dims = 1.0 GB. That's "fits in RAM" vs "disk-backed index."
  • Scoring is linear in dims: ~12x fewer multiply-adds per comparison.
  • Rescoring 100 candidates full-dim ≈ 0.3 ms. Recall@10 typically lands within ~1% of pure full-dim search.

Where people get burned

  • Not every model is Matryoshka-trained. text-embedding-3-small/large, nomic-embed-text, Snowflake arctic-embed and several sentence-transformers are. ada-002 and plain BERT mean-pooling are NOT — truncate those and recall falls off a cliff. Read the model card before you slice.
  • Mixed dimensions = garbage, not degraded. Docs stored at 256 and a query embedded at 3072 is not "slightly worse," it's meaningless. Pin the dimension in your index metadata.
  • OpenAI's dimensions=256 param does slice+renormalize server-side — convenient, but it also means you can't later recover the full vector without re-embedding. If storage allows, store full and truncate at read time.
  • Truncation ≠ quantization; they compose. 256 dims + int8 ≈ 48x smaller than 3072 × fp32. Do truncation first, measure, then quantize.
  • The knee is corpus-dependent. 64 dims is usually too lossy on large fine-grained corpora (think 500k near-duplicate support tickets), while 256 is often indistinguishable from full on a 10k-doc knowledge base.

Your exercise

Take ~5k docs. Embed at full dims and treat full-dim search as ground truth. Measure recall@10 for truncation at 64 / 128 / 256 / 512 and plot it — find your knee. Then bolt on the step-4 rescore and see how much of the lost recall you buy back for 0.3 ms.

Guess before you run it: at which dimension does recall@10 first drop below 95%?