An embedding turns a text into a list of numbers. Close meanings get vectors that point the same way, so search can match “nail-biting mystery” to “gripping thriller” with no word in common.
Pick a query, then switch between Keyword and Embedding. Watch which of the ten books rises to the top. Then we build, piece by piece, the counts, the learned vectors, the cosine, the training loss and the failures behind that ranking.
You need a little Python and what a list of numbers is. We build the rest from zero.
Illustrative toy. Keyword scores are the cosine of word-count vectors. Embedding scores are the cosine of hand-made six-number vectors (Chapter 9 shows them). A real model gives different numbers but the same pattern.
Chapter 0
See why matching words misses the right answer, and what a vector of numbers can do instead
You run a small online bookstore with ten books. A customer types “gripping thriller with a twist ending.” Your best match reads “A nail-biting mystery that subverts expectations.” Not one word is the same.
A keyword search ranks documents by the words they share with the query. It gives this book a score of 0. The meaning is there. The words are not.
The same gap appears whenever people look for “things like this”. Think of a support ticket like a past ticket, or a passage that answers a question. Computers compare numbers. So we need numbers that keep meaning.
An embedding is a list of numbers, a vector, that a model computes for a text, an image or a product. The model learns to give close meanings close vectors. Then “find similar things” becomes “find nearby points.”
Each warm dot is one book from the hero. Tap a dot, or press Next, to light its three nearest neighbours.
Illustrative toy. Each book's vector is the average of hand-made six-number word vectors. The map flattens six numbers to two, so distances on the map are approximate; the scores use all six.
Tap the Cold War spy book. Its neighbours are the detective and the mystery, then the Roman army. The map groups books by what they are about, not by their spelling.
The failure to watch for: users rephrase and get nothing. Measure it by logging queries with zero or poor results. The fix is search that compares meaning, which is what this lesson builds.
Chapter 1
Turn text into numbers by counting, and find the three ways counting gets meaning wrong
First try: give each word a number. apple = 1, banana = 2, zebra = 900. This invents an order. It says apple is closer to banana than to zebra, and a model will believe it.
One-hot encoding removes the false order. With a vocabulary of V words, each word becomes V zeros with a single 1 in its own slot. Now every pair of words is the same distance apart, the square root of 2. “King” is as far from “queen” as from “banana.”
A bag of words turns a whole text into counts: how many times each vocabulary word appears. Texts that share words get similar count vectors. Try three pairs.
Each column is one word. Each cell holds how many times that word appears. Pick a pair and read the score.
The scores are exact cosines of the count rows shown (Chapter 3 defines cosine). Every word counts, including “the” and “was”.
Counting fails three ways. “Happy movie” and “joyful film” score 0, though they mean the same. “Good” and “not good” score 0.89, though they mean the opposite. “Dog bites man” and “man bites dog” score a perfect 1.
Words like “a” fill every count vector and drown the useful words. TF-IDF (term frequency times inverse document frequency) shrinks a word that appears in many documents. Call the count of word w in document d tf. Call the number of documents N, and the number that contain w df.
T-F-I-D-F of w and d equals t-f times the natural log of N over d-f.
Count word w in document d: that is tf. Divide N by df and take the natural log. Multiply the two. A word found in every document gets ln of 1, which is 0.
In the hero's N = 10 books, “a” appears in df = 7, so each use weighs ln(10/7) = 0.36. The puppy book has “a” twice: 2 × 0.36 = 0.71. “Puppy” appears in only that book: 1 × ln(10) = 2.30. One rare word now outweighs two common ones.
| Method | What it captures | What breaks |
|---|---|---|
| Integer ID | nothing | a false order and false distances |
| One-hot | identity only | every pair is equally far apart |
| Bag of words | shared words | synonyms, negation, word order |
| TF-IDF | shared rare words | still no synonyms |
The failure: a user searches “joyful film” and your best “happy movie” page never appears. Measure it by sampling queries whose top result a person judges wrong. The fix is to learn vectors from how people use words. That is the next chapter.
Chapter 2
Learn word vectors by predicting neighbours, store them in a table, and do arithmetic on them
Fill the gap: “She poured the ___ into a cup and added milk.” You guessed coffee or tea from the words around the gap. That is the distributional hypothesis: words that appear in similar contexts have similar meanings.
Word2Vec (Mikolov and colleagues at Google, 2013) turns this into training. A small network gets a word and learns to predict its neighbours, or gets the neighbours and predicts the word. Each word owns a short vector. Words with similar neighbours get similar updates, so their vectors drift together. No person labels anything.
These vectors are dense: a few hundred numbers, all in use, where one-hot needs one slot per vocabulary word. Google released Word2Vec vectors with 300 numbers per word. GloVe (Pennington, Socher and Manning, 2014) learns similar vectors from counts of which words appear together.
The model keeps its vectors in an embedding table: a matrix with one row per word. With 50,000 words and 300 numbers each, the table holds 15 million numbers, 60 MB as 32-bit floats. To embed a word, read its row. That lookup gives the same answer as multiplying the word's one-hot vector by the table.
pythonimport torch, torch.nn as nn table = nn.Embedding(50_000, 300) # 50,000 rows x 300 numbers, learned ids = torch.tensor([42, 17, 29]) # word ids, shape (3,) vecs = table(ids) # row lookup, shape (3, 300)
The 2013 paper reported a surprise. Take the vector for “king”, subtract “man”, add “woman”. The nearest word vector is “queen”. Call a word's row in the table e with the word below it, and the result v.
v equals e-king minus e-man plus e-woman.
Start at e-king. Subtract e-man and add e-woman, number by number. Then find the word whose vector points most nearly the same way as v, skipping the three input words.
In the toy plane below, e-king = (1.5, −0.9), e-man = (−1.5, −1.0), e-woman = (−1.4, 1.1). So v = (1.5 + 1.5 − 1.4, −0.9 + 1.0 + 1.1) = (1.6, 1.2). Queen sits at (1.8, 1.15), with a cosine of 0.997 to v.
Pick an analogy and press Play. The teal arrows subtract and add; the green ring marks the nearest word.
Illustrative toy with two named axes, royalty and gender. Real Word2Vec vectors have 300 axes, and none has a clean name.
The trick is fragile. Standard analogy tests skip the three input words when they search. Without that rule, the answer can be one of the inputs. Measure it by running your analogies with and without the skip. Treat analogies as a picture of the geometry, not a guarantee.
Chapter 3
Compare two vectors three ways, and see when the three agree
You have two vectors. How close are they? Three measures are in common use. The dot product multiplies the vectors number by number and adds the results. Euclidean distance, also called L2 distance, is the straight-line gap between the two tips. Cosine similarity keeps only the angle.
Call the two vectors a and b. Write their dot product a · b, and the length of a vector, its norm, as ‖a‖.
Cos of a and b equals a dot b, divided by the norm of a times the norm of b.
Compute a dot b. Divide it by the norm of a and the norm of b. What is left depends only on the angle: 1 for the same direction, 0 for a right angle, −1 for opposite.
a = (3, 4) and b = (4, 3). a · b = 12 + 12 = 24. Both norms are 5. cos = 24 / 25 = 0.96. Double b to (8, 6): the dot product becomes 48, the cosine stays 0.96.
Teal is a, warm is b. Turn them, then stretch b. Watch which numbers move.
Exact geometry in two dimensions. a has length 1 here; the same rules hold in 1,536 dimensions.
Why ignore length? A vector's length can track things that are not topic, such as how common its words are. Cosine removes that. If you scale every vector to length 1 first, called normalizing, distance and cosine tell the same story.
The norm of a minus b, squared, equals two minus two cos of a and b, when a and b have length one.
Normalize a and b. Then the squared distance is 2 minus twice the cosine. A larger cosine always means a smaller distance, so both put results in the same order.
a = (0.6, 0.8) and b = (0.8, 0.6), both of length 1. ‖a − b‖2 = 0.22 + 0.22 = 0.08. And 2 − 2 × 0.96 = 0.08.
OpenAI's documentation says its embeddings come normalized to length 1. For such vectors cosine equals the dot product, and the dot product is cheaper to compute.
The failure: long or common texts win every search. Measure it by plotting each result's rank against its vector norm. The fix is to normalize before you store the vectors, or to compare by cosine.
Chapter 4
Merge many token vectors into one sentence vector, and train the encoder so that cosine on the result means something
Search needs one vector per text, not per word. “I sat on the bank of the river” and “I paid cash at the bank” use one word in two senses. The sentence decides which.
A transformer such as BERT reads the whole sentence and gives each token a contextual vector: the vector for “bank” now depends on its neighbours. To get one vector for the sentence, you pool the token vectors. Call the number of tokens n and the vector of token i hi.
s equals one over n, times the sum over i of h-i.
Add the n token vectors h-i number by number. Divide each total by n. The result is s, the mean pooled sentence vector.
With made-up numbers: dog = (0.8, 0.1, 0.3), bites = (0.2, 0.9, 0.1), man = (0.1, 0.2, 0.9). The sum is (1.1, 1.2, 1.3). Divide by n = 3: s = (0.37, 0.40, 0.43). “Man bites dog” has the same sum, so the same s.
Each row is one word's six numbers; the outlined row is their mean. Pick a pair and see what pooling keeps.
Illustrative toy with fixed word vectors, so order is lost by design. A transformer's token vectors depend on position, so its pooled vectors differ for the two orders, often only a little.
BERT was not trained to make vectors you compare by cosine. Reimers and Gurevych tested this in Sentence-BERT (2019). The score is how well cosine agrees with human similarity ratings, averaged over seven test sets.
| Sentence vector | Agreement with people (of 100) |
|---|---|
| BERT [CLS] token | 29.19 |
| Mean of BERT token vectors | 54.81 |
| Mean of GloVe word vectors | 61.32 |
| SBERT (BERT trained on sentence pairs) | 74.89 |
The fix is to train the encoder on sentence pairs. The result is a bi-encoder: one network encodes the query and each document separately. You embed every document once, offline. At query time you embed only the query. A cross-encoder reads query and document together: more accurate, but it runs once for every pair.
| Encoder | Sees | Cost for 1 query, 1 million docs | Use |
|---|---|---|---|
| Bi-encoder | one text at a time | 1 encoder pass, then a vector search | retrieve the top 100 |
| Cross-encoder | query and doc together | 1 million passes | rerank the top 100 |
The failure: a search built on raw BERT vectors returns neighbours that look random. Measure it on 50 sentence pairs that people have rated. The fix is a model trained for similarity; LLMs as Embedding Models shows the modern recipe.
Chapter 5
Teach an encoder which texts belong together by raising right pairs and lowering wrong ones
How does a bi-encoder learn that “reset password” goes with “change your login password”? From pairs. A positive pair is a query and a text that answers it. In a batch of such pairs, every other text is a negative for that query.
Embed the batch and score every query against every text by cosine. You get a square table. The right answers sit on the diagonal. Training raises the diagonal and lowers the rest.
Call the cosine between query i and text j sij. Call the temperature τ (tau): a small number that divides every score and so sharpens the choice.
L-i equals minus the natural log of: e to the s-i-i over tau, divided by the sum over j of e to the s-i-j over tau.
Divide each score in row i by tau and raise e to it. Divide the right text's value by the row total: that is the chance the model picks the right text. The loss L-i is minus the log of that chance.
With made-up scores 0.8 (right), 0.3 and 0.1, and tau = 0.1: e8 = 2,981, e3 = 20.1, e1 = 2.7. The chance is 2,981 / 3,004 = 0.992 and the loss is 0.008. With tau = 1 the same scores give a chance of 0.48 and a loss of 0.74.
This loss is called InfoNCE. It is a softmax over the row, scored like a multiple-choice test whose right answer is the diagonal.
Rows are queries, columns are texts; green cells are the right pairs. Press Train and watch the loss fall.
Toy. The device moves the scores along the loss gradient. A real encoder moves its weights, and the scores follow.
The same loss trains E5-Mistral (in LLMs as Embedding Models) and CLIP (Chapter 7). Contrastive Learning derives it in full.
The failure: two near-duplicate texts land in one batch, and the loss pushes them apart. Measure it by reading the highest-scoring negatives of a few batches. The fix is to remove duplicates before you batch.
Chapter 6
See why models use hundreds of numbers, what each one costs, and how Matryoshka vectors let you keep fewer
Real models use hundreds to thousands of numbers per vector. Each number is one dimension.
| Model | Dimensions | Source |
|---|---|---|
| Word2Vec (Google release) | 300 | Mikolov et al., 2013 |
| GloVe | 50 to 300 | Pennington et al., 2014 |
| Cohere embed-english-v3.0 | 1,024 | Cohere docs (light: 384) |
| BGE-large-en | 1,024 | BAAI model card |
| text-embedding-3-small | 1,536 | OpenAI docs |
| text-embedding-3-large | 3,072 | OpenAI docs |
| E5-Mistral-7B | 4,096 | Wang et al., 2024 |
Why so many? High dimensions give room. Pick two random directions in d dimensions. Their cosine clusters around 0, with a spread of about 1 divided by the square root of d: 0.71 in 2 dimensions, 0.036 in 768. Unrelated texts can sit near 0, and close meanings stand out.
Each bar counts random vector pairs with that cosine. Slide the dimensions up and watch the pile squeeze toward 0.
Exact simulation: 600 pairs of random Gaussian vectors, drawn in your browser. Memory assumes one million vectors of 32-bit floats.
Every dimension costs memory. Call the number of stored chunks N, the dimensions per vector d, and the bytes per number b.
Bytes equal N times d times b.
Multiply the number of vectors N by the dimensions d, then by the bytes per number b. That is the memory before the index adds its own structures.
One million chunks with text-embedding-3-small: 1,000,000 × 1,536 × 4 = 6.1 GB. Cut to d = 256: 1.0 GB.
Matryoshka Representation Learning (Kusupati and colleagues, 2022) trains a model so that the first few numbers of its vector also work alone. The vector nests smaller vectors, like nested dolls. OpenAI trained text-embedding-3 this way. Its dimensions parameter removes numbers from the end.
OpenAI reports that text-embedding-3-large cut to 256 numbers still beats the older ada-002 at its full 1,536 on the MTEB benchmark. If you cut a vector yourself, normalize it again before you use cosine as a dot product.
The failure: the index outgrows the machine's memory. Measure N × d × b before you build. The fix is fewer dimensions, 16-bit or 8-bit numbers, or both; Embedding Ops covers the trade-offs.
Chapter 7
Train an image encoder and a text encoder together, then label images by comparing them with captions
A shopper photographs a lamp and wants its product page. The photo is pixels and the page is text. To compare them, both must land in one space.
CLIP (Radford and colleagues, OpenAI, 2021) trains two encoders, one for images and one for text. It learns from 400 million image and caption pairs from the web. The loss is Chapter 5's contrastive loss. In each batch, each image must pick its own caption among all the captions, and each caption its own image.
After training, CLIP can sort images into classes it never trained on. Write each class as a caption: “a photo of a cat”, “a photo of a dog”, “a photo of a car”. Embed the image and the captions. Score each caption by cosine, divide by tau, and take the softmax from Chapter 5. The largest share wins.
With made-up cosines 0.30, 0.25 and 0.20, the captions look close. CLIP learns its temperature, and the paper caps 1/tau at 100. At tau = 0.01 the shares become 0.993, 0.007 and 0.000. A small cosine gap becomes a firm choice.
The pink arrow is the image; the warm arrows are captions. Turn the image and change tau.
Illustrative toy. Cosine = 0.15 + 0.15 × cos(angle gap), which keeps scores in CLIP's typical narrow band. The softmax and the cap of 1/tau at 100 follow the CLIP paper.
ImageBind (Girdhar and colleagues, Meta, 2023) extends the idea to six kinds of data: images, text, audio, depth, thermal and motion sensor (IMU) readings. It pairs each kind with images, and the other kinds line up through the shared image space.
The failure: in a mixed index, text-to-text scores beat every text-to-image score, so a text query returns only text. Measure the average cosine within and across the two kinds. The fix is to search one kind at a time; The Modality Gap explains why the gap exists.
Chapter 8
Spot the five quiet failures of embedding search, measure each, and fix it
Embedding search fails quietly. It still returns ten results; they are the wrong ten. Five failures cover most cases.
| Failure | Symptom | Measure | Fix |
|---|---|---|---|
| Jargon | product codes and in-house terms match nothing useful | hit rate on 50 labelled in-house queries | fine-tune on your pairs, or add keyword search |
| Negation | “not good” scores close to “good” | scores on a small set of negated pairs | rerank with a cross-encoder |
| Dilution | the answer hides in a long chunk and ranks low | rank of the right chunk against chunk length | shorter chunks |
| Stale vectors | search finds edited documents by their old text | compare a hash of each text with the hash stored at embed time | re-embed on change |
| Mixed models | scores make no sense after a model upgrade | check the model name stored with each vector | re-embed everything with one model |
Mixed models deserve one more line. Vectors from two models live in two unrelated spaces, so a cosine between them means nothing. Store the model name beside every vector.
Mean pooling averages everything in a chunk. Put one sentence that answers the query in a chunk with n unrelated sentences. Say each unrelated sentence points at a right angle to the rest. Then the cosine with the query falls to 1 divided by the square root of n + 1. That is 0.71 with one extra sentence and 0.33 with eight.
The green cell is the answer sentence; grey cells are filler. Add filler and watch the right chunk's score fall past the rival.
Illustrative toy in 64 dimensions with random filler vectors, so the score lands near, not on, 1 / √(n + 1). We made up the rival chunk's score of 0.45.
Negation is the other common trap. In the showcase's toy, “not” has a vector of zeros. So “the film was good” and “the film was not good” pool to the same vector. Real models do better than that, but they often still score such pairs high.
The working rule: retrieve the top 100 with a bi-encoder for speed. Then rerank them with a cross-encoder that reads query and text together. Text Chunking covers how to cut documents, and RAG shows the whole pipeline.
Chapter 9
Type a query, choose how texts become vectors and how to compare them, and watch the ranking change
Everything meets here. The engine holds the ten books from the hero. Each word in its small vocabulary has six hand-made numbers: suspense, romance, science, food, history and kids. A text's vector is the mean of its word vectors, as in Chapter 4.
Type a query or tap a chip. The map shows where the query lands; the bars rank the books.
Illustrative toy. A real model learns hundreds of unnamed dimensions; this one has six named ones that you can read. The query dot sits among the books it scores highest. The engine skips words outside its 89-word vocabulary, and the read-out lists them.
Five things to try:
Chapter 10
Keep the terms, the numbers, the checklist and the code in one place
An embedding model maps a text to a vector so that close meanings point the same way. You embed your documents once, store the vectors, embed each query, and return the documents with the highest cosine. Contrastive training on pairs makes the geometry work. Chunk size, normalization, the model name and a reranker decide whether it works for you.
| Term | Meaning | Number to remember |
|---|---|---|
| Embedding | a vector a model computes for an item | 300 to 4,096 numbers |
| TF-IDF | count times ln(N / df) | “a” in 7 of 10 books: 0.36 |
| Cosine | dot product divided by both norms | (3, 4) and (4, 3): 0.96 |
| Unit vectors | squared distance = 2 − 2 cos | 0.08 at cos 0.96 |
| Mean pooling | average of token vectors | loses word order for fixed vectors |
| SBERT | BERT trained on sentence pairs | 74.89 against 29.19 for [CLS] |
| InfoNCE | softmax loss over a batch row | tau 0.01 to 0.1 |
| Random cosine spread | about 1 / √d | 0.036 at d = 768 |
| Memory | N × d × b | 1M × 1,536 × 4 = 6.1 GB |
| CLIP | image and text in one space | 400M pairs, 1/tau capped at 100 |
| Dilution | answer averaged with filler | 1 / √(n + 1): 0.33 at n = 8 |
pythonimport numpy as np from sentence_transformers import SentenceTransformer model = SentenceTransformer("all-MiniLM-L6-v2") # a small bi-encoder docs = ["A nail-biting mystery that subverts expectations", "Weeknight recipes for busy families"] D = model.encode(docs, normalize_embeddings=True) # (N, d), each row length 1 def search(query, k=5): q = model.encode([query], normalize_embeddings=True)[0] # (d,) scores = D @ q # cosine, because rows are unit length top = np.argsort(-scores)[:k] return [(docs[i], float(scores[i])) for i in top] print(search("gripping thriller with a twist ending"))
Now press Present or Teach. Explain from memory why counts miss synonyms, what cosine keeps, how contrastive loss shapes the space, and the five failures. Then go back to the hero and say why each book moved when you switched methods.