Truncate Matryoshka embeddings and renormalise
Why it matters OpenAI and Nomic embedding APIs let you request shorter vectors exactly this way to cut vector DB cost.
Matryoshka embeddings are trained so the first m dimensions are a usable smaller embedding.
Write mrl_truncate(E, m). E is (n, d). Keep the first m columns and L2-normalise each row again. Leave all-zero rows as zeros.
def mrl_truncate(E, m)Example
mrl_truncate([[3, 4, 12]], 2) is [[0.6, 0.8]].
Understand the idea
Matryoshka embeddings are trained so that the first few dimensions already form a good, smaller embedding, like nested dolls where each smaller doll is still a complete doll. You can cut a 1024-dimension vector down to 256 to save memory and search time. After cutting, the vector is no longer unit length, so you normalise it again for cosine similarity. Worked example: row [1, 2, 2, 4], m = 3. Keep [1, 2, 2]. Its length is sqrt(1 + 4 + 4) = 3, so the result is [0.333, 0.667, 0.667]. A row of all zeros has length 0 and must stay all zeros instead of becoming NaN. Rule: take E[:, :m] (the leading columns, never the trailing ones), compute each row's L2 norm, divide rows by their norm where the norm is above 0, and leave zero rows untouched. Used in: OpenAI style and open embedding models that offer shorter vector sizes, and RAG systems that do a fast first pass on short vectors then rerank with full ones.