Skip to content
AgenticAIWiki
  1. Learn
  2. Part 1
  3. 4. Embeddings and semantic search
  4. 4.10

Lesson 4.10 · 10 of 10 · 6 min read · Reviewed 24 Nov 2026

L2 distance, normalisation and Matryoshka embeddings

By the end, you can

  • Relate L2 distance to cosine similarity for normalised vectors.
  • Normalise vectors correctly and match the index metric to the model.
  • Shorten Matryoshka embeddings safely.

Lesson 4.2 introduced cosine, dot product and distance. This lesson is about the mechanics you meet when you build an index: which metric to set, when to normalise, and how to shorten vectors without breaking search.

L2 distance

L2 distance (Euclidean distance) is the length of the straight line between two points:

L2(a, b) = sqrt( (a1 - b1)^2 + (a2 - b2)^2 + ... + (an - bn)^2 )

Unlike cosine, smaller is better: 0 means identical. Many vector databasesVector database: A database built to store embeddings and find the nearest ones to a query quickly. call this metric l2 or euclidean, and some store the squared value to skip the square root.

Why normalised vectors make the choice easy

Normalising means dividing a vector by its own length so the new length is exactly 1:

v = [3, 4]          length = sqrt(9 + 16) = 5
v / 5 = [0.6, 0.8]  length = 1

For two unit-length vectors there is a neat identity:

L2(a, b)^2 = 2 - 2 x cos(a, b)

So when everything is normalised, ranking by smallest L2, by largest cosine and by largest dot product all give the same order. Only the numbers differ.

cos(a, b) dot(a, b) L2 squared L2
1.00 1.00 0.00 0.00
0.90 0.90 0.20 0.45
0.50 0.50 1.00 1.00
0.00 0.00 2.00 1.41

When vectors are not normalised, the three disagree. A long vector can be far away in L2 yet have a large dot product with everything.

Where it goes wrong

The bug is almost always a mismatch between the model, the stored vectors and the index metric:

Mistake Symptom
Model trained for cosine, index set to dot product, vectors not normalised Long or repetitive chunks top every query
Documents normalised, queries not Scores shift by a constant per query; thresholds break
Index set to L2, but you sort results by “highest score” Results come back in reverse order

The fix is a rule you can test: normalise at write time and at query time (or let the database do both), and choose the metric the model’s docs recommend.

Matryoshka embeddings

Lesson 4.5 mentioned that some models are trained so the first numbers of a vector carry the most meaning, like Russian nesting dolls. Matryoshka representation learningMatryoshka embeddings: Embeddings trained so that their first dimensions carry the most meaning, letting you truncate them to save space. trains the model with a loss at several prefix lengths at once (say 64, 128, 256, 512 and 1,024), so every prefix is a usable embeddingEmbedding: A list of numbers (a vector) that represents the meaning of a piece of text, so similar meanings land close together. by itself.

The catch: the full vector was normalised, but a prefix is not. Cutting [0.6, 0.0, 0.8, 0.0] to its first two numbers gives [0.6, 0.0], with length 0.6. Divide by 0.6 again before you store or compare it.

A worked example

You index 10 million chunksChunking: Splitting documents into smaller passages before embedding and indexing them. with a 1,024-dimension Matryoshka model at float32.

Setup Storage (raw vectors) Use
Full 1,024 numbers about 41 GB Precise, but heavy
First 256, re-normalised about 10 GB First-stage search, 4x smaller
Search with 256, re-rank top 100 with 1,024 about 10 GB in memory, full vectors on disk Most of the quality at a quarter of the memory

Measure recall on your own query set at each length before choosing. The quality loss from cutting is usually small for Matryoshka models and large for ordinary ones.

Common mistakes

  • Cutting a model that wasn’t trained for it. Ordinary embeddings spread meaning across all numbers; a prefix loses it unpredictably.
  • Normalising twice in different ways. Pick one place (your code or the database) and test it.
  • Comparing L2 scores across models. Like cosine scores (4.2), distances only mean something within one model.

Key points

  • L2 (Euclidean) distance is the straight-line gap between two points. Smaller means more similar.
  • For unit-length vectors, squared L2 distance equals 2 minus 2 times the cosine, so both give the same ranking.
  • Normalise once at write time and once at query time, and set the index metric to what the model was trained for.
  • Matryoshka embeddings can be cut to their first numbers, but you must re-normalise after cutting.
