Vector Embeddings

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.

Search ten books two ways

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

Search by Meaning, Not by Spelling

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.”

Tap a book, find its neighbours

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.

The road

  1. Counting words: one-hot vectors, bags of words and TF-IDF, and why they miss synonyms.
  2. Dense vectors: Word2Vec, the embedding table and arithmetic on meaning.
  3. Measuring closeness: dot product, cosine and distance.
  4. Sentences: pooling, Sentence-BERT, bi-encoders and cross-encoders.
  5. Contrastive training: the loss that teaches a model what “similar” means.
  6. Dimensions: why hundreds of numbers, what they cost, and Matryoshka.
  7. Images and text: CLIP and zero-shot labels.
  8. Failures: negation, dilution, jargon, stale and mixed vectors.
  9. The showcase: a tiny search engine you control.
  10. The field guide: numbers, checklist, code and links.
Why does keyword search give “A nail-biting mystery that subverts expectations” a score of 0 for the query “gripping thriller with a twist ending”?

Chapter 1

Words to Numbers: One-Hot, Counts and TF-IDF

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.

Count the words, compare the rows

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.

TF-IDF: weigh the rare words up

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.

Say it aloud

T-F-I-D-F of w and d equals t-f times the natural log of N over d-f.

tfidf(w, d)
T-F-I-D-F of w and d the weight of word w in document d.
tf
t-f term frequency: how many times w appears in d.
ln
the natural log the log to base e. It grows slowly, so a rare word gets more weight but not without limit.
N
N the number of documents in the collection.
df
d-f document frequency: how many documents contain w at least once.
In plain words

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.

With numbers

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.

MethodWhat it capturesWhat breaks
Integer IDnothinga false order and false distances
One-hotidentity onlyevery pair is equally far apart
Bag of wordsshared wordssynonyms, negation, word order
TF-IDFshared rare wordsstill 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.

Why does one-hot encoding fail to show that “king” and “queen” are related?

Chapter 2

Dense Vectors Learned from Context

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 embedding table

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)

Arithmetic on meaning

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.

Say it aloud

v equals e-king minus e-man plus e-woman.

v
v the target point we search around.
eking
e-king the table row for “king”.
−
minus subtract number by number.
eman
e-man the row for “man”.
+
plus add number by number.
ewoman
e-woman the row for “woman”.
In plain words

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.

With numbers

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.

Walk an analogy with arrows

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.

How does Word2Vec learn that “dog” and “puppy” are close?

Chapter 3

Measuring Closeness: Dot, Cosine and Distance

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‖.

Say it aloud

Cos of a and b equals a dot b, divided by the norm of a times the norm of b.

cos(a, b)
cos of a and b the cosine of the angle between a and b, from −1 to 1.
a · b
a dot b multiply matching numbers and add the products.
‖a‖
the norm of a the length of a: the square root of a dot a.
‖b‖
the norm of b the length of b.
In plain words

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.

With numbers

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.

Turn and stretch two vectors

Teal is a, warm is b. Turn them, then stretch b. Watch which numbers move.

53°
37°
1.0

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.

Say it aloud

The norm of a minus b, squared, equals two minus two cos of a and b, when a and b have length one.

‖a − b‖2
the norm of a minus b, squared the squared L2 distance between the tips.
2
two a dot a plus b dot b, which is 1 + 1 for unit vectors.
cos(a, b)
cos of a and b the cosine from the first equation; for unit vectors it equals a dot b.
In plain words

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.

With numbers

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.

You double the length of vector b. What happens?

Chapter 4

From Words to Sentences: Pooling and Bi-Encoders

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.

Say it aloud

s equals one over n, times the sum over i of h-i.

s
s the sentence vector, as long as one token vector.
n
n the number of tokens in the sentence.
Σi
the sum over i add one term for each token, i from 1 to n.
hi
h-i the vector the encoder gives token i.
In plain words

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 numbers

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.

Pool two sentences and compare

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.

Raw BERT is not enough

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 vectorAgreement with people (of 100)
BERT [CLS] token29.19
Mean of BERT token vectors54.81
Mean of GloVe word vectors61.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.

EncoderSeesCost for 1 query, 1 million docsUse
Bi-encoderone text at a time1 encoder pass, then a vector searchretrieve the top 100
Cross-encoderquery and doc together1 million passesrerank 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.

Why can a bi-encoder search a million documents fast?

Chapter 5

Training for Similarity: Contrastive Loss

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.

Say it aloud

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.

Li
L-i the loss for query i. Training lowers it.
−ln
minus the natural log near 0 when the chance is near 1, large when the chance is small.
e
e to the e = 2.718 raised to a power. It keeps every term positive.
sii
s-i-i the score of query i with its own text: the diagonal.
τ
tau the temperature, often 0.01 to 0.1.
Σj
the sum over j add one term for every text in the batch, the right one included.
sij
s-i-j the score of query i with text j.
In plain words

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 numbers

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.

