02.3 Embeddings

Understand LLMsLesson 3 of 1017,519 words10 parts
Module 02 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

A neural network can only do arithmetic, so before an LLM can do anything with your text it must turn every token into a list of numbers. That list is called an embedding, and it's one of the most useful ideas in AI engineering. Inside an LLM, embeddings are the model's first step. Outside it, as standalone embedding models, they power semantic search, recommendations, deduplication, classification and every RAG system you'll build. This lesson explains what embeddings are, where they come from, how to compare them, how to get them locally and from each major provider, how to choose a model, and where embeddings quietly fail.

What you'll learn

  • How token IDs become vectors through the embedding matrix, a learned lookup table, and how much of a model it takes up
  • Why similar meanings end up as nearby vectors, why there are hundreds or thousands of dimensions, and why you can't read meaning off a single dimension
  • One-hot vectors vs dense vectors, word2vec, and the famous "king − man + woman ≈ queen" analogy, including its honest caveats
  • Static vs contextual embeddings: why "bank" (river) and "bank" (money) end up as different vectors inside a transformer
  • The three similarity measures (dot product, cosine similarity, Euclidean distance), normalization, and how to read similarity scores
  • How sentence and document embeddings are made (pooling), and why dedicated embedding models differ from chat LLMs
  • How to get embeddings locally (sentence-transformers) and from OpenAI, Gemini, Voyage AI (Anthropic's recommendation) and OpenRouter
  • How to choose an embedding model, and why vectors from different models are never interchangeable
  • What embeddings are used for, how to visualize them, and advanced topics: Matryoshka truncation, int8 and binary quantization, query vs document embeddings, multimodal embeddings, drift, privacy and the limits of embeddings

What you don't need

  • Linear algebra. You need to know that a vector is a list of numbers and that a dot product means "multiply matching items and add them up" (lesson 01, 2.3). Everything else is explained in plain English.
  • API keys for most of the lesson. Every demo except the provider samples in Part 6 runs locally and for free on a CPU laptop.
  • Vector databases. Storing and searching millions of vectors is the subject of Module 06. This lesson gives you the foundation it builds on.

Setup

The local demos need Python 3.11+, NumPy, PyTorch, Hugging Face Transformers and sentence-transformers. The first run downloads a few small models from Hugging Face (gpt2 about 550 MB, bert-base-uncased about 440 MB, and a handful of sentence-transformers models between 90 and 480 MB).

bash
uv add numpy torch transformers sentence-transformers
# or: pip install numpy torch transformers sentence-transformers

First time? Create a project with uv init llm-basics && cd llm-basics, then run scripts with uv run python file.py. The outputs in this lesson were produced with PyTorch 2.15.0, Transformers 5.22.1 and sentence-transformers 6.2.0. Transformers 5.x is a recent major version, so a newer major release may rename things again; if a sample fails after an upgrade, check its changelog.

The provider samples in Part 6 need the official SDKs and python-dotenv:

bash
uv add openai google-genai voyageai python-dotenv
# or: pip install openai google-genai voyageai python-dotenv

The provider samples were checked against openai 3.x and google-genai 2.x as of November 2026 (Module 03 gives the exact releases). An unversioned install gives you the newest release, and google-genai 3.x changes its default Gemini API version and HTTP library (03.1, 4.5), so if a sample does not match, check the SDK's changelog.

Put the keys you have in a .env file in your project folder, and never commit that file:

bash
OPENAI_API_KEY=...
GEMINI_API_KEY=...
VOYAGE_API_KEY=...       # Anthropic has no embeddings API; it recommends Voyage AI (see 6.4)
OPENROUTER_API_KEY=...

What you must be able to do after this lesson#

  • Explain how token IDs become vectors
  • Describe meaning as geometry in embedding space
  • Compute cosine similarity between two embeddings
  • Call a provider embedding API
  • Choose an embedding model for a task
  • Name the main uses of embeddings

Why this matters for an AI engineer#

Embeddings show up in almost every AI product you'll build, often in places where a wrong assumption causes silent failures rather than errors:

You'll hear... You'll understand it after...
"The model has a 4,096-dimensional hidden size." 1.4 The embedding matrix and 2.3 Why so many dimensions?
"A bigger vocabulary adds hundreds of millions of parameters." 1.5 Embeddings and model size
"Search by meaning, not keywords." Part 2: Meaning as geometry and 5.6 Mini semantic search
"Should we use cosine similarity or dot product?" 4.5 Which measure should you use?
"What similarity threshold counts as a match?" 4.6 Reading similarity scores
"Can't we just get embeddings from Claude?" 6.4 Anthropic: no embeddings API
"We switched embedding models and search broke." 7.5 Vectors from different models are not compatible
"Which embedding model is best? Check MTEB." 7.4 The MTEB leaderboard
"Cut the vectors to 256 dimensions to save storage." 10.1 Matryoshka embeddings
"Search returns the opposite of what the user asked for." 10.6 The limits of embeddings
"Embeddings are anonymized, so they're safe to share." 10.7 Embeddings and privacy
"Embed the documents, retrieve the top 5, give them to the LLM." 8.4 The foundation of RAG

Part 1: From token IDs to vectors#

1.1 The problem: IDs are bad numbers#

In lesson 02 you saw that a tokenizer turns text into a list of integer token IDs. With GPT-2's tokenizer, "The cat sat" becomes [464, 3797, 3332].

These are numbers, so why not feed them straight into the network? Because an ID is just a position in a list, like a seat number in a stadium. It carries no meaning:

  • ID 3797 (" cat") and ID 3798 are neighbours in the list, but the tokens have nothing to do with each other.
  • " cat" (3797) and " kitten" are closely related, but their IDs are far apart.
  • A neuron multiplies its inputs by weights (lesson 01, 2.2). Multiplying "3797" by a weight would treat " cat" as roughly twice as much of something as token 1,900, which is meaningless.

The network needs a representation where the numbers themselves carry meaning. That's what an embedding is.

1.2 First attempt: one-hot vectors#

The classic fix is one-hot encoding. Give each vocabulary item its own slot in a long vector, set that slot to 1 and every other slot to 0. With a 5-word vocabulary, "cat" is [1, 0, 0, 0, 0] and "kitten" is [0, 0, 1, 0, 0].

One-hot vectors solve the "fake ordering" problem, since no token is "bigger" than another, but they create two new ones:

  1. They're enormous. A vocabulary of 50,000 tokens needs 50,000-number vectors, almost all zeros. Modern LLM vocabularies have roughly 32,000–262,000 tokens, with most recent models above 100,000.
  2. Every word is equally unrelated to every other word. The dot product of any two different one-hot vectors is 0. "Cat" is exactly as similar to "kitten" as it is to "truck".

Dense vectors fix both. Instead of one slot per word, every word gets a short list of numbers (hundreds, not tens of thousands), and every number is used. Related words can then share similar values. Here's the difference in miniature, with a hand-made 3-number embedding:

python
import numpy as np

vocab = ["cat", "dog", "kitten", "car", "truck"]

# One-hot: one slot per word, a single 1, everything else 0
one_hot = np.eye(len(vocab))
print("one-hot 'cat'   :", one_hot[0])
print("one-hot 'kitten':", one_hot[2])
print("cat · kitten =", one_hot[0] @ one_hot[2], "  cat · car =", one_hot[0] @ one_hot[3])

# Dense embeddings: a small table of numbers per word (hand-made here; learned in real models)
#                  [animal, small/young, vehicle]
E = np.array([
    [0.9, 0.3, 0.0],   # cat
    [0.9, 0.1, 0.0],   # dog
    [0.8, 0.9, 0.0],   # kitten
    [0.0, 0.2, 0.9],   # car
    [0.0, 0.0, 1.0],   # truck
])
print("\ndense 'cat'   :", E[0])
print("cat · kitten =", round(E[0] @ E[2], 2), "  cat · car =", round(E[0] @ E[3], 2))

# An embedding lookup is the same as multiplying a one-hot vector by the matrix
print("\none_hot[cat] @ E :", one_hot[0] @ E)
print("E[cat]           :", E[0])
Output9 lines
one-hot 'cat'   : [1. 0. 0. 0. 0.]
one-hot 'kitten': [0. 0. 1. 0. 0.]
cat · kitten = 0.0   cat · car = 0.0

dense 'cat'   : [0.9 0.3 0. ]
cat · kitten = 0.99   cat · car = 0.06

one_hot[cat] @ E : [0.9 0.3 0. ]
E[cat]           : [0.9 0.3 0. ]

Three things to notice:

  • With one-hot vectors, "cat" is as unrelated to "kitten" (0.0) as to "car" (0.0).
  • With dense vectors, "cat" scores 0.99 with "kitten" and only 0.06 with "car". The numbers now carry meaning.
  • The last two lines are identical. Multiplying a one-hot vector by the embedding matrix just picks out one row. So an embedding layer is mathematically a dense layer with no bias, fed one-hot inputs (lesson 01, 3.3). In practice, nobody builds the one-hot vector. Libraries simply jump to the row, which is far faster.

1.3 Dense vectors: the core idea#

An embedding is a dense vector of numbers that represents a piece of content (a token, a sentence, a document, an image) so that similar content gets similar vectors. The number of entries in the vector is its dimension (or dimensionality): GPT-2's token embeddings have 768 dimensions, and OpenAI's text-embedding-3-small returns 1,536.

You'll meet embeddings in two different roles, and it's worth separating them from the start:

Token embeddings inside an LLM Embeddings from an embedding model
What gets a vector Each token A whole text (sentence, paragraph, document), or an image
Where they live The first layer of every LLM The output of a dedicated model or API (text-embedding-3-small, gemini-embedding-2, voyage-4, all-MiniLM-L6-v2...)
Who uses them The model itself, internally You: for search, RAG, clustering, classification...
Covered in Parts 1–3 Parts 5–10

Both rest on the same idea, meaning as geometry, and the similarity maths in Part 4 applies to both.

1.4 The embedding matrix: a learned lookup table#

Every LLM starts with an embedding matrix (also called the token embedding table, or wte, "word token embeddings", in GPT-2's code). It has:

  • One row per token in the vocabulary, and
  • One column per dimension. This number is the model's hidden size (also called d_model or hidden_size), and every layer of the model works with vectors of this width.

Converting a token ID into a vector is a plain lookup: go to row number ID and read it out.

flowchart TB
    subgraph mat ["Embedding matrix: 50,257 rows × 768 columns"]
        R0["row 0: '!' → [-0.11, -0.04, 0.03, ...]"]
        R1["row 1: '"' → [0.04, -0.05, 0.05, ...]"]
        RD["..."]
        R3797["row 3797: ' cat' → [0.01, 0.04, 0.16, ...]"]
        RE["..."]
        RL["row 50256: end-of-text → [0.05, -0.03, 0.05, ...]"]
    end
    ID["token ID 3797"] -- "look up row" --> R3797
    R3797 --> VEC["the vector for ' cat'<br/>768 learned numbers"]

Let's look at a real one. GPT-2 is small (124 million parameters) and freely downloadable:

python
from transformers import AutoModel, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("gpt2")
model = AutoModel.from_pretrained("gpt2")

E = model.wte.weight                     # the token embedding matrix
print("Embedding matrix shape:", tuple(E.shape))   # (vocabulary size, dimensions)

total = sum(p.numel() for p in model.parameters())
print(f"Parameters in embedding matrix: {E.numel():,}")
print(f"Parameters in whole model:      {total:,}")
print(f"Share of the model:             {E.numel() / total:.1%}")

# Text -> token IDs -> rows of the matrix
ids = tokenizer.encode(" cat")
print("\nToken IDs for ' cat':", ids)
vector = E[ids[0]]                       # "lookup" = pick one row
print("Vector length:", vector.shape[0])
print("First 8 numbers:", vector[:8].detach().numpy().round(3))
Output8 lines
Embedding matrix shape: (50257, 768)
Parameters in embedding matrix: 38,597,376
Parameters in whole model:      124,439,808
Share of the model:             31.0%

Token IDs for ' cat': [3797]
Vector length: 768
First 8 numbers: [ 0.01   0.037  0.164 -0.219  0.029 -0.098 -0.336 -0.075]
  • The matrix is 50,257 × 768: GPT-2's vocabulary size by its hidden size.
  • The token " cat" (with a leading space, as you saw in lesson 02) is ID 3797, and its embedding is row 3797: 768 numbers that, on their own, mean nothing to a human.
  • These 38.6 million numbers are parameters, learned during training like any other weight (lesson 01, 4.1).

1.5 Embeddings and model size#

The embedding matrix contains vocabulary size × hidden size parameters. That's a simple formula with real consequences:

Model Vocabulary Hidden size Embedding parameters Share of the model
GPT-2 (small) 50,257 768 38.6 million ~31% of 124M
Qwen2.5-0.5B 151,936 896 136 million ~28% of ~494M
Llama 3.1 8B 128,256 4,096 525 million (input) + 525 million (output) ~13% of 8B

What this tells you:

  • In small models, the embedding table is a big slice of the model. That's one reason small open models with large multilingual vocabularies are bigger than you might expect.
  • In large models, it's a small slice, because the transformer layers grow much faster with hidden size than the embedding table does.
  • A bigger vocabulary costs parameters. Every extra token adds a full row. This is one of the trade-offs model designers weigh when choosing a vocabulary size (lesson 02, 3.3): more tokens means shorter token sequences (cheaper, faster), but a larger embedding table.

1.6 How the embedding matrix is learned#

Nobody decides that row 3797 should hold those particular 768 numbers. The process is the same as for every other weight (lesson 01, Part 5):

  1. Start random. At the beginning of training, every row is random noise. "Cat" is as close to "truck" as to "kitten".
  2. Train on next-token prediction. Each time a token appears in the training text, backpropagation nudges that token's row in whatever direction would have made the model's prediction slightly better.
  3. Similar usage → similar vectors. "Cat" and "kitten" appear in similar contexts ("the ___ purred", "fed the ___"). The nudges they receive are similar, so their rows drift towards each other. Over trillions of tokens, the geometry of meaning emerges on its own.

Two consequences matter in practice:

  • Rare tokens get poorly trained rows. A row only gets a meaningful training signal when its token appears in the text. (In weight-tied models such as GPT-2, every row is also nudged slightly at each step through the output layer (1.5), but for a token that never appears, that nudge only ever says "not this token", so its row ends up in a vague, generic region.) Tokens that were in the tokenizer's vocabulary but almost never in the training data therefore end up with meaningless embeddings, which is the root of the infamous "glitch tokens" (such as SolidGoldMagikarp in early GPT models) that made models behave bizarrely (lesson 02, 12.1).
  • The embedding matrix is frozen at inference, like every other parameter (lesson 01, 7.2). Row 3797 is the same for every user and every request.

1.7 Where embeddings sit inside an LLM#

Putting it together, here's the journey of your text through the first steps of an LLM:

flowchart LR
    T["Text<br/>'The cat sat'"] --> TK["Tokenizer<br/>(lesson 02)"]
    TK --> IDS["Token IDs<br/>[464, 3797, 3332]"]
    IDS --> LOOK["Embedding matrix lookup<br/>pick row 464, 3797, 3332"]
    LOOK --> V["Static token vectors<br/>3 × 768 numbers"]
    V --> TR["Transformer layers<br/>(lesson 04)"]
    TR --> C["Contextual vectors<br/>3 × 768 numbers"]
    C --> OUT["Next-token prediction<br/>(lesson 05)"]

The lookup produces one vector per token, each one ignorant of its neighbours. The transformer layers then repeatedly mix information between the vectors, so that by the end each one reflects its context (Part 3). The model also needs to know the order of the tokens. Older models such as GPT-2 and BERT add a learned position vector to each token's embedding at this point. Most modern LLMs instead inject position inside every attention layer (RoPE), so their embedding output carries no position information at all (lesson 04, Part 5).

What this means for you as an engineer:

  • When you read a model card saying "hidden size 4,096", that's the width of every vector flowing through the model, starting with the embedding table.
  • You never call the embedding matrix directly through a chat API. It's internal. When you want vectors to use in your own application, you use an embedding model (Part 5).

Part 2: Meaning as geometry#

2.1 Similar meanings, nearby vectors#

Once trained, the embedding space has a remarkable property: distance means something. Vectors for related tokens sit close together, and unrelated ones sit far apart. Days of the week cluster together, as do programming languages, countries and emotions. That's the whole reason embeddings are useful: "find things with a similar meaning" becomes "find vectors that are close", which is just arithmetic.

2.2 Try it: nearest neighbours in GPT-2#

Let's find each token's nearest neighbours in GPT-2's embedding matrix, using cosine similarity, which you'll learn properly in Part 4. For now, read it as "1.0 means pointing in the same direction, 0 means unrelated".

python
import numpy as np
from transformers import AutoModel, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("gpt2")
E = AutoModel.from_pretrained("gpt2").wte.weight.detach().numpy()
E_unit = E / np.linalg.norm(E, axis=1, keepdims=True)    # length-1 rows, so dot product = cosine

def token_id(word):
    ids = tokenizer.encode(word)
    assert len(ids) == 1, f"{word!r} is {len(ids)} tokens"
    return ids[0]

def nearest(vector, k=6, exclude=()):
    sims = E_unit @ (vector / np.linalg.norm(vector))
    best = [i for i in np.argsort(-sims) if i not in exclude][:k]
    return ", ".join(f"{tokenizer.decode([i])!r} {sims[i]:.2f}" for i in best)

for word in [" cat", " Paris", " happy", " Python", " Monday"]:
    i = token_id(word)
    print(f"{word.strip():7s} -> {nearest(E[i], exclude={i})}")

# The famous analogy, done on GPT-2's input embeddings
king, man, woman = (token_id(w) for w in [" king", " man", " woman"])
target = E[king] - E[man] + E[woman]
print("\nking - man + woman ->", nearest(target, k=5, exclude={king, man, woman}))
print("same, without excluding the inputs ->", nearest(target, k=3))
Output8 lines
cat     -> ' Cat' 0.71, ' cats' 0.69, 'Cat' 0.64, 'cat' 0.60, ' dog' 0.55, ' Cats' 0.54
Paris   -> 'Paris' 0.83, ' France' 0.63, ' French' 0.58, ' London' 0.58, 'France' 0.57, ' Copenhagen' 0.57
happy   -> 'happy' 0.70, ' Happy' 0.69, ' happier' 0.67, ' unhappy' 0.66, 'Happy' 0.66, ' pleased' 0.63
Python  -> ' python' 0.77, 'Python' 0.76, 'python' 0.70, ' Django' 0.61, ' PHP' 0.57, ' Py' 0.56
Monday  -> ' Tuesday' 0.89, ' Thursday' 0.85, ' Wednesday' 0.84, ' Friday' 0.82, ' Sunday' 0.81, ' Saturday' 0.80

king - man + woman -> ' queen' 0.71, ' princess' 0.60, ' Queen' 0.60, ' kings' 0.59, 'Queen' 0.57
same, without excluding the inputs -> ' king' 0.78, ' queen' 0.71, ' princess' 0.60

(The last two lines, the analogy, are discussed in 2.6.)

What the neighbours reveal:

  • Spelling variants come first. ' Cat', 'Cat' and 'cat' are different tokens with different rows: with or without a leading space, capitalized or not (lesson 02). The model had to learn separately that they mean nearly the same thing, and it did.
  • Then come related concepts: ' dog' near ' cat', ' France' and ' London' near ' Paris', ' Django' and ' PHP' near ' Python', every other weekday near ' Monday'.
  • Opposites can be close. ' unhappy' is one of ' happy''s nearest neighbours. Opposites appear in very similar contexts ("I feel ___ about it"), so distributional training places them near each other. Keep this in mind: it resurfaces as a real limitation in 10.6.

2.3 Why hundreds or thousands of dimensions?#

Our hand-made example used 3 dimensions. Real models use far more:

Model Dimensions
word2vec (Google News vectors, 2013) 300
all-MiniLM-L6-v2 (sentence embedding model) 384
GPT-2 small, BERT-base (token embeddings / hidden size) 768
Voyage voyage-4 (default) 1,024
OpenAI text-embedding-3-small (default) 1,536
OpenAI text-embedding-3-large, Gemini gemini-embedding-2 (default) 3,072
Llama 3.1 8B (hidden size) 4,096

Why so many? Language has an enormous number of ways in which things can be similar or different: topic, sentiment, formality, tense, language, grammatical role, domain, register, and countless subtler properties. A handful of dimensions can't keep all of them apart at once. More dimensions give the model more room to place things near each other in some respects and far apart in others.

But more isn't automatically better:

  • Diminishing returns. Past some point, extra dimensions add little quality. Gemini's documentation shows its gemini-embedding-001 model scoring 68.17 on the MTEB benchmark at 1,536 dimensions and 67.99 at 768 (10.1).
  • Real costs. Every dimension is stored, moved and multiplied for every vector. Double the dimensions and you double the storage and roughly double the comparison work (7.2).

What this means for you as an engineer: dimension count is a cost decision as much as a quality one. Don't pick the biggest by default. Test smaller sizes on your own data (7.2, 10.1).

2.4 Why you can't read meaning from one dimension#

It's tempting to imagine that dimension 17 means "is an animal" and dimension 342 means "is plural". Real embeddings almost never work that way, for two reasons:

  1. Nothing in training rewards tidy dimensions. The model only cares about predicting well. If you rotated the entire embedding space (and adjusted the next layer to match), the model would work exactly as well, but every individual dimension would now mean something different. Since every rotation works equally well, there's no reason for training to land on one where dimensions align with human concepts.
  2. Superposition. As lesson 01, 3.4 explained, networks pack more concepts than they have dimensions by giving each concept a direction, a particular mix of many dimensions, with directions overlapping slightly. Every dimension takes part in many concepts, and every concept is spread over many dimensions.

What does carry meaning is direction and relative position: which vectors are near each other, and which directions consistently separate one kind of thing from another (such as singular → plural, or male → female in the analogy below). Interpretability research finds such directions inside models, but you won't find them by staring at single numbers.

What this means for you as an engineer:

  • Never build logic on individual dimensions ("if dimension 12 > 0.5 then..."). Compare whole vectors.
  • Embeddings are opaque. You can't explain why two texts scored 0.71 by inspecting the vectors. You evaluate embedding systems by their results, which is what Module 10A is about.

2.5 A short history: from one-hot to word2vec to contextual embeddings#

Year Milestone Why it mattered
1950s–2000s One-hot vectors, bag-of-words, TF-IDF Represent documents by (weighted) word counts. TF-IDF weights words by how distinctive they are. Fast and still useful for keyword search (BM25, a classic keyword-ranking formula, Module 06), but no notion of meaning
2003 Neural language model (Bengio et al.) Learned a dense vector per word as part of predicting the next word: the embedding matrix you saw in 1.4
2013 word2vec (Mikolov et al., Google) Trained word vectors cheaply on billions of words, and showed the famous vector-arithmetic analogies
2014 GloVe (Stanford) Similar word vectors learned from word co-occurrence statistics
2018 ELMo, BERT Contextual embeddings: a word's vector depends on its sentence (Part 3)
2019 Sentence-BERT (Reimers & Gurevych) Fine-tuned BERT to produce one good vector per sentence, launching the sentence-transformers library (Part 5)
2021 CLIP (OpenAI) Put images and text in the same embedding space (10.4)
2022–now Embedding APIs and LLM-based embedding models OpenAI, Google, Voyage, Cohere and open models (E5, BGE, Qwen3-Embedding and more) offer ready-made embeddings; the MTEB benchmark compares them (Part 7)

word2vec is worth understanding because its ideas still shape how people talk about embeddings. It trained a tiny network on a simple task: given a word, predict the words around it (or the reverse). The network itself was thrown away. Only its embedding matrix was kept, and that matrix turned out to capture meaning surprisingly well. The vectors were static: one fixed vector per word, whatever the context.

2.6 Try it: king − man + woman#

word2vec became famous for vector arithmetic. Take the vector for "king", subtract "man", add "woman", and the nearest word to the result is "queen". The idea is that the direction from "man" to "woman" encodes something like "male → female", and adding it to "king" moves you to the female equivalent.

Our GPT-2 script from 2.2 tried exactly this on GPT-2's token embeddings. The last two lines of its output were:

text
king - man + woman -> ' queen' 0.71, ' princess' 0.60, ' Queen' 0.60, ' kings' 0.59, 'Queen' 0.57
same, without excluding the inputs -> ' king' 0.78, ' queen' 0.71, ' princess' 0.60

It works: ' queen' comes first. But look at the second line, because it reveals the first of several honest caveats:

  • The analogy usually excludes the input words. Without excluding them, the nearest vector to "king − man + woman" is still "king" (0.78), not "queen". The standard analogy tests always drop the input words from the candidates. That's a reasonable rule, but it makes results look cleaner than the raw geometry is.
  • It's cherry-picked. "King/queen" is the showcase example. Many other analogies fail or give mediocre answers, and success rates on analogy benchmarks are well below 100%, even for word2vec.
  • It reflects the training data, including its biases. Research in 2016 (Bolukbasi et al.) found word2vec completing "man is to computer programmer as woman is to ___" with "homemaker". Embeddings absorb stereotypes in the text they're trained on, and those biases can leak into search rankings and classifiers you build (Module 12).
  • Modern embedding models aren't designed for it. Sentence embedding models are trained to place similar texts close together, not to make arithmetic analogies work. Don't build features on vector arithmetic.

The durable lesson isn't the party trick. It's that directions in embedding space can encode consistent relationships, a property that interpretability research and techniques such as "steering" models build on.


Part 3: Static vs contextual embeddings#

Deep-dive

3.1 The problem with one vector per word#

The embedding matrix gives one fixed vector per token. That's called a static embedding. But many words have several meanings (polysemy):

  • "I deposited cash at the bank." (a financial institution)
  • "We had a picnic on the river bank." (the side of a river)

The token bank is the same in both, so its row in the embedding matrix is the same. A static vector has to be a blurry average of every meaning the word has. word2vec and GloVe had exactly this weakness.

3.2 Contextual embeddings#

Transformers fix this. The embedding lookup is only the starting point. As the vectors pass through the model's layers, each token's vector is repeatedly updated using information from the other tokens in the text, through a mechanism called attention (lesson 04, Part 2). By the final layer, the vector for bank in a sentence about money has moved to a different place from the vector for bank in a sentence about rivers.

These context-dependent vectors are called contextual embeddings (or hidden states). Every layer produces its own set. In a 12-layer model, each token has 13 versions: the input to the first layer (the looked-up embedding, plus a position vector in models like BERT and GPT-2), and one more after each layer.

Static embedding Contextual embedding
Where it comes from A row of the embedding matrix The output of a transformer layer
Depends on the surrounding text? ❌ Same vector everywhere ✅ Different in every context
Examples word2vec, GloVe, the first layer of any LLM BERT/GPT hidden states; what embedding models are built on

3.3 Try it: "bank" in four sentences#

Let's measure it. We'll use BERT (bert-base-uncased), a classic 110-million-parameter transformer, and compare the vector for bank in four sentences, first from the embedding matrix (static) and then from the model's final layer (contextual):

python
import torch
import torch.nn.functional as F
from transformers import AutoModel, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModel.from_pretrained("bert-base-uncased").eval()

sentences = [
    "I deposited my salary at the bank this morning.",      # money
    "The bank approved our mortgage application.",          # money
    "We had a picnic on the grassy bank of the river.",     # river
    "The boat drifted towards the muddy bank.",             # river
]

def bank_vectors(sentence):
    inputs = tokenizer(sentence, return_tensors="pt")
    with torch.no_grad():
        out = model(**inputs)
    position = inputs.input_ids[0].tolist().index(tokenizer.convert_tokens_to_ids("bank"))
    static = model.embeddings.word_embeddings.weight[inputs.input_ids[0, position]]   # lookup table row
    contextual = out.last_hidden_state[0, position]                                    # after all 12 layers
    return static, contextual

static, contextual = zip(*(bank_vectors(s) for s in sentences))

def table(vectors, title):
    print(title)
    for i in range(len(sentences)):
        row = [F.cosine_similarity(vectors[i], vectors[j], dim=0).item() for j in range(len(sentences))]
        print(f"  s{i+1}: " + "  ".join(f"{v:.2f}" for v in row))

table(static, "Static (lookup table) vector for 'bank', cosine between sentences:")
table(contextual, "\nContextual (final layer) vector for 'bank', cosine between sentences:")
Output11 lines
Static (lookup table) vector for 'bank', cosine between sentences:
  s1: 1.00  1.00  1.00  1.00
  s2: 1.00  1.00  1.00  1.00
  s3: 1.00  1.00  1.00  1.00
  s4: 1.00  1.00  1.00  1.00

Contextual (final layer) vector for 'bank', cosine between sentences:
  s1: 1.00  0.79  0.47  0.47
  s2: 0.79  1.00  0.38  0.40
  s3: 0.47  0.38  1.00  0.82
  s4: 0.47  0.40  0.82  1.00
  • Static: every similarity is 1.00. It's literally the same row of the table in all four sentences.
  • Contextual: the two money sentences (s1, s2) score 0.79 with each other, and the two river sentences (s3, s4) score 0.82. Across meanings, the scores drop to 0.38–0.47. The model has separated the two senses of "bank" on its own, purely from context, with no one telling it there are two meanings.

3.4 Encoders and decoders see context differently#

BERT is an encoder model: every token can look at every other token, both before and after it. GPT-style chat LLMs are decoder models: each token can only look at the tokens before it, because they generate text left to right (lesson 04, 3.1).

That difference matters for embeddings. In "The bank approved our mortgage", a decoder's vector for "bank" can't see "approved our mortgage", because those words come later. An encoder's can. That's one reason most classic embedding models (Sentence-BERT, E5, BGE, all-MiniLM-L6-v2) are built on encoders (lesson 04, 9.2). Many newer, LLM-based embedding models start from decoders and use extra training, or a vector taken at the last token (which has seen everything), to work around this (5.2). Some remove the causal mask altogether during embedding training, so every token can see the whole text (for example LLM2Vec and NV-Embed).

3.5 What this means for you as an engineer#

  • The vectors you use in applications are contextual. When you embed "bank account" with an embedding model, you get a vector for the whole phrase in context, not a dictionary average of "bank".
  • Context in, context out. The same sentence can embed differently depending on what surrounds it, which is why how you split documents into chunks affects search quality (Module 05, Module 07).
  • Internal hidden states are not a free embedding API. Every LLM computes contextual vectors, but chat APIs don't expose them, and raw hidden states from a chat model aren't trained to compare well anyway (5.3).

Part 4: Measuring similarity#

Everything useful you do with embeddings comes down to one question: how similar are these two vectors? There are three standard ways to answer it.

4.1 Dot product#

The dot product multiplies matching numbers and adds the results, the same operation a neuron performs (lesson 01, 2.3). For a = [3, 4] and b = [6, 8]: 3×6 + 4×8 = 50.

  • Large and positive when the vectors point the same way, around 0 when they're unrelated (at right angles), and negative when they point in opposite directions.
  • It's also affected by length. Doubling a vector doubles every dot product with it. So the dot product mixes up two things: direction (what the vector is about) and length (how big its numbers are).

The length of a vector (also called its norm or magnitude) is the square root of the sum of its squared numbers, Pythagoras' theorem extended to many dimensions. The length of [3, 4] is √(9 + 16) = 5.

4.2 Cosine similarity#

Cosine similarity measures only the angle between two vectors and ignores their length. In words: take the dot product, then divide by the length of each vector. The result always lies between −1 and 1:

Cosine Meaning
1 Same direction (the most similar possible)
0 At right angles (unrelated)
−1 Opposite directions

Cosine is the most common similarity measure for text embeddings, because what a text is about is captured by the direction of its vector, while length often reflects incidental things such as how common its words are.

4.3 Euclidean distance#

Euclidean distance is the straight-line distance between the tips of the two vectors, like measuring with a ruler. It's a distance, not a similarity: 0 means identical, and bigger means more different. It's sensitive to both direction and length.

4.4 Normalization: when all three agree#

Normalizing a vector means dividing it by its own length, so that its length becomes exactly 1 (a unit vector). Its direction doesn't change. Normalization has a very useful consequence: once vectors are normalized, all three measures give the same ranking:

  • Cosine similarity of normalized vectors equals their dot product (dividing by lengths of 1 changes nothing).
  • Euclidean distance becomes a simple function of cosine: for unit vectors, the squared distance equals 2 − 2 × cosine. Higher cosine means smaller distance, so the order of results is identical.

Let's verify all of this:

python
import numpy as np

a = np.array([3.0, 4.0])      # length 5
b = np.array([6.0, 8.0])      # same direction as a, twice as long
c = np.array([4.0, -3.0])     # at a right angle to a

def dot(x, y):
    return float(np.dot(x, y))

def cosine(x, y):
    return dot(x, y) / (np.linalg.norm(x) * np.linalg.norm(y))

def euclidean(x, y):
    return float(np.linalg.norm(x - y))

for name, y in [("b", b), ("c", c)]:
    print(f"a vs {name}: dot={dot(a, y):6.1f}  cosine={cosine(a, y):5.2f}  euclidean={euclidean(a, y):5.2f}")

# Normalize: divide each vector by its length so every vector has length 1
def normalize(x):
    return x / np.linalg.norm(x)

a1, b1, c1 = normalize(a), normalize(b), normalize(c)
print("\nafter normalizing:", a1, b1, c1)
for name, y in [("b", b1), ("c", c1)]:
    print(f"a vs {name}: dot={dot(a1, y):5.2f}  cosine={cosine(a1, y):5.2f}  euclidean={euclidean(a1, y):5.2f}")

# For length-1 vectors: euclidean^2 = 2 - 2 * cosine, so both give the same ranking
rng = np.random.default_rng(0)
x, y = normalize(rng.normal(size=384)), normalize(rng.normal(size=384))
print(f"\n384-dim check: euclidean^2 = {euclidean(x, y)**2:.4f}, 2 - 2*cosine = {2 - 2*cosine(x, y):.4f}")
Output8 lines
a vs b: dot=  50.0  cosine= 1.00  euclidean= 5.00
a vs c: dot=   0.0  cosine= 0.00  euclidean= 7.07

after normalizing: [0.6 0.8] [0.6 0.8] [ 0.8 -0.6]
a vs b: dot= 1.00  cosine= 1.00  euclidean= 0.00
a vs c: dot= 0.00  cosine= 0.00  euclidean= 1.41

384-dim check: euclidean^2 = 2.0161, 2 - 2*cosine = 2.0161
  • Before normalizing, a and b point in exactly the same direction (cosine 1.00), yet their Euclidean distance is 5.00 and their dot product is a large 50.0. Length is muddying the picture.
  • After normalizing, a and b become the same vector: dot 1.00, cosine 1.00, distance 0.00. All three measures now agree.
  • The last line confirms the relationship between distance and cosine on two random 384-dimensional unit vectors. Notice also that their cosine is about 0 (2 − 2 × cosine ≈ 2), as 2.3 predicted for random high-dimensional directions.

4.5 Which measure should you use?#

Measure Range Best for Watch out for
Cosine similarity −1 to 1 (higher = more similar) The safe default for text embeddings Slightly more work than the dot product if vectors aren't normalized
Dot product Any number (higher = more similar) The fastest option. Equals cosine for normalized vectors On unnormalized vectors, long vectors win regardless of meaning
Euclidean distance 0 to ∞ (lower = more similar) Some clustering algorithms and vector indexes expect it Remember to sort ascending, not descending

The practical rules:

  1. Use what the model was trained for. The model card or API docs say which measure the model's training optimized. Most text embedding models are trained with cosine similarity.
  2. Normalize once, then use the dot product. OpenAI and Voyage AI document that their embeddings are already normalized to length 1, and so are Gemini's full-size (3,072-dimension) vectors. If you're unsure, normalize them yourself when you store them, and the cheap dot product then gives you cosine similarity. Re-normalize after you truncate vectors (10.1).
  3. Let the library apply it. In sentence-transformers, model.similarity(a, b) uses the measure the model is configured for (shown by model.similarity_fn_name), so you can't accidentally use the wrong one (10.3 shows it).
  4. Configure your vector database to match. Vector databases ask you to choose a metric when you create an index (Module 06). Picking the wrong one silently degrades results.

4.6 Reading similarity scores: there is no universal threshold#

The most common beginner question is: "What similarity score counts as a match?" There's no universal answer:

  • Every model has its own scale. With all-MiniLM-L6-v2, unrelated sentences score around 0 and close paraphrases 0.6–0.9 (as you'll see in 5.5). Some other models put almost every pair of texts between 0.7 and 1.0, because their vectors all crowd into a narrow cone of directions (a known property called anisotropy). A score of 0.75 might mean "nearly identical" with one model and "barely related" with another.
  • Scores are relative, not absolute. A similarity score is useful for ranking ("this document is more relevant than that one"), not as a probability or a confidence. 0.8 doesn't mean "80% relevant".
  • Thresholds depend on the task. A deduplication threshold should be strict, while a "related articles" feature can be loose.

What this means for you as an engineer: when you need a threshold (deduplication, "no good answer found", routing), set it empirically. Collect real examples of matches and non-matches, embed them with your chosen model, look at the score distributions, and choose the cut-off that gives the trade-off you want between missed matches and false matches (Module 10A). Re-check thresholds whenever you change models.


Part 5: Sentence and document embeddings#

5.1 From token vectors to one vector per text#

For search, clustering or RAG, you need one vector per piece of text: a whole question, paragraph or document. But a transformer outputs one vector per token. A 12-token sentence gives you 12 contextual vectors. A sentence embedding (also called a text embedding or document embedding) squeezes them into a single vector that represents the meaning of the whole text.

flowchart LR
    S["Sentence"] --> TOK["Tokenizer"]
    TOK --> ENC["Transformer<br/>(usually an encoder)"]
    ENC --> TV["One contextual vector<br/>per token"]
    TV --> POOL["Pooling<br/>mean, CLS<br/>or last-token"]
    POOL --> NORM["Normalize<br/>to length 1"]
    NORM --> E["One sentence embedding<br/>e.g. 384 numbers"]

5.2 Pooling: from many token vectors to one#

Pooling is the step that combines the token vectors. Three strategies are common:

Pooling How it works Used by
Mean pooling Average all the token vectors (ignoring padding) Many sentence-transformers models, including all-MiniLM-L6-v2
CLS pooling BERT-style models add a special [CLS] token at the start; use its final vector as the summary Many BERT-based models, such as the BGE family
Last-token pooling Use the final token's vector, the only one that has seen the whole text in a decoder model (3.4) Many LLM-based embedding models, such as E5-Mistral and Qwen3-Embedding

Pooling is fixed when the model is trained, and the model is trained to make that particular pooled vector meaningful. Use the pooling the model was trained with. Libraries such as sentence-transformers read it from the model's configuration, so you rarely do it by hand. Doing it once by hand shows there's no magic, though:

python
import numpy as np
import torch
from sentence_transformers import SentenceTransformer
from transformers import AutoModel, AutoTokenizer

name = "sentence-transformers/all-MiniLM-L6-v2"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name).eval()

sentence = "Embeddings turn text into vectors."
inputs = tokenizer(sentence, return_tensors="pt")
with torch.no_grad():
    token_vectors = model(**inputs).last_hidden_state[0]      # one vector per token

print("Tokens:", tokenizer.convert_ids_to_tokens(inputs.input_ids[0]))
print("Token vectors shape:", tuple(token_vectors.shape))

mean = token_vectors.mean(dim=0)                  # mean pooling: average the token vectors
mean = mean / mean.norm()                         # then normalize to length 1
print("Pooled sentence vector shape:", tuple(mean.shape))

reference = SentenceTransformer("all-MiniLM-L6-v2").encode(sentence)
print("Matches sentence-transformers:", np.allclose(mean.numpy(), reference, atol=1e-5))
Output4 lines
Tokens: ['[CLS]', 'em', '##bed', '##ding', '##s', 'turn', 'text', 'into', 'vectors', '.', '[SEP]']
Token vectors shape: (11, 384)
Pooled sentence vector shape: (384,)
Matches sentence-transformers: True

The model produced 11 token vectors of 384 numbers each (including the special [CLS] and [SEP] tokens, and with "embeddings" split into four WordPiece tokens, lesson 02). Averaging and normalizing them gives exactly the vector sentence-transformers returns.

5.3 Dedicated embedding models vs chat LLMs#

Every LLM computes contextual vectors internally, so why not use a chat model's hidden states as embeddings? Because the training objective decides what the vectors are good at:

Chat LLM (GPT, Claude, Gemini...) Embedding model
Trained to Predict the next token, then follow instructions Place texts with similar meaning close together, and different meanings far apart
Output Generated text One vector per input
Typical size Billions to hundreds of billions of parameters Tens of millions to a few billion
Cost Priced per input and output token Priced per input token only, and usually far cheaper
Speed Slow (one forward pass per generated token) Fast (one forward pass per input)
Do provider chat APIs expose their vectors? ❌ No ✅ That's their whole purpose

A chat model's raw hidden states can be pooled into a vector, but nothing in its training made those vectors compare well with cosine similarity, and in practice they make poor sentence embeddings without further training. Conversely, an embedding model can't chat.

Many of today's best embedding models are, however, built from LLMs: a pretrained language model (often a decoder) is further trained with the embedding objective below. Google describes its Gemini embedding models as built on Gemini, and open models such as Qwen3-Embedding start from the Qwen3 LLMs. They inherit the LLM's knowledge of language, then learn to produce comparable vectors.

What this means for you as an engineer: you'll use two kinds of model side by side. A cheap, fast embedding model finds relevant content, and a chat model reads it and writes the answer. That's the architecture of RAG (8.4).

5.4 How embedding models are trained (in brief)#

Embedding models are usually trained with contrastive learning:

  1. Collect huge numbers of positive pairs: texts that should be close. Examples are a question and its accepted answer, a search query and the page users clicked, a title and its article, or a sentence and its paraphrase.
  2. For each pair, use the other examples in the batch as negatives: texts that should be further away. Some training also adds deliberately chosen hard negatives, which look similar but aren't a match (for example a passage about the same topic that doesn't answer the question).
  3. Adjust the weights so that each text's vector is closer (by cosine similarity) to its positive than to any negative.

The details belong to research, but two consequences matter to you:

  • An embedding model's idea of "similar" is whatever its training pairs taught it. A model trained on question–answer pairs is good at matching questions to answers. One trained on paraphrases is good at spotting paraphrases. This is why the right model depends on your task (Part 7).
  • Embedding models can be fine-tuned on your own pairs to fit your domain, which Module 06 touches on. It's rarely the first thing to try.

5.5 Try it: a similarity matrix#

Let's use a real embedding model. all-MiniLM-L6-v2 is a small (about 22 million parameters, 90 MB), fast, English-language model that runs comfortably on a laptop CPU. It's not the most accurate model available, but it's perfect for learning:

python
import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")   # ~90 MB download on first run

sentences = [
    "How do I reset my password?",
    "I forgot my login credentials.",
    "What is your refund policy?",
    "Can I get my money back?",
    "The weather is lovely today.",
]
emb = model.encode(sentences, normalize_embeddings=True)
print("Shape:", emb.shape)

sims = emb @ emb.T            # normalized, so dot product = cosine similarity
print("\nSimilarity matrix:")
print("     " + " ".join(f"{'s' + str(j+1):>6}" for j in range(len(sentences))))
for i, row in enumerate(sims):
    print(f"s{i+1:<4}" + " ".join(f"{v:6.2f}" for v in row))
Output9 lines
Shape: (5, 384)

Similarity matrix:
         s1     s2     s3     s4     s5
s1     1.00   0.64   0.16   0.28  -0.06
s2     0.64   1.00   0.20   0.23  -0.03
s3     0.16   0.20   1.00   0.52  -0.09
s4     0.28   0.23   0.52   1.00  -0.04
s5    -0.06  -0.03  -0.09  -0.04   1.00
  • emb @ emb.T computes every pair's similarity in one matrix multiplication, a 5 × 5 table. The diagonal is 1.00, since each sentence is identical to itself.
  • "Reset my password" ↔ "forgot my login credentials" scores 0.64, although they share no important words. That's the point of embeddings: matching meaning, not keywords.
  • "Refund policy" ↔ "money back" scores 0.52, again with no shared words.
  • The weather sentence scores around 0 with everything. Unrelated topics sit at right angles.

Semantic search finds documents by meaning: embed every document once, embed the query, and return the documents whose vectors are most similar. Here it is over ten help-centre snippets:

python
import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")

docs = [
    "To reset your password, click 'Forgot password' on the sign-in page.",
    "Refunds are issued within 14 days of receiving the returned item.",
    "We ship to over 40 countries; international delivery takes 5-10 days.",
    "Our support team is available Monday to Friday, 9am to 6pm.",
    "You can pay with a credit card, PayPal or bank transfer.",
    "Two-factor authentication adds a second step when you log in.",
    "Premium plans include priority support and unlimited projects.",
    "Delete your account from Settings > Privacy > Delete account.",
    "Invoices can be downloaded as PDF from the Billing page.",
    "The mobile app is available for iOS and Android.",
]
doc_emb = model.encode(docs, normalize_embeddings=True)       # embed once, store, reuse

def search(query, k=3):
    q = model.encode(query, normalize_embeddings=True)
    scores = doc_emb @ q                                       # cosine similarity to every doc
    top = np.argsort(-scores)[:k]
    print(f"\nQuery: {query}")
    for i in top:
        print(f"  {scores[i]:.2f}  {docs[i]}")

search("I can't remember my login")
search("how long until my parcel arrives abroad?")
search("can I get my money back")
search("is there an app for my phone")
Output19 lines
Query: I can't remember my login
  0.62  To reset your password, click 'Forgot password' on the sign-in page.
  0.47  Delete your account from Settings > Privacy > Delete account.
  0.38  Two-factor authentication adds a second step when you log in.

Query: how long until my parcel arrives abroad?
  0.68  We ship to over 40 countries; international delivery takes 5-10 days.
  0.37  Refunds are issued within 14 days of receiving the returned item.
  0.20  Invoices can be downloaded as PDF from the Billing page.

Query: can I get my money back
  0.46  Refunds are issued within 14 days of receiving the returned item.
  0.30  You can pay with a credit card, PayPal or bank transfer.
  0.25  To reset your password, click 'Forgot password' on the sign-in page.

Query: is there an app for my phone
  0.66  The mobile app is available for iOS and Android.
  0.22  You can pay with a credit card, PayPal or bank transfer.
  0.14  To reset your password, click 'Forgot password' on the sign-in page.

Every query finds the right document first, although none of them shares its key words: "parcel arrives abroad" matched "international delivery", and "app for my phone" matched "iOS and Android". A keyword search for "parcel" would have found nothing.

Notice the pattern, because it's the blueprint for every retrieval system you'll build:

  1. Index time: embed the documents once and store the vectors (doc_emb).
  2. Query time: embed the query with the same model, compare it with the stored vectors, and take the top k.

Here, "compare with every stored vector" is a single matrix multiplication, which is fine for ten documents or even a hundred thousand. For millions, you need a vector database with an approximate nearest-neighbour (ANN) index, a data structure that finds nearly the closest vectors without comparing against every one, which is Module 06's job.

5.7 Maximum input length and silent truncation#

Every embedding model has a maximum input length in tokens. Anything beyond it is usually cut off silently, with no error:

python
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")
print("Max tokens the model reads:", model.max_seq_length)

intro = "This document is about our holiday policy. " * 60       # ~490 tokens of filler
doc = intro + "Important: the office is closed on 25 December."
short = "Important: the office is closed on 25 December."

q, d, s = model.encode(["When is the office closed?", doc, short], normalize_embeddings=True)
print(f"Tokens in long document: {len(model.tokenizer(doc).input_ids)}")
print(f"Query vs long document : {float(q @ d):.2f}   (the key sentence was cut off)")
print(f"Query vs key sentence  : {float(q @ s):.2f}")
Output4 lines
Max tokens the model reads: 256
Tokens in long document: 492
Query vs long document : 0.06   (the key sentence was cut off)
Query vs key sentence  : 0.76

The model reads only the first 256 tokens. The answer sat at token ~480, so the document's vector knows nothing about it, and the search scores it 0.06. The same sentence on its own scores 0.76.

Limits vary widely (as of October 2026): 256 tokens for all-MiniLM-L6-v2, 2,048 for Gemini's gemini-embedding-001, 8,192 for OpenAI's embedding models and gemini-embedding-2, and 32,000 for Voyage's current models. Behaviour on over-long input differs too: local sentence-transformers models truncate silently, OpenAI rejects over-long input with an error, and Voyage truncates by default (truncation=True) but can be told to raise an error instead.

What this means for you as an engineer: know your model's limit, count tokens before embedding (lesson 02, 12.6), and chunk long content deliberately rather than letting the model truncate it for you.


Part 6: Provider embedding APIs#

Every major provider's embedding API works the same way: send one or more texts, get back one vector per text, and pay per input token. The differences are in the models, the options and some important gotchas.

6.1 Overview#

As of October 2026 (check each provider's documentation for current models; links in Further resources):

Provider Embeddings API? Current models Default dimensions Max input (tokens) Shorter vectors Query vs document hint
OpenAI ✅ text-embedding-3-small, text-embedding-3-large (text-embedding-ada-002 is older) 1,536 / 3,072 8,192 dimensions ❌ None
Google Gemini ✅ gemini-embedding-2 (text, images, video, audio, PDF), gemini-embedding-001 (text) 3,072 8,192 / 2,048 output_dimensionality (128–3,072) task_type (001) or a task prefix in the text (2)
Anthropic ❌ No embeddings API Recommends Voyage AI: voyage-4-large, voyage-4, voyage-4-lite, plus code, finance, law, multimodal and contextual models 1,024 (most models) 32,000 (most current models) output_dimension (256, 512, 1,024, 2,048) input_type="query" / "document"
OpenRouter ✅ (OpenAI-compatible) Many providers' models, such as openai/text-embedding-3-small, openai/text-embedding-3-large and perplexity/pplx-embed-v1-0.6b Depends on the model Depends on the model dimensions (if the model supports it) input_type (passed to models that support it)

The documentation for all of them uses cosine similarity (or the equivalent dot product on normalized vectors) in its examples. OpenAI, Voyage and Gemini (at full size, and gemini-embedding-2 at any size) return normalized vectors.

Other embedding APIs include Cohere (Embed v4, with built-in int8 and binary output; Cohere's model list now also has Embed v5), Mistral, Jina and the cloud platforms (Amazon Bedrock, Google Vertex AI). For self-hosting at scale, servers such as Hugging Face Text Embeddings Inference (TEI) or Ollama serve open models over HTTP. This lesson's samples cover the four providers used throughout the path.

6.2 OpenAI#

python
import numpy as np
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()                      # reads OPENAI_API_KEY from .env
client = OpenAI()

texts = ["How do I reset my password?", "I forgot my login credentials.", "What is your refund policy?"]

response = client.embeddings.create(
    model="text-embedding-3-small",   # 1536 dimensions by default
    input=texts,                      # a list: one request, many embeddings
)
vectors = np.array([item.embedding for item in response.data])
print("Shape:", vectors.shape)
print("Lengths:", np.linalg.norm(vectors, axis=1).round(3))     # already normalized
print("Tokens billed:", response.usage.total_tokens)
print("password vs forgot-login:", round(float(vectors[0] @ vectors[1]), 3))
print("password vs refund      :", round(float(vectors[0] @ vectors[2]), 3))

# Ask for shorter vectors (Matryoshka-style truncation done by the API)
short = client.embeddings.create(model="text-embedding-3-small", input=texts, dimensions=256)
print("Shorter shape:", (len(short.data), len(short.data[0].embedding)))
Example output · illustrative6 lines
Shape: (3, 1536)
Lengths: [1. 1. 1.]
Tokens billed: 20
password vs forgot-login: 0.618
password vs refund      : 0.214
Shorter shape: (3, 256)

Points to know:

  • Batch your inputs. input accepts a list: up to 2,048 inputs per request, each within 8,192 tokens, and at most 300,000 tokens in total per request (2,048 chunks of 500 tokens would be about 1 million, so split big jobs). Over-long inputs are rejected with an error, not truncated, so count tokens first (lesson 02, 12.6). One request with 100 texts is much faster than 100 requests.
  • response.data keeps the input order. Each item also carries an index field.
  • dimensions shortens vectors to any size up to the default. The API returns them already re-normalized (10.1). OpenAI's guide notes that text-embedding-3-large shortened to 256 dimensions still outperforms the older text-embedding-ada-002 at its full 1,536 on the MTEB benchmark.
  • Pricing is per input token. OpenAI's embeddings guide lists approximate "pages per dollar" for each model, and text-embedding-3-small is several times cheaper than -large. Check the current pricing page rather than hard-coding prices. OpenAI's Batch API also accepts embedding requests, at a discount, for large offline jobs.
  • Knowledge cutoff exists here too. OpenAI's documentation states that the v3 embedding models lack knowledge of events after September 2021. That rarely matters for embeddings, but new product names or slang may embed less precisely.

6.3 Google Gemini#

Gemini has two current embedding models, and they behave differently in ways that can trip you up:

gemini-embedding-001 gemini-embedding-2
Input Text only Text, images, video, audio and PDF in one shared space (10.4)
Max input 2,048 tokens 8,192 tokens
Telling it the task The task_type parameter No task_type: put a task prefix in the text instead
A list of texts in contents One embedding per text One aggregated embedding for the whole list, unless each item is wrapped in its own Content
Normalization when shortened ❌ You must normalize yourself (only 3,072 is normalized) ✅ Automatic
Compatible with the other? ❌ Different spaces: switching means re-embedding everything (7.5)
python
import numpy as np
from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()                      # reads GEMINI_API_KEY from .env
client = genai.Client()

docs = ["Refunds are issued within 14 days of receiving the returned item.",
        "The mobile app is available for iOS and Android."]
query = "can I get my money back"

# gemini-embedding-001: text only, task_type tells the model how the vector will be used
doc_result = client.models.embed_content(
    model="gemini-embedding-001",
    contents=docs,
    config=types.EmbedContentConfig(task_type="RETRIEVAL_DOCUMENT", output_dimensionality=768),
)
query_result = client.models.embed_content(
    model="gemini-embedding-001",
    contents=query,
    config=types.EmbedContentConfig(task_type="RETRIEVAL_QUERY", output_dimensionality=768),
)
D = np.array([e.values for e in doc_result.embeddings])
q = np.array(query_result.embeddings[0].values)

# gemini-embedding-001 only normalizes the full 3072-dim output, so normalize ourselves
D /= np.linalg.norm(D, axis=1, keepdims=True)
q /= np.linalg.norm(q)
print("Shape:", D.shape)
print("Scores:", (D @ q).round(3))

# gemini-embedding-2: no task_type; put the task in the text instead.
# Wrap each text in its own Content, or you get ONE combined embedding for the whole list.
result = client.models.embed_content(
    model="gemini-embedding-2",
    contents=[
        types.Content(parts=[types.Part.from_text(text=f"task: search result | query: {query}")]),
        types.Content(parts=[types.Part.from_text(text=f"title: none | text: {docs[0]}")]),
    ],
    config=types.EmbedContentConfig(output_dimensionality=768),   # auto-normalized by this model
)
print("gemini-embedding-2 vectors:", len(result.embeddings), "x", len(result.embeddings[0].values))
Example output · illustrative3 lines
Shape: (2, 768)
Scores: [0.712 0.431]
gemini-embedding-2 vectors: 2 x 768

The task_type values for gemini-embedding-001 are:

task_type Use it for
RETRIEVAL_DOCUMENT Documents you'll search over
RETRIEVAL_QUERY Search queries (pair with RETRIEVAL_DOCUMENT)
QUESTION_ANSWERING Questions whose answers you'll retrieve (pair with RETRIEVAL_DOCUMENT)
FACT_VERIFICATION Statements to check against evidence (pair with RETRIEVAL_DOCUMENT)
CODE_RETRIEVAL_QUERY Natural-language queries for code (pair with RETRIEVAL_DOCUMENT for the code)
SEMANTIC_SIMILARITY Comparing texts with each other (duplicates, recommendations)
CLASSIFICATION Texts you'll classify against labels
CLUSTERING Texts you'll group by similarity

For gemini-embedding-2, Google's documentation gives text formats instead: for search, queries become task: search result | query: {content} and documents become title: {title} | text: {content} (with title: none if there's no title). Other query prefixes include task: question answering, task: fact checking and task: code retrieval, while symmetric tasks use task: classification | query: {content}, task: clustering | query: {content} or task: sentence similarity | query: {content} for both sides. Whatever format you choose, use it consistently for everything you compare.

Gemini's Batch API also processes embedding requests at 50% of the standard price, which suits large indexing jobs where latency doesn't matter.

6.4 Anthropic: no embeddings API (use Voyage AI)#

Anthropic does not offer its own embedding model, and the anthropic SDK has no embeddings method. Claude's documentation recommends Voyage AI (now part of MongoDB) and shows how to use it, while advising you to evaluate several embedding vendors for your use case. This is a common pattern: Claude generates the answers, and a separate embedding model handles retrieval. Nothing requires the embedding model and the chat model to come from the same company.

Voyage AI keys are created in MongoDB's Voyage console (under AI Model APIs) and read from VOYAGE_API_KEY:

python
import numpy as np
import voyageai
from dotenv import load_dotenv

load_dotenv()                      # reads VOYAGE_API_KEY from .env
vo = voyageai.Client()

docs = ["Refunds are issued within 14 days of receiving the returned item.",
        "The mobile app is available for iOS and Android."]
query = "can I get my money back"

# input_type tells Voyage whether it is embedding a document or a search query
D = np.array(vo.embed(docs, model="voyage-4", input_type="document").embeddings)
q = np.array(vo.embed([query], model="voyage-4", input_type="query").embeddings[0])

print("Shape:", D.shape)                       # 1024 dimensions by default
print("Scores:", (D @ q).round(3))             # normalized, so dot product = cosine

small = vo.embed(docs, model="voyage-4", input_type="document", output_dimension=256)
print("Smaller:", len(small.embeddings[0]))
Example output · illustrative3 lines
Shape: (2, 1024)
Scores: [0.684 0.218]
Smaller: 256

Points to know (from Claude's and Voyage's documentation, as of October 2026):

  • Models: voyage-4-large (best quality), voyage-4 (balanced), voyage-4-lite (lowest latency and cost), and the open-weight voyage-4-nano (Apache 2.0), which you download from Hugging Face and run yourself. It isn't served through the API, and it defaults to 2,048 dimensions rather than 1,024. There are also domain models (voyage-code-4, voyage-finance-2, voyage-law-2), a multimodal model (voyage-multimodal-3.5, called with multimodal_embed()) and contextualized chunk models (voyage-context-4, called with contextualized_embed()). Context limits are 32,000 tokens for most current models, but voyage-law-2 accepts 16,000 and voyage-context-4 up to 120,000 with automatic chunking enabled.
  • input_type matters. For retrieval, Voyage's guidance is not to omit it. Under the hood, it prepends an instruction such as "Represent the query for retrieving supporting documents: " to your text (10.3).
  • output_dtype can return int8, uint8, binary or ubinary vectors instead of floats, for 4× or 32× less storage (10.2).
  • A shared embedding space across the Voyage 4 family. Voyage states that all Voyage 4 models produce compatible embeddings, so you can embed documents once with voyage-4-large and embed queries with the cheaper voyage-4-lite. This is a deliberate, documented exception to the rule in 7.5, and it applies only within that family.
  • Rerankers. Voyage also offers rerankers (rerank-3, rerank-3-lite), which Module 06 covers.

6.5 OpenRouter#

OpenRouter provides an OpenAI-compatible embeddings endpoint at https://openrouter.ai/api/v1/embeddings, routing to embedding models from several providers. Because it follows OpenAI's format, the openai SDK works with a different base_url:

python
import os

import numpy as np
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()                      # reads OPENROUTER_API_KEY from .env
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"])

texts = ["How do I reset my password?", "I forgot my login credentials."]
response = client.embeddings.create(
    model="openai/text-embedding-3-small",     # OpenRouter IDs are "provider/model"
    input=texts,
    dimensions=512,
)
vectors = np.array([item.embedding for item in response.data])
print("Shape:", vectors.shape)
print("Similarity:", round(float(vectors[0] @ vectors[1]), 3))
Example output · illustrative2 lines
Shape: (2, 512)
Similarity: 0.617

Points to know:

  • Model IDs use the provider/model form. Browse the current embedding models on OpenRouter's models page filtered to embeddings output, or list them programmatically with GET https://openrouter.ai/api/v1/embeddings/models.
  • Extra fields. OpenRouter's API also accepts input_type (for models that distinguish queries from documents), provider (routing preferences, such as which providers to allow and whether to allow data collection) and multimodal inputs for models that support them. With the openai SDK, pass fields it doesn't know about through extra_body={...}.
  • Same model, same space. openai/text-embedding-3-small through OpenRouter is the same model as through OpenAI directly. But mixing different models behind one gateway doesn't make their vectors compatible (7.5).

6.6 Practical concerns for every provider#

Concern What to do
Batching Send many texts per request (within the provider's per-request limits). Use offline batch APIs for large backfills where available.
Rate limits and retries Indexing jobs hit rate limits. Retry with exponential backoff, and make jobs resumable so a failure at item 80,000 doesn't restart from zero (Module 03).
Embedding cache The same text with the same model and settings gives the same vector (apart from tiny floating-point differences), so never pay to embed the same text twice. Cache by a hash of (model, settings, text). (This is your own application cache, not the provider prompt caching of lesson 07, Part 7.)
Record the model with the vector Store the model ID, dimensions and any task type or prefix alongside every vector. You'll need them when you change models (7.5).
Cost Embedding is cheap per token, but indexing a large corpus is many tokens, and re-indexing after a model change costs it all again. Estimate it as total tokens × price per token, and look the price up on the provider's pricing page.
Privacy Embedding sends your text to the provider, just like a chat request. The same data-use policies apply (Module 12), and vectors themselves can leak content (10.7).
Local alternative Open-weight models (via sentence-transformers, or voyage-4-nano) keep data on your own machines and have no per-token fees, at the cost of running the hardware yourself.

Part 7: Choosing an embedding model#

7.1 The trade-offs#

There's no single best embedding model, only the best one for your data, languages, budget and constraints. These are the factors to weigh:

Factor Why it matters Questions to ask
Retrieval quality on your data The whole point. Varies by domain far more than leaderboards suggest How does it do on my queries and my documents?
Dimensions Storage, memory and search speed scale with them (7.2) Can I shorten the vectors (Matryoshka) without losing much?
Cost Priced per input token for APIs; hardware for self-hosted What does embedding my whole corpus cost, and re-embedding it?
Speed / latency Every search embeds the user's query before anything else happens How long does one short query take to embed?
Max input length Longer inputs are truncated or rejected (5.7) Does it fit my chunk size comfortably?
Languages English-only models fail silently on other languages (7.3) Which languages are my users and documents in? Are queries and documents in different languages?
Domain fit Code, legal, medical, finance and other jargon-heavy text benefit from specialist models Is there a domain model, and does it beat the general ones on my data?
Modalities Text only, or also images, PDFs, audio, video (10.4) Do I need to search images with text, or vice versa?
Deployment and privacy APIs send data to a provider; open models can run on your own servers Can this data leave my infrastructure?
Licence and stability Open-weight licences vary; API models get deprecated Can I use it commercially? What happens when it's retired?

7.2 Dimensions and storage maths#

Each vector costs dimensions × bytes per number. Standard float32 numbers take 4 bytes each (lesson 01, 4.4). For ten million chunks:

python
def storage_gb(num_vectors, dims, bytes_per_number):
    return num_vectors * dims * bytes_per_number / 1e9

n = 10_000_000          # ten million chunks
print(f"{'dims':>5}  {'float32':>9}  {'int8':>8}  {'binary':>8}")
for dims in [384, 768, 1024, 1536, 3072]:
    print(f"{dims:>5}  {storage_gb(n, dims, 4):6.1f} GB  {storage_gb(n, dims, 1):5.1f} GB  {storage_gb(n, dims, 1/8):5.2f} GB")
Output6 lines
 dims    float32      int8    binary
  384    15.4 GB    3.8 GB   0.48 GB
  768    30.7 GB    7.7 GB   0.96 GB
 1024    41.0 GB   10.2 GB   1.28 GB
 1536    61.4 GB   15.4 GB   1.92 GB
 3072   122.9 GB   30.7 GB   3.84 GB

At full 3,072 dimensions, ten million vectors need about 123 GB, which is expensive to keep in a vector database's memory. Shortening to 768 dimensions cuts that to 31 GB, and int8 storage to under 8 GB (Part 10). These numbers exclude the index structures a vector database adds on top (Module 06).

The practical takeaway: dimensions are a cost dial. Start with a model's recommended or default size, then test whether smaller sizes keep enough quality on your evaluation set.

7.3 Multilingual models#

An English-only model doesn't fail loudly on other languages. It just returns poor vectors. Compare all-MiniLM-L6-v2 (English) with a multilingual sibling, paraphrase-multilingual-MiniLM-L12-v2, on the same question in four languages:

python
from sentence_transformers import SentenceTransformer

english_only = SentenceTransformer("all-MiniLM-L6-v2")
multilingual = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2")

query = "Where is the train station?"
candidates = [
    "¿Dónde está la estación de tren?",        # Spanish: same meaning
    "Wo ist der Bahnhof?",                     # German: same meaning
    "रेलवे स्टेशन कहाँ है?",                     # Hindi: same meaning
    "I like eating apples.",                   # English: unrelated
]
for name, model in [("all-MiniLM-L6-v2", english_only), ("multilingual", multilingual)]:
    q = model.encode(query, normalize_embeddings=True)
    c = model.encode(candidates, normalize_embeddings=True)
    print(name)
    for text, score in zip(candidates, c @ q):
        print(f"  {score:5.2f}  {text}")
Output10 lines
all-MiniLM-L6-v2
   0.16  ¿Dónde está la estación de tren?
   0.43  Wo ist der Bahnhof?
   0.10  रेलवे स्टेशन कहाँ है?
  -0.01  I like eating apples.
multilingual
   0.99  ¿Dónde está la estación de tren?
   0.93  Wo ist der Bahnhof?
   0.97  रेलवे स्टेशन कहाँ है?
   0.02  I like eating apples.

The multilingual model places translations of the same question almost on top of each other (0.93–0.99), which makes cross-lingual search possible: an English query finding Spanish or Hindi documents. The English-only model barely recognizes them. All the current provider models in Part 6 are multilingual (Gemini's documentation, for example, says gemini-embedding-2 covers over 100 languages), but quality still varies by language, so test with your actual languages, especially lower-resource ones.

7.4 The MTEB leaderboard and its caveats#

The Massive Text Embedding Benchmark (MTEB) is the standard public comparison of embedding models. It tests models on many tasks (retrieval, classification, clustering, reranking, semantic similarity, pair classification, bitext mining (finding sentence translations across languages), summarization) across many datasets. Its multilingual expansion, MMTEB (2025), covers hundreds of languages and adds tasks such as code retrieval and instruction following. The leaderboard is hosted on Hugging Face, and providers often quote their MTEB scores, as OpenAI's and Google's documentation do.

It's a useful starting point for a shortlist. Treat it carefully:

  • Look at the right column. The headline average mixes many task types. If you're building search or RAG, look at the retrieval scores, for languages and domains like yours.
  • Benchmark data may have leaked into training. Many MTEB datasets are public, and models can be trained (deliberately or not) on similar data, inflating scores. It's the same contamination problem as for LLM benchmarks (lesson 01, 6.4, lesson 09).
  • Check RTEB. The MTEB maintainers' Retrieval Embedding Benchmark (RTEB), introduced in October 2025, mixes open datasets with private ones that model builders can't train on, scored with NDCG@10 (a standard measure of how well the top 10 results are ranked). It covers domains such as law, healthcare, finance and code across 20 languages. A model that does much worse on the private datasets than on the open ones has probably overfitted the benchmark. For search and RAG, RTEB's retrieval ranking is a better shortlist than the overall MTEB average.
  • Small score differences are noise. A 0.5-point gap rarely translates into a difference you can see on your own data.
  • Not every model is listed. Some commercial models aren't submitted, or are evaluated by the provider rather than independently.
  • The leaderboard ignores your constraints: cost, latency, dimensions, licence and deployment.

The reliable method is the one Module 10A teaches: build a small evaluation set of real queries with known relevant documents (even 50–100 is useful), run your shortlist on it, and measure how often the right documents appear in the top results.

7.5 Vectors from different models are not compatible#

This is the single most important operational rule in this lesson: vectors from different embedding models live in different spaces and must never be compared with each other. Each model learns its own arrangement of meaning. Dimension 17 in one model has no relationship to dimension 17 in another, even when both produce vectors of the same length.

Here's what happens if you build an index with one model, then embed queries with another 384-dimension model, a mistake that's easy to make when "upgrading" a model:

python
import numpy as np
from sentence_transformers import SentenceTransformer

old_model = SentenceTransformer("all-MiniLM-L6-v2")
new_model = SentenceTransformer("intfloat/e5-small-v2")       # also 384 dimensions

docs = [
    "To reset your password, click 'Forgot password' on the sign-in page.",
    "Refunds are issued within 14 days of receiving the returned item.",
    "The mobile app is available for iOS and Android.",
    "We ship to over 40 countries; international delivery takes 5-10 days.",
]
query = "I can't remember my login"

stored = old_model.encode(docs, normalize_embeddings=True)       # index built last year
print("Dimensions:", stored.shape[1], "and", new_model.get_sentence_embedding_dimension())

for name, model in [("query embedded with the SAME model", old_model),
                    ("query embedded with a DIFFERENT model", new_model)]:
    q = model.encode(query, normalize_embeddings=True)
    scores = stored @ q
    print(f"\n{name}:")
    for i in np.argsort(-scores):
        print(f"  {scores[i]:5.2f}  {docs[i]}")
Output13 lines
Dimensions: 384 and 384

query embedded with the SAME model:
   0.62  To reset your password, click 'Forgot password' on the sign-in page.
   0.01  Refunds are issued within 14 days of receiving the returned item.
  -0.01  The mobile app is available for iOS and Android.
  -0.11  We ship to over 40 countries; international delivery takes 5-10 days.

query embedded with a DIFFERENT model:
   0.12  To reset your password, click 'Forgot password' on the sign-in page.
   0.02  The mobile app is available for iOS and Android.
  -0.01  Refunds are issued within 14 days of receiving the returned item.
  -0.05  We ship to over 40 countries; international delivery takes 5-10 days.
  • Same model: the right document stands out clearly (0.62, against 0.01 or less for everything else).
  • Different model: every score collapses towards zero. The best is 0.12, barely distinguishable from the unrelated documents. A "match" threshold of, say, 0.4 would now return nothing, and in a real index of thousands of chunks, the right one would be lost among noise-level scores.
  • The correct document still happens to come first here. That's partly luck with only four candidates, and partly because these two small models share the same tokenizer vocabulary and a similar BERT-style architecture. Don't count on it: between unrelated models, the ranking is effectively random.

Notice that nothing errors. The shapes match, so the maths runs and returns numbers. That's what makes this mistake dangerous: search quality silently collapses.

What this means for you as an engineer:

  • Store the model ID and settings with every vector (6.6), and refuse to compare vectors whose model IDs differ.
  • Changing models means re-embedding everything. Google's documentation states this explicitly for moving from gemini-embedding-001 to gemini-embedding-2: the spaces are incompatible, so existing data must be re-embedded.
  • Plan migrations like database migrations. A typical approach: build a second index with the new model in the background, write new content to both, compare quality on your evaluation set, switch queries over, then delete the old index. Budget the cost of re-embedding the whole corpus.
  • Model versions count too. A provider can retire a model, and an "updated" model under a new name is a new space. Pin exact model IDs.
  • The documented exception: a provider can deliberately train a family of models into a shared space. Voyage states that all Voyage 4 models are compatible with each other (6.4). Rely on this only when the provider documents it, and only within that family.

7.6 A practical selection process#

flowchart TB
    A["Start: what will you embed?"] --> B{"Data must stay<br/>on your servers?"}
    B -- "yes" --> L["Open-weight model run locally<br/>(sentence-transformers, BGE, E5, Qwen3-Embedding, voyage-4-nano...)"]
    B -- "no" --> C{"Mostly one language<br/>and general text?"}
    C -- "yes" --> G["Shortlist: a small/cheap API model<br/>and one larger model"]
    C -- "no: many languages,<br/>code, legal, images..." --> S["Shortlist models that support<br/>your languages, domain or modality"]
    L --> E["Evaluate on YOUR queries and documents"]
    G --> E
    S --> E
    E --> F["Pick the cheapest model that meets<br/>your quality bar; choose dimensions"]

A sensible default if you already use one provider is to start with its embedding model (or Voyage AI if you're on Claude), build your evaluation set early, and only switch if the numbers say so. Switching later is possible, but costs a full re-embed (7.5).


Part 8: What embeddings are used for#

You built one in 5.6: embed documents once, embed each query, return the nearest documents. It powers help-centre search, internal knowledge search, code search, product search and "find similar" features. In production, it's usually combined with keyword search (hybrid search), because each catches what the other misses (10.6, Module 06).

8.2 Classification, deduplication and anomaly detection#

Three more uses fit in one short script:

python
import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")
embed = lambda texts: model.encode(texts, normalize_embeddings=True)

# 1. Zero-shot classification: compare each ticket with a short description of each label
labels = {
    "billing":   "billing, payments, invoices, charges and refunds",
    "technical": "bugs, errors, crashes and technical problems with the app",
    "account":   "login, password, sign-in and account settings",
}
tickets = [
    "I was charged twice this month.",
    "The app crashes when I upload a photo.",
    "I can't sign in after changing my email.",
]
L = embed(list(labels.values()))
for ticket, scores in zip(tickets, embed(tickets) @ L.T):
    print(f"{list(labels)[scores.argmax()]:9s} ({scores.max():.2f})  {ticket}")

# 2. Near-duplicate detection: flag pairs above a similarity threshold
reviews = [
    "Great product, arrived quickly and works perfectly.",
    "Works perfectly, and it arrived quickly. Great product!",
    "Terrible battery life, would not recommend.",
    "The battery died after two hours. Not recommended.",
    "Nice colour but the strap feels cheap.",
]
R = embed(reviews)
S = R @ R.T
print("\nReview pairs, most similar first (threshold 0.85):")
pairs = [(S[i, j], i, j) for i in range(len(reviews)) for j in range(i + 1, len(reviews))]
for score, i, j in sorted(pairs, reverse=True)[:3]:
    flag = "DUPLICATE" if score > 0.85 else ""
    print(f"  {score:.2f}  #{i} ~ #{j}  {flag}".rstrip())

# 3. Anomaly detection: which message is furthest from the average of all messages?
messages = [
    "Your order has shipped.", "Your order is out for delivery.",
    "Your order was delivered.", "Your order has been packed.",
    "Congratulations, you won a free cruise! Click here.",
]
M = embed(messages)
centre = M.mean(axis=0)
centre /= np.linalg.norm(centre)
print("\nSimilarity to the average message (lowest = most unusual):")
for score, msg in sorted(zip(M @ centre, messages)):
    print(f"  {score:.2f}  {msg}")
Output15 lines
billing   (0.33)  I was charged twice this month.
technical (0.60)  The app crashes when I upload a photo.
account   (0.43)  I can't sign in after changing my email.

Review pairs, most similar first (threshold 0.85):
  0.89  #0 ~ #1  DUPLICATE
  0.72  #2 ~ #3
  0.42  #1 ~ #3

Similarity to the average message (lowest = most unusual):
  0.48  Congratulations, you won a free cruise! Click here.
  0.87  Your order is out for delivery.
  0.90  Your order has shipped.
  0.91  Your order was delivered.
  0.91  Your order has been packed.
  • Classification: each ticket went to the right category by comparing it with a one-line description of each label. No training, no examples. That's zero-shot classification. It's a quick baseline. For higher accuracy, train a small classifier (such as logistic regression, lesson 01, 5.5) on embeddings of a few hundred labelled examples, which is usually far cheaper per item than asking a chat model.
  • Deduplication: the two reworded "great product" reviews scored 0.89 and were flagged. The two battery complaints (0.72) say the same thing in different words and weren't flagged at 0.85. Whether they should be is a product decision, which is exactly why thresholds must be tuned on real examples (4.6).
  • Anomaly detection: the spam message is far from the "centre" of the other messages (0.48 against ~0.9). The same idea flags unusual log lines, off-topic chatbot inputs or suspicious transactions described in text.

8.3 Clustering, recommendations and more#

Use How embeddings help Example
Semantic search Nearest vectors to the query Help centre, docs, code search
Clustering Group nearby vectors with standard clustering algorithms (such as k-means or HDBSCAN) Discover themes in 50,000 support tickets or survey answers
Classification Nearest label, or a small classifier on top of the vectors Routing tickets, tagging content, sentiment
Deduplication Pairs above a tuned threshold Merging duplicate bug reports, cleaning training or RAG data (Module 05)
Recommendations Items near what a user liked, or near the user's average vector "Related articles", "similar products"
Anomaly / outlier detection Vectors far from everything else Spam, off-topic inputs, unusual logs
Retrieval for RAG Find the passages a chat model needs to answer Every RAG system (8.4)
Semantic caching Reuse a stored answer when a new question is close enough to an old one Cutting LLM costs for repeated questions (Module 11B)
Routing Send a request to the handler whose description is nearest Choosing which tool, prompt or model handles a request (Module 08A)
Evaluation Similarity between an answer and a reference answer A cheap signal (with clear limits) in eval pipelines (Module 10A)

8.4 The foundation of RAG#

Retrieval-augmented generation (RAG) is the most common reason AI engineers use embeddings. A chat model knows nothing about your private or recent documents (lesson 01, 7.3), so you retrieve the relevant passages with embeddings and put them in the prompt:

flowchart TB
    subgraph idx ["Index time: once per document"]
        D["Documents"] --> CH["Split into chunks<br/>(Module 05)"]
        CH --> EM1["Embedding model"]
        EM1 --> ST[("Vector store<br/>(Module 06)")]
    end
    subgraph qry ["Query time: every request"]
        Q["User question"] --> EM2["Same embedding model"]
        EM2 --> SIM["Similarity search<br/>cosine / dot product"]
        ST --> SIM
        SIM --> TOP["Top-k most similar chunks"]
        TOP --> LLM["Chat LLM answers using them<br/>(RAG, Module 07)"]
    end

Everything in this lesson shows up in that diagram: choosing a model (Part 7), using the same model on both sides (7.5), matching the similarity measure (Part 4), staying within input limits (5.7), and knowing what embeddings can't distinguish (10.6). The engineering of vector stores, indexes, hybrid search and reranking is Module 06, and building full RAG pipelines is Module 07.


Part 9: Visualizing embeddings#

Deep-dive

9.1 Try it: PCA in NumPy#

You can't picture 384 dimensions, but you can squash them down to 2 and plot them. The classic method is principal component analysis (PCA): find the directions along which the vectors vary the most, and keep only the top two. It needs nothing but NumPy:

python
import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")
items = [
    ("pets",    "My dog loves chasing the ball in the park."),
    ("pets",    "The kitten fell asleep on the warm windowsill."),
    ("pets",    "Our parrot can say a dozen words."),
    ("finance", "The central bank raised interest rates again."),
    ("finance", "Index funds are a low-cost way to invest."),
    ("finance", "Inflation reduced the value of my savings."),
    ("cooking", "Simmer the tomato sauce for twenty minutes."),
    ("cooking", "Knead the dough until it is smooth and elastic."),
    ("cooking", "Add a pinch of salt to the boiling pasta water."),
]
labels = [label for label, _ in items]
X = model.encode([text for _, text in items], normalize_embeddings=True)   # 9 x 384

# PCA with plain numpy: centre the data, then find the directions of greatest spread
Xc = X - X.mean(axis=0)
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
coords = Xc @ Vt[:2].T                       # project onto the top 2 directions
explained = (S**2) / (S**2).sum()

print(f"{'topic':8s} {'x':>6s} {'y':>6s}  text")
for (label, text), (x, y) in zip(items, coords):
    print(f"{label:8s} {x:6.2f} {y:6.2f}  {text}")
print(f"\nVariance kept by 2 dimensions: {explained[:2].sum():.0%} (of what's left after centring)")
Output12 lines
topic         x      y  text
pets      -0.13   0.60  My dog loves chasing the ball in the park.
pets      -0.15   0.32  The kitten fell asleep on the warm windowsill.
pets      -0.01   0.65  Our parrot can say a dozen words.
finance   -0.44  -0.33  The central bank raised interest rates again.
finance   -0.41  -0.34  Index funds are a low-cost way to invest.
finance   -0.49  -0.33  Inflation reduced the value of my savings.
cooking    0.55  -0.09  Simmer the tomato sauce for twenty minutes.
cooking    0.56  -0.21  Knead the dough until it is smooth and elastic.
cooking    0.52  -0.28  Add a pinch of salt to the boiling pasta water.

Variance kept by 2 dimensions: 39% (of what's left after centring)

Even printed as numbers, the three groups are visible:

Region of the 2D map Topic
Top (y ≈ 0.3 to 0.65) Pets
Bottom left (x ≈ −0.45, y ≈ −0.33) Finance
Right (x ≈ 0.55) Cooking

Nine sentences with no shared words fell into three clean clusters, although nobody told the model about the topics. (To draw the map, pass coords to any plotting library, such as matplotlib's scatter.)

9.2 What 2D pictures hide#

The last line of the output says it all: the two dimensions kept only 39% of the variation in the data. The other 61% was thrown away. That's typical, and it's why 2D embedding plots need care:

  • Points that look close in 2D can be far apart in the full space, and vice versa. Always check a suspicious closeness with the real similarity score.
  • t-SNE and UMAP, two popular alternatives to PCA, produce prettier, more clustered pictures, but they distort distances further: the gaps between clusters and the sizes of clusters often mean nothing, and different random seeds give different layouts.
  • Clean clusters in a plot don't prove good retrieval. Visualization is for exploring and explaining data (spotting topics, outliers, mislabelled items, duplicate-heavy regions), not for evaluating a model. Use the measurements from 7.4 for that.

Part 10: Going deeper#

Deep-dive

10.1 Matryoshka embeddings: truncatable dimensions#

Normally, cutting a vector short wrecks it, because information is spread across all dimensions (2.4). Matryoshka Representation Learning (MRL) (Kusupati et al., 2022), named after Russian nesting dolls, trains a model so that the first dimensions carry the most important information. The first 256 numbers form a usable small embedding, the first 768 a better one, and so on up to the full vector.

Current provider models are trained this way:

Provider How to get shorter vectors Normalized afterwards?
OpenAI text-embedding-3-* dimensions=256 (any value up to the default) ✅ Yes, by the API
Gemini gemini-embedding-001 output_dimensionality=768 (128–3,072; 768, 1,536 or 3,072 recommended) ❌ Only at 3,072: normalize yourself
Gemini gemini-embedding-2 output_dimensionality=768 (same range) ✅ Yes, automatically
Voyage voyage-4* output_dimension=256 (256, 512, 1,024 or 2,048) ✅ Yes, by the API

Google's documentation gives a sense of how gracefully quality degrades for gemini-embedding-001 on MTEB: 68.16 at 2,048 dimensions, 68.17 at 1,536, 67.99 at 768, 67.55 at 512, 66.19 at 256 and 63.31 at 128.

Rules for using it:

  • Prefer the API parameter to shortening vectors yourself.
  • If you shorten stored vectors yourself, keep the first k numbers and re-normalize (divide by the new length). Forgetting to re-normalize breaks the "dot product = cosine" shortcut.
  • Only do this with models trained for it. On an ordinary model, truncation loses information faster, as the experiment below shows.
  • A common pattern: search with short vectors to get fast, cheap candidates, then re-score the top candidates with the full vectors ("funnel" or "adaptive" retrieval).

Let's test the claim. We'll compare all-MiniLM-L6-v2 (not trained for truncation) with static-retrieval-mrl-en-v1, a small, very fast English model from the sentence-transformers team that was trained with a Matryoshka loss (about 125 MB). For 25 help-centre documents and 12 queries, we cut each model's vectors to 1/2, 1/4, 1/8 and 1/16 of their length and measure how much of each query's top 3 survives:

python
import numpy as np
from sentence_transformers import SentenceTransformer

docs = [
    "To reset your password, click 'Forgot password' on the sign-in page.",
    "Refunds are issued within 14 days of receiving the returned item.",
    "We ship to over 40 countries; international delivery takes 5-10 days.",
    "Our support team is available Monday to Friday, 9am to 6pm.",
    "You can pay with a credit card, PayPal or bank transfer.",
    "Two-factor authentication adds a second step when you log in.",
    "Premium plans include priority support and unlimited projects.",
    "Delete your account from Settings > Privacy > Delete account.",
    "Invoices can be downloaded as PDF from the Billing page.",
    "The mobile app is available for iOS and Android.",
    "Standard delivery within the country takes 2-3 working days.",
    "You can change your email address under Settings > Profile.",
    "Gift cards never expire and can be used on any order.",
    "Damaged items can be returned free of charge within 30 days.",
    "Our offices are closed on public holidays.",
    "Students get a 50% discount with a valid university email.",
    "You can export all your data as a ZIP file from Settings.",
    "The free plan is limited to three projects and 1 GB of storage.",
    "Orders can be cancelled until they have been dispatched.",
    "We use encryption to protect your data at rest and in transit.",
    "Team plans let you invite colleagues and share projects.",
    "Our API allows up to 100 requests per minute on paid plans.",
    "Subscriptions renew automatically unless cancelled before the renewal date.",
    "Live chat support is available on the website for premium customers.",
    "Track your parcel using the link in your shipping confirmation email.",
]
queries = [
    "I can't remember my login", "when will I get my refund", "do you deliver to Canada",
    "how do I pay", "remove my account", "can I talk to someone at the weekend",
    "how long does shipping take", "is there a discount for students", "where is my order",
    "how do I stop my subscription renewing", "can I get my data out", "is my data secure",
]

def top3_agreement(D, Q, k):
    """How much of each query's top 3 survives when vectors are cut to their first k numbers."""
    def unit(x):
        return x / np.linalg.norm(x, axis=1, keepdims=True)
    full = np.argsort(-(Q @ D.T), axis=1)[:, :3]
    cut = np.argsort(-(unit(Q[:, :k]) @ unit(D[:, :k]).T), axis=1)[:, :3]
    return np.mean([len(set(a) & set(b)) / 3 for a, b in zip(full, cut)])

for name in ["all-MiniLM-L6-v2", "sentence-transformers/static-retrieval-mrl-en-v1"]:
    model = SentenceTransformer(name)
    D = model.encode(docs, normalize_embeddings=True)
    Q = model.encode(queries, normalize_embeddings=True)
    dims = D.shape[1]
    row = "  ".join(f"1/{f}: {top3_agreement(D, Q, dims // f):4.0%}" for f in [2, 4, 8, 16])
    print(f"{name.split('/')[-1]:30s} ({dims} dims)  top-3 kept at  {row}")
Output2 lines
all-MiniLM-L6-v2               (384 dims)  top-3 kept at  1/2:  86%  1/4:  75%  1/8:  64%  1/16:  56%
static-retrieval-mrl-en-v1     (1024 dims)  top-3 kept at  1/2:  94%  1/4:  83%  1/8:  69%  1/16:  61%

The Matryoshka-trained model keeps more of its ranking at every cut: 94% vs 86% at half size, and still 61% at 1/16 (64 numbers) against MiniLM's 56% at 1/16 (just 24 numbers). The gap is real but modest on this small test, and truncation always costs something: even the MRL model loses about a sixth of its top-3 agreement at a quarter of its size. Whether that's acceptable depends on your task, so measure it on your own evaluation set.

10.2 Quantized embeddings: int8 and binary#

Shortening reduces the number of numbers. Quantization reduces the size of each number, exactly as model quantization does (lesson 01, 4.5):

  • int8: map each float to one of 256 levels (1 byte instead of 4): 4× smaller.
  • Binary: keep only whether each number is positive or not (1 bit): 32× smaller. Binary vectors are compared by counting matching bits (Hamming distance), which computers do extremely quickly.

Let's measure what each technique does to search results, using the ten documents from 5.6 and five queries. "Same top-1" means the best result matches the full-precision search, and "top-3 overlap" means how much of the top three agrees:

python
import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")
docs = [
    "To reset your password, click 'Forgot password' on the sign-in page.",
    "Refunds are issued within 14 days of receiving the returned item.",
    "We ship to over 40 countries; international delivery takes 5-10 days.",
    "Our support team is available Monday to Friday, 9am to 6pm.",
    "You can pay with a credit card, PayPal or bank transfer.",
    "Two-factor authentication adds a second step when you log in.",
    "Premium plans include priority support and unlimited projects.",
    "Delete your account from Settings > Privacy > Delete account.",
    "Invoices can be downloaded as PDF from the Billing page.",
    "The mobile app is available for iOS and Android.",
]
queries = ["I can't remember my login", "when will I get my refund",
           "do you deliver to Canada", "how do I pay", "remove my account"]
D = model.encode(docs, normalize_embeddings=True)
Q = model.encode(queries, normalize_embeddings=True)
full_rank = np.argsort(-(Q @ D.T), axis=1)

def report(name, scores, bytes_per_vector):
    rank = np.argsort(-scores, axis=1)
    top1 = np.mean(rank[:, 0] == full_rank[:, 0])
    top3 = np.mean([len(set(r[:3]) & set(f[:3])) / 3 for r, f in zip(rank, full_rank)])
    print(f"{name:22s} {bytes_per_vector:5d} bytes   same top-1: {top1:.0%}   top-3 overlap: {top3:.0%}")

report("float32 (384 dims)", Q @ D.T, 384 * 4)

# int8: map each number to one of 256 levels (scale chosen from the data)
scale = np.abs(D).max() / 127
D8 = np.round(D / scale).astype(np.int8)
report("int8", Q @ (D8.astype(np.float32) * scale).T, 384)

# binary: keep only the sign of each number (1 bit), compare by counting matching bits
Db, Qb = D > 0, Q > 0
hamming_sim = (Qb[:, None, :] == Db[None, :, :]).sum(axis=2)
report("binary", hamming_sim.astype(float), 384 // 8)

# truncation: keep the first k numbers (this model was NOT trained for it)
for k in [192, 96, 48]:
    Dt = D[:, :k] / np.linalg.norm(D[:, :k], axis=1, keepdims=True)
    Qt = Q[:, :k] / np.linalg.norm(Q[:, :k], axis=1, keepdims=True)
    report(f"truncated to {k}", Qt @ Dt.T, k * 4)
Output6 lines
float32 (384 dims)      1536 bytes   same top-1: 100%   top-3 overlap: 100%
int8                     384 bytes   same top-1: 100%   top-3 overlap: 100%
binary                    48 bytes   same top-1: 80%   top-3 overlap: 93%
truncated to 192         768 bytes   same top-1: 100%   top-3 overlap: 87%
truncated to 96          384 bytes   same top-1: 100%   top-3 overlap: 87%
truncated to 48          192 bytes   same top-1: 100%   top-3 overlap: 73%
  • int8 used a quarter of the storage with no change to the results here.
  • Binary used 1/32 of the storage and still got the best result right 4 times out of 5. That's why binary search is usually followed by rescoring: fetch the top 50–100 candidates with binary vectors, then re-rank them with the full-precision vectors.
  • Truncation of a model that wasn't trained for it erodes the lower ranks steadily (73% top-3 agreement at 48 dimensions). An MRL-trained model holds up better (10.1).

Two refinements matter in real systems:

  • Real int8 quantization calibrates a range per dimension. Our demo used one global scale for all 384 numbers. Proper implementations measure each dimension's typical minimum and maximum on a sample of your embeddings (thousands of them), which loses less information.
  • Binary quantization works best on high-dimensional models (1,024 dimensions and up). With only 384 bits, more is lost (as the 80% top-1 above shows); with 1,024 or more, binary search plus rescoring often keeps most of the quality.

Voyage's API returns quantized vectors directly (output_dtype="int8", "uint8", "binary" or "ubinary"). Many vector databases can also quantize vectors internally, which Module 06 covers.

10.3 Asymmetric query vs document embeddings#

Search is asymmetric. A query is short and phrased as a question ("can I get my money back"), while the document that answers it is longer and phrased as a statement ("Refunds are issued within 14 days..."). The ideal query vector isn't "a vector for text like this", but "a vector near the documents that answer this". Many models therefore embed queries and documents slightly differently:

Approach Example
An API parameter Voyage input_type="query" / "document"; Gemini 001 task_type="RETRIEVAL_QUERY" / "RETRIEVAL_DOCUMENT"; OpenRouter input_type
A text prefix Gemini 2 task: search result | query: ... vs title: ... | text: ...; E5 models query: vs passage:
An instruction Many LLM-based models expect a one-line task instruction before the query
Nothing OpenAI's text-embedding-3-* models take no such hint

Under the hood, these hints are usually just text prepended to the input, as Voyage's documentation shows ("Represent the query for retrieving supporting documents: "). The model was trained with those prefixes, so it expects them.

Here's what using them looks like with intfloat/e5-small-v2, a small open model trained with query: and passage: prefixes. The documents include a tricky distractor: a sentence that repeats the question without answering it.

python
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("intfloat/e5-small-v2")   # trained with "query: " and "passage: " prefixes

docs = [
    "Refunds are issued within 14 days of receiving the returned item.",
    "Customers often ask whether they can get their money back.",
    "The mobile app is available for iOS and Android.",
]
query = "can I get my money back"

def show(title, q_text, doc_texts):
    q = model.encode(q_text, normalize_embeddings=True)
    D = model.encode(doc_texts, normalize_embeddings=True)
    print(title)
    for doc, score in sorted(zip(docs, D @ q), key=lambda x: -x[1]):
        print(f"  {score:.3f}  {doc}")

show("Without prefixes:", query, docs)
show("\nWith the prefixes the model was trained on:", "query: " + query, ["passage: " + d for d in docs])
Output9 lines
Without prefixes:
  0.909  Customers often ask whether they can get their money back.
  0.837  Refunds are issued within 14 days of receiving the returned item.
  0.766  The mobile app is available for iOS and Android.

With the prefixes the model was trained on:
  0.873  Customers often ask whether they can get their money back.
  0.819  Refunds are issued within 14 days of receiving the returned item.
  0.731  The mobile app is available for iOS and Android.

This small experiment teaches three things, and only one of them is about prefixes:

  • The prefixes changed the scores but not the order here. On a well-built evaluation set, the model's authors report that the prefixes improve retrieval, but the effect on any single query is often small. You only see it by measuring over many queries (Module 10A).
  • The question-shaped distractor won, with or without prefixes. "Customers often ask whether they can get their money back" restates the question without answering it, and it outranked the real answer. Matching the wording of a question instead of its answer is a classic retrieval failure. It's exactly what asymmetric training aims to reduce, and what rerankers fix more reliably (Module 06).
  • This model's scores are compressed. Even the unrelated "mobile app" sentence scores 0.73–0.77. That's the anisotropy from 4.6: with e5, 0.8 is unremarkable, while with all-MiniLM-L6-v2 it would signal a near-duplicate. (e5's authors explain this as a side effect of the low temperature used in its contrastive training (a scaling factor in the training loss, not the sampling temperature of lesson 05). It doesn't harm ranking, which is what matters.)

The rules:

  • Read the model card and use exactly the prefixes, instructions or parameters it specifies. Leaving them out usually degrades retrieval somewhat, without any error.
  • Be consistent. Embed every document the same way, and every query the same way. If you change prefixes, re-embed.
  • Match the task. For comparing like with like (duplicate detection, clustering), use the symmetric setting (such as Gemini's SEMANTIC_SIMILARITY, or the same prefix on both sides), not the query/document pair.

In practice: let the library do it. The demos in this part did truncation, quantization and prefixes by hand so you could see what happens. In real code, sentence-transformers has built-in support for all of them, plus the model's own similarity measure (4.5). This removes whole classes of bugs, such as forgetting a prefix on one side:

python
from sentence_transformers import SentenceTransformer
from sentence_transformers.quantization import quantize_embeddings

docs = ["Refunds are issued within 14 days of receiving the returned item.",
        "The mobile app is available for iOS and Android."]
query = "can I get my money back"

# 1. Matryoshka truncation: ask the library for shorter vectors (it keeps the first 256 numbers)
mrl = SentenceTransformer("sentence-transformers/static-retrieval-mrl-en-v1", truncate_dim=256)
print("Truncated shape:", mrl.encode(docs).shape)

# 2. Query vs document prompts: register them once, then never forget them
e5 = SentenceTransformer("intfloat/e5-small-v2", prompts={"query": "query: ", "document": "passage: "})
q = e5.encode_query(query)            # adds "query: " for you
D = e5.encode_document(docs)          # adds "passage: " for you

# 3. Similarity: the library uses the measure the model is configured for
print("Similarity function:", e5.similarity_fn_name)
print("Scores:", e5.similarity(q, D))

# 4. Quantization: int8 and binary, with ranges calibrated from your own embeddings
print("int8:  ", quantize_embeddings(D, precision="int8", calibration_embeddings=D).dtype, end="  ")
print("binary:", quantize_embeddings(D, precision="ubinary").shape, "(384 bits packed into 48 bytes)")
Output4 lines
Truncated shape: (2, 256)
Similarity function: cosine
Scores: tensor([[0.8195, 0.7310]])
int8:   int8  binary: (2, 48) (384 bits packed into 48 bytes)
  • truncate_dim=256 returns Matryoshka-truncated vectors (10.1).
  • prompts= registers the model's query and document prefixes once. encode_query() and encode_document() then add them for you. Many newer models ship with their prompts already configured, so you only need encode_query() / encode_document().
  • similarity() applies the model's configured measure (cosine here). The scores match the prefixed run above.
  • quantize_embeddings() produces int8 vectors using per-dimension ranges calibrated from the embeddings you pass (use a large sample in practice), or bit-packed binary vectors.

10.4 Multimodal embeddings#

Embeddings aren't limited to text. CLIP (OpenAI, 2021) trained an image encoder and a text encoder together on hundreds of millions of image–caption pairs, so that a photo of a dog and the text "a photo of a dog" land near each other in one shared space. That enables:

  • Text-to-image search: type "red trainers on a white background" and find matching product photos.
  • Image-to-image search: find visually similar items.
  • Zero-shot image classification: compare an image's vector with the vectors of label descriptions, as in 8.2.

Current multimodal embedding models go further. Gemini's gemini-embedding-2 maps text, images, video, audio and PDF pages into a single space, and Voyage's voyage-multimodal-3.5 handles interleaved text, images and video. Open CLIP-style models (such as OpenCLIP and SigLIP) run locally. One caution: in many models, text-to-text similarities and image-to-text similarities sit on different scales (the "modality gap"), so don't reuse one threshold across both. Multimodal applications are covered in Module 09.

10.5 Embedding drift and versioning#

Drift means your vectors gradually stop matching reality. There are three kinds:

Kind What changes Symptom What to do
Model drift The embedding model (a new version, a retired model, a changed prefix or setting) Search quality drops suddenly; scores shift Pin model IDs; store model metadata with vectors; re-embed everything on a change (7.5)
Content drift Your documents change, but their stored vectors don't Search returns outdated passages Re-embed on every content update; track a content hash per chunk
Data (query) drift Users start asking about new things: new products, slang, languages Gradual decline on new topics Monitor retrieval quality and "no good result" rates; refresh evaluation sets; reconsider the model (Module 11A)

A related trap is mixing preprocessing: if documents were cleaned, chunked or prefixed one way last year and another way today, the vectors are no longer directly comparable, even with the same model. Treat the whole embedding pipeline (cleaning, chunking, prefixes, model, dimensions, normalization) as a versioned unit.

10.6 The limits of embeddings#

An embedding compresses a text into a few hundred numbers that capture its overall topic and gist. Precise details often don't survive. Here's all-MiniLM-L6-v2 on pairs that differ in exactly the ways that matter in real applications:

python
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")

pairs = [
    ("Negation",     "The patient has diabetes.",            "The patient does not have diabetes."),
    ("Numbers",      "The meeting is at 3pm on 12 March.",   "The meeting is at 9am on 21 March."),
    ("Exact IDs",    "Error code E-4012 on checkout.",       "Error code E-4021 on checkout."),
    ("Role swap",    "The dog bit the man.",                 "The man bit the dog."),
    ("Paraphrase",   "The patient has diabetes.",            "This person is diabetic."),
]
for name, a, b in pairs:
    ea, eb = model.encode([a, b], normalize_embeddings=True)
    print(f"{name:11s} {float(ea @ eb):.2f}   {a!r} vs {b!r}")
Output5 lines
Negation    0.81   'The patient has diabetes.' vs 'The patient does not have diabetes.'
Numbers     0.88   'The meeting is at 3pm on 12 March.' vs 'The meeting is at 9am on 21 March.'
Exact IDs   0.79   'Error code E-4012 on checkout.' vs 'Error code E-4021 on checkout.'
Role swap   0.98   'The dog bit the man.' vs 'The man bit the dog.'
Paraphrase  0.84   'The patient has diabetes.' vs 'This person is diabetic.'

Look at the first and last rows. "Has diabetes" vs "does not have diabetes" (0.81) scores almost the same as a true paraphrase (0.84). The opposite meaning is nearly as "similar" as the same meaning. Every other pair is also highly similar, although each pair means something different:

Limitation Why it happens Mitigation
Negation ("not", "never", "without") One small word flips the meaning but barely changes the topic Rerankers, which read query and document together; let the LLM check retrieved text (Module 06, Module 07)
Numbers, dates, prices, versions Numbers are split into tokens with weak meanings (lesson 02); "3pm" and "9am" are both just "a time" Store them as structured metadata and filter on them exactly
Exact identifiers and rare terms (error codes, SKUs, names, legal citations) Similar-looking strings get similar vectors; rare strings get poor vectors Hybrid search: add keyword search (BM25) alongside vector search
Word order and roles (who did what to whom) Pooling averages tokens, losing much of the structure Rerankers; structured extraction
Long, multi-topic texts One vector averages many topics (5.7) Chunk content into focused pieces
Domain jargon and new terms Words rare or absent in training get vague vectors Domain models, hybrid search, fine-tuning (7.1)

Stronger models do better on some of these than our small demo model, but no single-vector embedding solves them all. There's even a theoretical reason. Research from Google DeepMind (Weller et al., 2025, "On the Theoretical Limitations of Embedding-Based Retrieval") shows that a vector's dimension caps how many distinct top-k combinations of documents it can represent, so even perfect training can't make single-vector search return every combination of relevant documents. That is one more reason for hybrid and multi-vector retrieval (10.8), and it is why production retrieval combines vector search with keyword search, metadata filters and reranking, and why answers are checked downstream (Module 06, lesson 10).

10.7 Embeddings and privacy#

It's tempting to think a vector is an anonymized, irreversible summary. It isn't. Research has shown that text can be reconstructed from its embedding with surprising accuracy. Morris et al. (2023), "Text Embeddings Reveal (Almost) As Much As Text", recovered the majority of short input texts exactly from their vectors, including names from clinical notes. Techniques like this are called embedding inversion. And because vectors can sometimes be translated between embedding spaces even without paired examples (vec2vec, 2025, see 7.5), leaked vectors are at risk even if the attacker doesn't know which model produced them.

What this means for you as an engineer:

  • Treat embeddings with the same sensitivity as the text they came from. Access control, encryption, retention and deletion policies all apply to your vector store.
  • Deleting a document means deleting its vectors too, including in backups and caches (relevant for data-protection rules such as the GDPR's right to erasure).
  • Don't publish or share "only the vectors" of confidential data on the assumption they're safe.
  • Sending text to an embedding API is subject to the provider's data policies, exactly as for chat requests (Module 12).

10.8 Beyond one vector per text#

Single-vector embeddings (one vector per text) are the standard and the subject of this lesson. You'll also meet these variations, all covered in Module 06:

  • Sparse embeddings (such as SPLADE): very long vectors, mostly zeros, with one slot per vocabulary term, learned so related terms get weight too. They behave like smarter keyword search.
  • Multi-vector (late-interaction) models (such as ColBERT): keep one vector per token and compare query and document token by token. They're more precise and much more expensive to store.
  • Rerankers (cross-encoders): not embeddings at all. They read the query and a document together and output a relevance score. Too slow to run over millions of documents, but excellent for re-ordering the top 20–100 results found by embeddings.

Common misconceptions#

Misconception Reality
"Each dimension of an embedding means something specific." Meaning lives in directions and relative positions spread across many dimensions. Individual dimensions are rarely interpretable (2.4).
"A word has one embedding." Only in the static lookup table. Inside a transformer, every occurrence gets a contextual vector that depends on its sentence (Part 3).
"I can get embeddings from my chat model's API." Chat APIs don't expose their internal vectors, and raw chat-model hidden states make poor sentence embeddings anyway. Use a dedicated embedding model (5.3).
"Claude has an embeddings endpoint." Anthropic offers no embedding model and recommends Voyage AI (6.4).
"A similarity of 0.8 means 80% relevant." Scores are model-specific and only meaningful for ranking. Thresholds must be tuned per model and task (4.6).
"Vectors with the same number of dimensions are interchangeable." Different models produce incompatible spaces. Comparing them returns numbers but meaningless results. Changing models means re-embedding (7.5).
"More dimensions are always better." Quality gains flatten out while storage and compute keep growing. Matryoshka models let you trade a little quality for a lot of savings (7.2, 10.1).
"The model reads my whole document." Input beyond the model's limit is usually truncated silently (5.7).
"Semantic search understands exactly what I mean." Embeddings capture topic and gist. Negation, numbers, exact IDs and word order are weak spots (10.6).
"The top model on MTEB is the best choice for us." Leaderboards are a shortlist, not a decision. Test on your own queries, languages and documents (7.4).
"king − man + woman = queen proves embeddings understand meaning." It's a cherry-picked example that works only when the input words are excluded, and embeddings also absorb biases (2.6).
"Embeddings are anonymous, so they're safe to share." Text can often be reconstructed from its embedding. Protect vectors like the source text (10.7).

Key takeaways#

  • An embedding is a dense vector of numbers that represents content so that similar meaning → nearby vectors.
  • Inside an LLM, the embedding matrix (vocabulary × hidden size) is a learned lookup table: token ID n → row n. It's made of ordinary parameters, and can be a large share of a small model.
  • One-hot vectors make every word equally unrelated. Dense vectors learned from how words are used put related meanings close together (the distributional hypothesis).
  • Hundreds or thousands of dimensions give room for many kinds of similarity at once, but individual dimensions aren't human-readable (superposition). Only whole-vector comparisons are meaningful.
  • word2vec's king − man + woman ≈ queen shows that directions can encode relationships, with real caveats: input words excluded, cherry-picked examples, absorbed bias.
  • Static embeddings give one vector per token. Contextual embeddings from transformer layers separate meanings such as river bank vs money bank.
  • Compare vectors with cosine similarity (direction only), the dot product (fast; equals cosine on normalized vectors) or Euclidean distance (lower = closer). On normalized vectors all three give the same ranking. There's no universal similarity threshold.
  • Sentence embeddings come from dedicated embedding models, trained contrastively, that pool token vectors into one vector per text. They're separate from, and much cheaper than, chat models.
  • Providers: OpenAI (text-embedding-3-small/-large, dimensions), Gemini (gemini-embedding-001 with task_type; multimodal gemini-embedding-2 with text prefixes and an aggregation gotcha), Anthropic has none and recommends Voyage AI (voyage-4 family, input_type), and OpenRouter (OpenAI-compatible /embeddings).
  • Choose models on your own evaluation data, weighing quality, dimensions, cost, speed, input length, languages, domain, modality and privacy. MTEB is a starting point only.
  • Vectors from different models are incompatible. Store the model ID with every vector, and re-embed everything when you switch (unless the provider documents a shared space).
  • Embeddings power semantic search, classification, clustering, deduplication, recommendations, anomaly detection and, above all, RAG.
  • Matryoshka truncation and int8/binary quantization shrink vectors dramatically. Query/document hints improve retrieval. Multimodal models share one space across text and images.
  • Embeddings struggle with negation, numbers, exact identifiers and word order, drift when models or content change, and can leak their source text. Production systems add keyword search, metadata filters, reranking, versioning and access control.

Terms introduced in this lesson#

Term One-line definition
Embedding A dense vector of numbers representing content so that similar content gets similar vectors
Dimension (dimensionality) The number of entries in an embedding vector
One-hot encoding A vector with a single 1 in the slot for one item and 0 everywhere else
Dense vector A short vector where every number carries information (the opposite of one-hot)
Embedding matrix (token embedding table) The learned vocabulary × hidden-size table an LLM uses to look up each token's vector
Hidden size (d_model) The width of the vectors flowing through a model's layers
Weight tying Reusing the embedding matrix as the model's output layer
Distributional hypothesis The idea that words used in similar contexts have similar meanings
word2vec / GloVe Early (2013/2014) methods for learning static word vectors
Static embedding One fixed vector per token, regardless of context
Contextual embedding (hidden state) A token's vector after transformer layers, which depends on its surrounding text
Polysemy One word having several meanings ("bank")
Dot product Multiply matching numbers and add them up
Cosine similarity Similarity based only on the angle between vectors, from −1 to 1
Euclidean distance Straight-line distance between vectors; lower means more similar
Norm (length, magnitude) The length of a vector
Normalization (unit vector) Dividing a vector by its length so its length becomes 1
Anisotropy When a model's vectors crowd into a narrow range of directions, so all similarity scores are high
Sentence / text embedding One vector representing a whole text
Embedding model A model trained specifically to produce comparable vectors for texts (or images)
Pooling (mean, CLS, last-token) Combining a text's token vectors into one vector
Contrastive learning Training that pulls matching pairs together and pushes non-matching examples apart
Semantic search Finding content by meaning, using embedding similarity
Zero-shot classification Classifying by similarity to label descriptions, without training examples
MTEB / MMTEB The standard public benchmark (and its multilingual expansion) for embedding models
RTEB MTEB's retrieval benchmark, which mixes open and private datasets to expose benchmark overfitting
Approximate nearest-neighbour (ANN) index A data structure that finds nearly the closest vectors without comparing against every one
PCA Principal component analysis: projecting vectors onto their most informative directions, for example to plot them in 2D
Matryoshka Representation Learning (MRL) Training embeddings so that their first dimensions form usable shorter embeddings
Binary / int8 quantized embeddings Embeddings stored with 1 bit or 1 byte per number instead of 4 bytes
Asymmetric embedding Embedding queries and documents differently (via input_type, task_type or prefixes)
Multimodal embedding An embedding space shared by text and other modalities such as images (for example CLIP)
Embedding drift Vectors gradually or suddenly no longer matching the current model, content or queries
Embedding inversion Reconstructing the original text from its embedding

All terms are also collected in the glossary.


Exercises#

Run the code from this lesson and experiment:

  1. Embedding matrix (1.4): load Qwen/Qwen2.5-0.5B instead of GPT-2, using model.get_input_embeddings().weight. Print the matrix shape and its share of the parameters, and check the numbers against the table in 1.5.
  2. Neighbours (2.2): find the nearest neighbours of " doctor", " nurse", " engineer" and " teacher" in GPT-2's embedding matrix. Do you see any patterns that look like social bias? What would that mean for a search system built on such vectors?
  3. Analogies (2.6): try " Paris" − " France" + " Italy" and " walking" − " walk" + " swim". Which work? Count how many of your attempts succeed, and decide how much you'd trust analogy arithmetic.
  4. Contextual embeddings (3.3): add a fifth sentence where "bank" means "to rely on" ("You can bank on her to finish the job."). Which group does its vector join? Then compare the vectors from layer 1 instead of the last layer (pass output_hidden_states=True to the model and use out.hidden_states[1]). What changes, and why?
  5. Similarity (4.4): write a function that takes a list of vectors and returns the indices of the top-k most similar to a query, using Euclidean distance. Confirm it returns the same order as cosine similarity on normalized vectors.
  6. Semantic search (5.6): add 20 more documents from a domain you know (your college's FAQ, a product manual). Write ten realistic queries and note how many return the correct document first. Which queries fail, and do the failures match the limitations in 10.6?
  7. Thresholds (4.6, 8.2): collect 20 pairs of near-duplicate and 20 pairs of different-but-related sentences. Embed them, print both score distributions, and choose the threshold that best separates them. Then repeat with paraphrase-multilingual-MiniLM-L12-v2. Is the best threshold the same?
  8. Truncation (5.7): find the number of filler sentences at which the key sentence starts being cut off. Then split the document into chunks of about 100 tokens, embed each chunk, and show that the right chunk is found.
  9. Compression (10.2): rerun the compression experiment with your larger document set from exercise 6. How do binary vectors compare now? Add rescoring: retrieve the top 5 with binary vectors, then re-rank those 5 with the float32 vectors.
  10. Providers (Part 6): if you have an API key, run the same ten queries from exercise 6 through one provider's embedding model and compare its accuracy with all-MiniLM-L6-v2. Then try a smaller dimensions / output_dimensionality value. How small can you go before results change?
Hints and what you should see
  1. The matrix should be (151936, 896), which is 151,936 × 896 = 136,134,656 parameters, about 28% of the whole model (a little under 500 million parameters). Qwen2.5-0.5B ties its input and output matrices, so the output layer adds no second copy.
  2. Print the top 10 neighbours and read them with the caveats in 2.2 in mind: spelling variants come first, then related words. Whether a gendered or stereotyped pattern shows up depends on the words and the model, and a handful of neighbours is anecdote, not proof. The engineering point is that a search system built on vectors inherits whatever associations the training text contained, so test it with your own queries (Module 10A).
  3. Keep a tally, for example "5 of 12 attempts put the intended word first". Relationships such as country to capital or verb to tense are the ones analogy arithmetic handles best, but expect failures with GPT-2's raw input embeddings, and remember that the input words must be excluded from the candidates (2.6). The exercise is meant to leave you sceptical of analogy arithmetic as a feature.
  4. Compare the new sentence's last-layer vector with the four existing ones using the table helper, and judge by the scores, not by what you expect. For the layer comparison, the layer-1 vectors have had only one round of attention mixing, so the separation between the money and river senses should be weaker than at the last layer, and the final layer is where the senses are best separated. Check that against your numbers.
  5. Sort ascending by distance (np.argsort(distances)[:k]), where the cosine version sorts descending (np.argsort(-scores)[:k]). For unit vectors the squared distance equals 2 minus 2 times the cosine (4.4), so the two orderings are identical; for unnormalized vectors they can differ.
  6. Failures usually fall into the 10.6 families: queries that depend on a number, an exact ID or a negation, or whose answer is split across two documents. Write the failing queries down; they are the start of a real evaluation set.
  7. Plot or print the two groups' scores side by side and choose the cut-off that makes the fewest mistakes. Expect the best threshold to differ between models, since each model has its own score scale (4.6).
  8. The cut-off appears where the filler pushes the key sentence past 256 tokens (each filler sentence in 5.7 is about 8 tokens, so the key sentence starts to fall outside the window at roughly 30 filler sentences). Chunks of about 100 tokens put the key sentence inside a chunk the model reads in full, so the query should score highest against that chunk.
  9. Binary vectors on a larger document set should lose more than on ten documents, but rescoring the top 5 with the float32 vectors should recover most of the loss, because the right document is usually still in the candidate list. This two-stage pattern is the standard way to use binary vectors.
  10. Compare top-1 accuracy over your ten queries, then repeat with a smaller dimension setting and find the size at which the first query changes. Reaching 512 or 256 with little change is common for Matryoshka-trained models, but your own data decides.

Check yourself#

  1. Why can't an LLM use token IDs directly as inputs to its layers?
  2. GPT-2's embedding matrix is 50,257 × 768. What do the two numbers mean, and how many parameters does the matrix contain?
  3. Why is multiplying a one-hot vector by the embedding matrix the same as looking up a row?
  4. How do "cat" and "kitten" end up with similar vectors, when nobody told the model they're related?
  5. Why can't you say "dimension 42 means animal"?
  6. What are two honest caveats about the "king − man + woman ≈ queen" example?
  7. What's the difference between a static and a contextual embedding? Give an example where it matters.
  8. Two vectors point in exactly the same direction, but one is three times longer. What's their cosine similarity? Is their dot product affected by the length difference?
  9. Why do cosine similarity, dot product and Euclidean distance give the same ranking on normalized vectors?
  10. A colleague says "anything above 0.8 similarity is a match". What's wrong with that rule, and what should you do instead?
  11. What is pooling, and why can't you just pool a chat model's hidden states to get good sentence embeddings?
  12. Your team uses Claude for generation. Which embeddings API should you use, and why?
  13. With gemini-embedding-2, you pass a list of 50 texts in contents and get back one vector. What happened, and how do you fix it?
  14. You index 2 million chunks with model A, then switch queries to model B, which has the same dimensions. What happens, and what's the correct migration process?
  15. A legal search tool returns documents saying "the contract is not enforceable" for the query "when is the contract enforceable?", and mixes up clause 4.12 with clause 4.21. Which limitations are these, and how would you mitigate each?
  16. What does output_dimensionality=768 (Gemini) or dimensions=256 (OpenAI) do, and what must you remember if you truncate stored vectors yourself?

Further resources#


← 02.2 — Tokens and Tokenization | Module 02 overview | 02.4 — Attention and Transformers →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close