Hands-on labRuns in the Playground

Truncate and re-normalise Matryoshka vectors

Check that L2, cosine and dot product agree on unit vectors, and that cut vectors only behave after re-normalising.

You will have: A script that ranks documents with full and shortened vectors and reports vector lengths and whether rankings match.

Steps

  1. Run the starter: it prints the full-length ranking and the length of each vector.
  2. Fill in truncate(): keep the first d numbers.
  3. Rank with the cut vectors by dot product and print the query's new length.
  4. Fill in unit() and re-normalise after cutting; confirm the length is 1.00 again.
  5. Check that L2 and dot product rankings match after re-normalising.

Done when

  • The cut query has a length below 1 before re-normalising.
  • After re-normalising, every length prints 1.00.
  • The script prints 'L2 and dot agree: True'.

Open in the Playground No API key needed.

Starter code (Python)
import math
def length(a): return math.sqrt(sum(x * x for x in a))
def unit(a):
    return a  # TODO: divide every number by length(a)
def dot(a, b): return sum(x * y for x, y in zip(a, b))
def l2(a, b): return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))

# Toy Matryoshka-style vectors: early numbers carry most of the meaning.
RAW = {"query": [0.7, 0.5, 0.3, 0.2, 0.2, 0.15, 0.1, 0.1],
       "A": [0.68, 0.48, 0.35, 0.15, 0.25, 0.1, 0.12, 0.05],
       "B": [0.6, -0.2, 0.5, 0.4, 0.1, 0.3, 0.2, 0.2],
       "C": [0.1, 0.1, -0.6, 0.5, 0.4, 0.3, 0.3, 0.2]}
FULL = {k: [x / length(v) for x in v] for k, v in RAW.items()}

def truncate(v, d):
    return v  # TODO: keep only the first d numbers

def rank(vecs, metric):
    q = vecs["query"]
    docs = [k for k in vecs if k != "query"]
    if metric == "dot":
        return sorted(docs, key=lambda k: -dot(q, vecs[k]))
    return sorted(docs, key=lambda k: l2(q, vecs[k]))

print("full:", rank(FULL, "dot"))
cut = {k: truncate(v, 3) for k, v in FULL.items()}
print("cut query length:", round(length(cut["query"]), 2))
# TODO: re-normalise the cut vectors with unit(), print lengths, and compare rank(..., "dot") with rank(..., "l2")
Show a solution
import math
def length(a): return math.sqrt(sum(x * x for x in a))
def unit(a):
    n = length(a)
    return [x / n for x in a] if n else a
def dot(a, b): return sum(x * y for x, y in zip(a, b))
def l2(a, b): return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))

RAW = {"query": [0.7, 0.5, 0.3, 0.2, 0.2, 0.15, 0.1, 0.1],
       "A": [0.68, 0.48, 0.35, 0.15, 0.25, 0.1, 0.12, 0.05],
       "B": [0.6, -0.2, 0.5, 0.4, 0.1, 0.3, 0.2, 0.2],
       "C": [0.1, 0.1, -0.6, 0.5, 0.4, 0.3, 0.3, 0.2]}
FULL = {k: unit(v) for k, v in RAW.items()}

def truncate(v, d):
    return v[:d]

def rank(vecs, metric):
    q = vecs["query"]
    docs = [k for k in vecs if k != "query"]
    if metric == "dot":
        return sorted(docs, key=lambda k: -dot(q, vecs[k]))
    return sorted(docs, key=lambda k: l2(q, vecs[k]))

print("full:", rank(FULL, "dot"), "agree:", rank(FULL, "dot") == rank(FULL, "l2"))
cut = {k: truncate(v, 3) for k, v in FULL.items()}
print("cut query length:", round(length(cut["query"]), 2))
fixed = {k: unit(v) for k, v in cut.items()}
print("lengths after re-normalising:", {k: f"{length(v):.2f}" for k, v in fixed.items()})
print("cut + renormalised:", rank(fixed, "dot"))
print("L2 and dot agree:", rank(fixed, "dot") == rank(fixed, "l2"))
Quick checkYou keep the first 256 numbers of a 1,024-number Matryoshka embedding and store them in a dot-product index. What else must you do?
How sure are you?
Pick an answer and how sure you are

Finished the chapter? Take the chapter check.