Train a batch of four pairs

Rows are queries, columns are texts; green cells are the right pairs. Press Train and watch the loss fall.

0.1

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.

In a batch of 32 pairs, what are the negatives for query 5?

Chapter 6

How Many Numbers: Dimensions and Memory

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.

ModelDimensionsSource
Word2Vec (Google release)300Mikolov et al., 2013
GloVe50 to 300Pennington et al., 2014
Cohere embed-english-v3.01,024Cohere docs (light: 384)
BGE-large-en1,024BAAI model card
text-embedding-3-small1,536OpenAI docs
text-embedding-3-large3,072OpenAI docs
E5-Mistral-7B4,096Wang 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.

Add dimensions, watch random pairs spread out

Each bar counts random vector pairs with that cosine. Slide the dimensions up and watch the pile squeeze toward 0.

32

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.

Say it aloud

Bytes equal N times d times b.

bytes
bytes the memory for the raw vectors, before any index overhead.
N
N the number of stored vectors, one per chunk.
d
d the dimensions per vector.
b
b bytes per number: 4 for a 32-bit float, 2 for 16-bit.
In plain words

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.

With numbers

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: one vector, many sizes

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.

You store 2 million vectors of 1,024 numbers as 16-bit floats. About how much memory do the raw vectors need?

Chapter 7

Images and Text in One Space

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.

Zero-shot labels

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.

Turn the image, read the labels

The pink arrow is the image; the warm arrows are captions. Turn the image and change tau.

50°

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.

How does CLIP label an image as “dog” with no dog classifier?

Chapter 8

When Embeddings Fail

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.

FailureSymptomMeasureFix
Jargonproduct codes and in-house terms match nothing usefulhit rate on 50 labelled in-house queriesfine-tune on your pairs, or add keyword search
Negation“not good” scores close to “good”scores on a small set of negated pairsrerank with a cross-encoder
Dilutionthe answer hides in a long chunk and ranks lowrank of the right chunk against chunk lengthshorter chunks
Stale vectorssearch finds edited documents by their old textcompare a hash of each text with the hash stored at embed timere-embed on change
Mixed modelsscores make no sense after a model upgradecheck the model name stored with each vectorre-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.

Dilution, measured

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.

Bury the answer in filler

The green cell is the answer sentence; grey cells are filler. Add filler and watch the right chunk's score fall past the rival.

3

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.

A 40-sentence chunk holds the answer in one sentence and ranks below a short, half-related chunk. What is the likely cause and fix?

Chapter 9

Build a Tiny Search Engine

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.

Search ten books your way

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:

  1. Type “scary spy” in Keyword mode. Only books that share a word score.
  2. Switch to Embedding. The detective and the mystery rise, with no shared word.
  3. Tap “not good”. “Not” is all zeros here, so the query means “good”: the negation failure of Chapter 8.
  4. Switch to Dot product. Books whose vectors are longer climb. Cosine and L2 agree more often.
  5. Type a word the engine does not know, such as “zeppelin”. The engine skips it: the jargon failure.
In the engine, why does “the film was not good” rank books like the query “the film was good” would?

Chapter 10

Field Guide

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.

Terms and numbers

TermMeaningNumber to remember
Embeddinga vector a model computes for an item300 to 4,096 numbers
TF-IDFcount times ln(N / df)“a” in 7 of 10 books: 0.36
Cosinedot product divided by both norms(3, 4) and (4, 3): 0.96
Unit vectorssquared distance = 2 − 2 cos0.08 at cos 0.96
Mean poolingaverage of token vectorsloses word order for fixed vectors
SBERTBERT trained on sentence pairs74.89 against 29.19 for [CLS]
InfoNCEsoftmax loss over a batch rowtau 0.01 to 0.1
Random cosine spreadabout 1 / √d0.036 at d = 768
MemoryN × d × b1M × 1,536 × 4 = 6.1 GB
CLIPimage and text in one space400M pairs, 1/tau capped at 100
Dilutionanswer averaged with filler1 / √(n + 1): 0.33 at n = 8

Checklist before you ship embedding search

  1. Pick a model trained for similarity, and record its name with every vector.
  2. Normalize the vectors, then use the dot product as cosine.
  3. Cut documents into chunks of a few hundred tokens.
  4. Compute N × d × b; cut dimensions or bytes if it does not fit.
  5. Label 50 real queries and measure how often the right chunk lands in the top 10.
  6. Rerank the top results with a cross-encoder.
  7. Store a hash of each text; re-embed when it changes.

The core, in code

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"))

Keep going

Sources

The one idea. An embedding is a position that a model learned from pairs of things that belong together. Search is measuring angles between positions, and every failure is a case where the angle and the meaning part.

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.

Vector Embeddings
Back to Gleams