BEGINNERCHAPTER 07

Embeddings and similarity

A learned vector where distance means meaning: how embeddings are trained, which distance to use, and the four ways cosine similarity lies to you

50 MINAI ENGINEERINGUPDATED 2026-11-02
PREDICT

You embed 'The battery lasts all day' and 'The battery does not last all day' with a modern sentence-embedding model and compute cosine similarity. Roughly what do you get?

An embedding is a list of numbers that stands in for a piece of text. That sounds like nothing until you add the one property that matters: the model that produced the list was trained so that texts with similar meaning produce lists that are close together. Distance in this space is a stand-in for meaning. Every retrieval system you build in this course, and most recommendation and deduplication systems you will meet, rest on that stand-in. It is useful and it is imperfect in specific, predictable ways. This chapter is about both.

What an embedding is

Take a model and a piece of text. Run the text through the model and, instead of asking for the next token, read out a vector from somewhere inside the network, usually the last hidden layer, pooled across tokens into one fixed-length vector. For nomic-embed-text that vector has 768 numbers; for mxbai-embed-large, 1024; for OpenAI’s text-embedding-3-large, 3072. Each number on its own means nothing. The vector as a whole is a point in a space with hundreds of dimensions, and the useful statement is about pairs of points: two texts the model considers similar are close, two it considers unrelated are far apart.

Nobody designed the axes. There is no dimension for ‘colour’ or ‘price’. The geometry was learned from training data by a loss function that rewarded putting related things together and unrelated things apart. That has two consequences you should carry for the rest of the course. First, ‘similar’ means whatever the training data said it meant, and that is rarely the same as what your application means. Second, the coordinate system is a property of that one model. Two models produce two unrelated spaces, even if the vectors happen to have the same length.

A quick way to make this concrete: embed a few sentences and print the cosine similarity between each pair. ‘A dog chased the ball’ and ‘The puppy ran after the toy’ score high, perhaps 0.8, despite sharing no words. ‘A dog chased the ball’ and ‘Quarterly revenue fell by 4%’ score low, perhaps 0.1. That is the whole promise, and it is a real one: keyword search cannot match ‘puppy’ to ‘dog’. The lab does this against a product catalogue.

From word2vec to retrieval models

The idea is older than transformers. word2vec (Mikolov et al., 2013) trained a shallow network to predict a word from its neighbours, or the neighbours from a word, and the weights it learned were a vector per word. Those vectors had the famous arithmetic: king - man + woman lands near queen. But a word has one vector regardless of context, so ‘bank’ in ‘river bank’ and ‘bank account’ are the same point, and a sentence was at best the average of its words, which throws away order and structure.

Sentence-BERT (Reimers and Gurevych, 2019) changed the training objective. Take a pretrained BERT, run two sentences through it in a Siamese setup, pool each into one vector, and train on pairs labelled as entailing, contradicting or neutral so that the vectors of related sentences come together. The paper’s headline number: finding the most similar pair among 10,000 sentences by running BERT on every pair takes about 65 hours; with SBERT you embed each sentence once and compare vectors, about 5 seconds. That gap is why every retrieval system embeds documents ahead of time and compares vectors at query time rather than running a model over every candidate.

Modern retrieval embeddings (E5, BGE, GTE, nomic-embed, mxbai, Voyage, OpenAI’s text-embedding-3 series) push the same idea further with contrastive training at scale. The data is hundreds of millions of (query, relevant passage) pairs mined from the web, search logs, question-answer sites and synthetic generation. The loss, usually InfoNCE, takes a query, its matching passage, and a batch of non-matching passages, and pushes the query towards the match and away from the rest. ‘Hard negatives’, passages that look relevant but are not, sharpen the boundary. The result is a model whose notion of ‘similar’ is specifically ‘would this passage answer that query’, which is what retrieval needs and which is different from ‘do these two sentences mean the same thing’.

Hold onto that last point. A model trained on query-passage pairs will put ‘what is the return policy’ near a paragraph about returns. It will also put ‘the battery does not last all day’ near ‘the battery lasts all day’, because nothing in its training data ever punished that.

Measuring distance

Once you have two vectors, you need a number for how close they are. There are three in common use, and the differences matter less than people fear once you know one fact about your model.

measure formula range what it measures
cosine similarity a·b / (‖a‖ ‖b‖) -1 to 1 (higher is closer) angle between the vectors, ignoring length
dot product (inner product) a·b unbounded angle and length together; long vectors score higher
Euclidean (L2) distance ‖a − b‖ 0 to ∞ (lower is closer) straight-line distance

Cosine ignores magnitude, so a long document and a short query about the same thing can still score high. Dot product rewards magnitude, which some models exploit deliberately by giving confident or information-dense texts longer vectors; it is also the cheapest to compute, one multiply-add per dimension. Euclidean is the geometric default and the one most ANN index libraries were first built around.

The fact that collapses the choice: most retrieval models, including nomic-embed-text, mxbai-embed-large, the Voyage models and OpenAI’s, output vectors normalised to length 1. For unit vectors, cosine similarity equals the dot product, and Euclidean distance is a monotonic function of both (‖a − b‖² = 2 − 2 a·b). All three give the same ranking. Pick dot product if you want speed, cosine if you want a number that is readable (a similarity of 0.82 means something; a dot product of 0.82 only means something if you know the vectors are normalised), and check the model card before assuming normalisation. If a model’s vectors are not normalised and you use Euclidean, two long vectors about the same topic can be further apart than two short vectors about different topics.

In pgvector the operators are <=> for cosine distance (which is 1 − cosine similarity, so lower is closer), <#> for the negative inner product (negative because Postgres index scans only sort ascending, so multiply by −1 to get the real value), and <-> for L2. There are matching operator classes for indexes: vector_cosine_ops, vector_ip_ops, vector_l2_ops. Use the one that matches your query operator or the index is not used.

One more thing about the number itself. Cosine similarity is not a probability and not a percentage. Scores from one model are not comparable with scores from another; one model’s ‘unrelated’ baseline might sit at 0.3 and another’s at 0.7. A threshold such as ‘only return results above 0.8’ is a per-model constant that you tune against your own data, never a universal setting.

Dimensions and Matryoshka embeddings

More dimensions store more information, at a cost: a 3072-dimensional float32 vector is 12 KB, so a million documents are 12 GB of vectors before any index. Storage, memory and comparison time scale linearly with dimensions. 768 dimensions for a million documents is 3 GB; 256 dimensions is 1 GB.

Until recently you picked a model and accepted its dimensionality. Matryoshka Representation Learning (Kusupati et al., 2022) trains a model so that the first k dimensions of the vector are themselves a good embedding for several values of k. The loss is applied to the truncated prefixes as well as the full vector, so the most important information is pushed into the leading dimensions, like the nested dolls the technique is named after. You can then store 256 of the 768 dimensions, lose a few points of retrieval quality, and cut storage and compare time by two thirds. nomic-embed-text v1.5 is trained this way and documents the trade-off: on the MTEB benchmark it scores 62.3 at 768 dimensions and 56.1 at 64. OpenAI’s text-embedding-3 models expose this as a dimensions request parameter; Voyage’s 4-series models offer 2048, 1024, 512 and 256 through output_dimension.

If you truncate a vector yourself, re-normalise it afterwards: the first 256 dimensions of a unit vector are not a unit vector. Providers that accept a dimensions parameter do this for you.

The practical rule: start at the model’s default. Truncate only when you have measured retrieval quality on your own queries and know what you lose. Dimensions are cheap compared with a search that returns the wrong document.

Symmetric and asymmetric models

A symmetric model treats both sides of a comparison the same. Use it for sentence-to-sentence tasks: deduplication, clustering, finding paraphrases. An asymmetric model knows that the two sides are different in kind: a query is a short, often ungrammatical question, and a document is a long passage that answers it. Retrieval is asymmetric.

Asymmetric models implement the distinction with a prefix or an instruction that you must add to the text before embedding. For nomic-embed-text the prefixes are search_query: for queries and search_document: for the passages you index (there are also clustering: and classification: ). For mxbai-embed-large, queries get the prompt Represent this sentence for searching relevant passages: and documents get nothing. Voyage exposes the same idea as an input_type parameter with values query and document, and prepends the prompt server-side. E5 uses query: and passage: .

This matters more than it looks. The Ollama library page for nomic-embed-text does not mention prefixes at all, and a learner who copies the quick-start embeds queries and documents the same way. The model still works, in the sense that it returns vectors and nearest neighbours look plausible. It works measurably worse than it should, and nothing tells you. Read the model card, not the quick start, for every embedding model you adopt. The lab has you drop the prefix and watch the neighbours shift.

What similarity gets wrong

Here is the list to keep next to any system that uses embeddings for retrieval. Each of these is a direct consequence of how the models are trained, so switching to a bigger model moves the numbers a little and fixes none of them.

Negation. ‘The jacket is waterproof’ and ‘The jacket is not waterproof’ typically score above 0.9. The model was trained to pull together texts about the same thing, and both are about the jacket’s waterproofing. A user searching ‘laptops without a touchscreen’ will get touchscreen laptops near the top. If your domain has meaningful negation (medical records, legal clauses, product filters), handle it with structured filters or a reranker that reads both texts together, not with embedding distance.

Numbers. ‘2 TB hard drive’ and ‘4 TB hard drive’ are near-identical to an embedding model; the digit is one token among many and carries little semantic weight in the training data. The same goes for dates, versions, dosages, prices and quantities. ‘Python 3.8’ and ‘Python 3.12’ are one point. If a number matters to the answer, extract it and filter on it as a column. Embeddings are for the fuzzy part of the query, not the exact part.

Antonyms. ‘cheap’ and ‘expensive’ appear in the same contexts (prices, products, comparisons), and models trained on context put them close together. Often closer than a true synonym pair phrased differently. ‘Affordable running shoes’ can score higher against ‘premium running shoes’ than against ‘budget trainers’. Sentiment and polarity are weakly represented in retrieval embeddings because retrieval training does not need them.

Domain shift. A general model has seen a lot of web text and little of your internal jargon. Product codes, your company’s acronyms, drug names, legal terms of art: the model has weak or no representations for them, so it falls back on surface features like string overlap. The symptom is retrieval that works on the demo questions and fails on the long tail of real ones. The fixes, in increasing cost, are: hybrid search that combines a keyword index with the vector index (so an exact code match still wins), a domain-specific model (Voyage ships finance, law and code variants), and fine-tuning on your own query-document pairs. Module A3’s chapter on RAG covers hybrid search and reranking because these failures are the reason it exists.

There is a fifth, quieter one. Length. A single-sentence query against a 500-word chunk compares two things with different amounts of information, and the chunk’s vector is an average of everything in it. A chunk that answers the question in one sentence and spends the other 490 words on something else can score lower than a chunk that mentions the topic in general throughout. Chunking strategy is part of retrieval quality, which is why the project chapter next makes you chunk naively and measure the damage.

Versioning: you cannot mix models

Every model defines its own space. nomic-embed-text and mxbai-embed-large both place ‘running shoes’ at some point, but the two points have nothing to do with each other, and the vectors are not even the same length (768 and 1024). Two models of the same dimensionality are no better: the axes mean different things. Cosine similarity between a vector from model A and a vector from model B is a random number.

That makes the embedding model a schema decision. The failure in the Why above, half the index on one model and half on another, happens when a deployment rolls the model forward and re-embeds new documents without re-embedding old ones. The queries, embedded with the new model, match the new half and return noise from the old half. There is no error. Retrieval quality drops and nobody knows why until someone notices the model name changed.

The discipline is this: store the model identifier next to every vector, in a column or in the table name. Give the column a fixed dimensionality (vector(768)), so that a vector from the wrong model fails loudly on insert. When you change models, re-embed the whole corpus into a new table or column, switch queries over atomically, then drop the old one. Treat a provider deprecating a model as a migration with a deadline, not a config change. Pin exact model versions where the provider offers them. The data-pipelines chapter in module A4 covers doing this without downtime; today, you build the habit.

The same logic applies within a model when the input changes. Chunks embedded with the search_document: prefix and chunks embedded without it are in slightly different places. Normalisation, truncation to a Matryoshka dimension, and even the text-cleaning you run before embedding are all part of the version. Change any of them and re-embed.

What comes next

Embeddings give you a fast, fuzzy, language-aware way to find candidate documents. They do not read. The pattern for the rest of the course is: use the vector to find twenty candidates, then use something that reads, a reranker or the language model itself, to decide which five matter and what they say. The project chapter builds the first half of that pipeline on purpose without the second, so you can see what breaks.

LAB Embed the catalogue and watch cosine lie ~35 MIN
YOU NEEDDocker with the labs/databases stack running (docs/LABS.md)Ollama installed and running (ollama.com), about 300 MB of disk for the modelPython 3.12 with uv15 minutes of CPU time for the embedding step on a laptop without a GPU

You will embed a 5,000-product sample of the shop catalogue with a local model, store the vectors in Postgres with pgvector, run nearest-neighbour queries, then measure three cases where similarity and meaning come apart. Everything runs locally; there is no API cost.

1. Enable pgvector in the shop database.

The shop’s db service runs pgvector/pgvector:pg17: Postgres 17 with the pgvector extension available but not enabled, which the Databases course uses as plain Postgres. If your container was created from an older checkout whose compose.yaml said postgres:17, the up below recreates it on the new image and keeps the data volume. Enable the extension:

cd labs/databases
docker compose up -d db
docker compose exec db psql -U atlas shop -c "CREATE EXTENSION IF NOT EXISTS vector;"
docker compose exec db psql -U atlas shop -c "SELECT extversion FROM pg_extension WHERE extname = 'vector';"
CREATE EXTENSION then a version such as 0.8.0 or later. Your shop data is untouched: pgvector is an extension on top of the same Postgres 17, in the same volume. If the first command says the extension is not available, the container is still on the old image; check that docker compose ps shows pgvector/pgvector:pg17 and run docker compose up -d db again.

2. Pull the embedding model and check what it returns.

ollama pull nomic-embed-text
curl -s http://localhost:11434/api/embed -d '{"model":"nomic-embed-text","input":["search_query: running shoes"]}' | python3 -c "import json,sys; e=json.load(sys.stdin)['embeddings'][0]; print(len(e), e[:3])"
768 [0.0123, -0.0456, ...]: one vector of 768 floats. Note the search_query: prefix in the input. nomic-embed-text is an asymmetric model and its model card requires search_query: on queries and search_document: on the texts you index. The Ollama library page does not mention this; the model card on Hugging Face does.

3. Create the project and the table.

Work in a new directory, for example labs/ai/embeddings/:

From the root of your checkout (the labs/ai uv project comes from the first chapter’s lab):

mkdir -p labs/ai/embeddings && cd labs/ai/embeddings
uv add ollama "psycopg[binary]"

Create the table. The model column and the fixed vector(768) width are the versioning discipline from the chapter: a vector from a different model fails on insert instead of silently polluting the index.

docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop <<'SQL'
CREATE TABLE IF NOT EXISTS product_embeddings (
  product_id bigint PRIMARY KEY,   -- a products.id; no foreign key, so the shop's load.sql can still truncate products
  model      text NOT NULL,
  content    text NOT NULL,
  embedding  vector(768) NOT NULL
);
SQL
CREATE TABLE. No index yet: 5,000 rows is small enough for an exact scan, and the vector-indexes chapter in module A3 is where you add HNSW and measure what it costs in recall.

4. Embed 5,000 products.

Create embed.py. It samples 5,000 products, builds one text per product from the name and category, embeds in batches of 64 with the search_document: prefix, and inserts the vectors as pgvector literals. Vectors are passed as '[0.1,0.2,...]'::vector, which is the text form pgvector accepts, so no extra adapter is needed.

import os, ollama, psycopg, time

MODEL = "nomic-embed-text"
DSN = os.environ.get("SHOP_DSN", "postgres://atlas:atlas@localhost:5432/shop")

def to_vec(v):
    return "[" + ",".join(f"{x:.7f}" for x in v) + "]"

with psycopg.connect(DSN) as conn:
    rows = conn.execute(
        "SELECT id, name, category FROM products ORDER BY random() LIMIT 5000"
    ).fetchall()
    t0 = time.perf_counter()
    for i in range(0, len(rows), 64):
        batch = rows[i:i + 64]
        texts = [f"{name} ({category})" for _, name, category in batch]
        res = ollama.embed(model=MODEL, input=[f"search_document: {t}" for t in texts])
        with conn.cursor() as cur:
            cur.executemany(
                "INSERT INTO product_embeddings (product_id, model, content, embedding) "
                "VALUES (%s, %s, %s, %s::vector) ON CONFLICT (product_id) DO NOTHING",
                [(pid, MODEL, text, to_vec(vec))
                 for (pid, _, _), text, vec in zip(batch, texts, res["embeddings"])],
            )
        conn.commit()
        print(f"{i + len(batch)}/{len(rows)}", end="\r")
    print(f"\nembedded {len(rows)} products in {time.perf_counter() - t0:.0f}s")
uv run embed.py
A counter climbing to 5000/5000, then embedded 5000 products in 90s or so: one to three minutes on a laptop CPU, 15 to 30 seconds with a GPU. Each batch of 64 short strings is one request to Ollama. Check the row count and size: SELECT count(*), pg_size_pretty(pg_total_relation_size('product_embeddings')) FROM product_embeddings; gives 5,000 rows and about 16 MB, which is the 768 × 4 bytes per vector plus row overhead that the chapter’s arithmetic predicts.

5. Nearest neighbours.

Create search.py. It embeds the query with the search_query: prefix and orders by cosine distance; 1 - (embedding <=> q) turns the distance back into a similarity you can read.

import os, sys, ollama, psycopg

DSN = os.environ.get("SHOP_DSN", "postgres://atlas:atlas@localhost:5432/shop")
MODEL = "nomic-embed-text"

def to_vec(v):
    return "[" + ",".join(f"{x:.7f}" for x in v) + "]"

def search(q, k=5, prefix="search_query: "):
    vec = to_vec(ollama.embed(model=MODEL, input=[prefix + q])["embeddings"][0])
    with psycopg.connect(DSN) as conn:
        return conn.execute(
            "SELECT p.name, p.category, 1 - (e.embedding <=> %s::vector) AS sim "
            "FROM product_embeddings e JOIN products p ON p.id = e.product_id "
            "ORDER BY e.embedding <=> %s::vector LIMIT %s",
            (vec, vec, k),
        ).fetchall()

if __name__ == "__main__":
    for name, category, sim in search(" ".join(sys.argv[1:])):
        print(f"{sim:.3f}  {name}  [{category}]")

Pick a category from SELECT DISTINCT category FROM products LIMIT 10; and describe it in words the catalogue does not use, then run:

uv run search.py something you would wear on a cold day
Five products, similarities roughly between 0.55 and 0.75, mostly from one or two related categories, none of which share a word with your query. That is the thing keyword search cannot do. Now try a query that is a product name from the table verbatim: it comes back at the top with a similarity near 0.9, and the gap between first and second is small. Embedding scores compress; the ranking is more trustworthy than the absolute number.

6. Three ways cosine lies.

Create lies.py. It embeds sentence pairs with the same prefix (symmetric comparison, since these are sentence-to-sentence) and prints cosine similarity, computed as a dot product because nomic’s vectors are unit length.

import ollama

MODEL = "nomic-embed-text"

def sim(a, b):
    e = ollama.embed(model=MODEL, input=[f"search_document: {a}", f"search_document: {b}"])["embeddings"]
    return sum(x * y for x, y in zip(e[0], e[1]))

cases = {
    "negation": [("This jacket is waterproof.", "This jacket is not waterproof."),
                 ("This jacket is waterproof.", "This jacket keeps the rain out.")],
    "numbers":  [("External hard drive, 2 TB, USB-C", "External hard drive, 4 TB, USB-C"),
                 ("External hard drive, 2 TB, USB-C", "Two terabyte portable drive with USB-C")],
    "antonyms": [("affordable running shoes", "expensive running shoes"),
                 ("affordable running shoes", "budget trainers")],
}
for name, pairs in cases.items():
    print(name)
    for a, b in pairs:
        print(f"  {sim(a, b):.3f}  {a!r} vs {b!r}")
uv run lies.py
Numbers vary by model version, but the shape is stable. Negation: the sentence and its negation score around 0.90, higher than or equal to the sentence and its true paraphrase. Numbers: 2 TB versus 4 TB scores around 0.95, higher than 2 TB versus the paraphrase that says ‘two terabyte’; the model cannot tell the drives apart but can be thrown by spelling the number out. Antonyms: ‘affordable’ versus ‘expensive’ running shoes scores in the high 0.80s, above or close to ‘affordable running shoes’ versus ‘budget trainers’, which means the same thing. In every case the pair that differs in meaning scored at least as high as the pair that differs in wording. Write these three numbers down; the project chapter asks you to find the same failures in a real question set.

7. The prefix matters.

Run the same search twice, once with the correct query prefix and once with none:

uv run python -c "
from search import search
q = 'something you would wear on a cold day'
for prefix in ('search_query: ', ''):
    print(repr(prefix)); [print(f'  {s:.3f} {n}') for n, c, s in search(q, prefix=prefix)]
"
The two lists overlap but differ in order, and the similarities without the prefix are shifted, often higher across the board, because the query vector is now in the ‘document’ region of the space and is closer to everything. The model did not error. It returned plausible results that are measurably worse at scale. This is the asymmetric-model trap, and the only defence is reading the model card.
Pull mxbai-embed-large (ollama pull mxbai-embed-large), change MODEL in search.py to it, and search again. Postgres refuses: expected 768 dimensions, not 1024. That error is the fixed-width column doing its job, and it is the good outcome. Now imagine both models were 768-dimensional: the insert would succeed, the query would return five products with confident-looking similarities, and every one of them would be noise, because the two models’ coordinate systems have nothing to do with each other. To use mxbai, you create a product_embeddings_mxbai table with vector(1024), re-embed all 5,000 rows (mxbai takes no prefix on documents and Represent this sentence for searching relevant passages: on queries, a different convention from nomic), and point queries at the new table. That is the migration you will run for real when a provider deprecates a model.
ARTEFACT Write the similarity-threshold decision record ~45 MIN
YOU PRODUCEA similarity-threshold decision record

Template

# Decision record: similarity threshold for <use>
Owner: <name or role>. Approver: <name or role>. Date: <date>. Status: <proposed | accepted>.

## 1. Decision needed
<What the threshold controls, who is affected, decide by when.>

## 2. Setup the threshold belongs to
Model: <name and version>. Prefixes: <query / document>. Vectors normalised: <yes | no>. Measure: <cosine>.

## 3. Labelled pairs
| Pair | Score | Judged the same? | Source |
Sample size: <n pairs>, labelled by <who>. Pairs that differ by number or negation listed separately.

## 4. Cost of each error
- False match (score above threshold, not the same): <what happens, cost>
- Missed match (score below threshold, the same): <what happens, cost>

## 5. Chosen threshold
<value>, and why that value over the neighbours on either side. What it does not catch: <...>

## 6. How this could be wrong
<One way, and what would show it.>

## 7. Revisit
Review on <date>, or earlier if <model change, new content type, complaint rate above x>. Rollback: <how to return to the previous value>. Out of scope: <...>
WORKED EXAMPLE

The head of search at the shop writes this record, and the head of engineering approves it; it is dated 20 November 2026 and the decision is needed by the end of the month. The use is flagging near-duplicate products in the 5,000-product sample from the lab, with nomic-embed-text (768 dimensions), the search_document: prefix on both sides, unit-length vectors and cosine similarity.

Labelled pairs, using the lab’s printed scores. ‘External hard drive, 2 TB, USB-C’ against the 4 TB version scores around 0.95, and the people reviewing it (labels assumed for this example) judged them different products. ‘This jacket is waterproof.’ against ‘This jacket is not waterproof.’ scores around 0.90, different. ‘affordable running shoes’ against ‘expensive running shoes’ scores in the high 0.80s, different. A verbatim product name used as a query scores near 0.9, the same. The lab does not print scores for the paraphrase pairs, so the record lists them as unscored and the first task is to run them.

Cost, both assumed: a false match hides a product from shoppers until someone notices; a missed match leaves a duplicate that costs a reviewer about a minute.

Chosen: no automatic merging at any score, because three different-meaning pairs already score from the high 0.80s to 0.95. A score of 0.90 or above only puts a pair in a review queue, and size, capacity and negation are compared as columns first.

Could be wrong: 0.90 comes from three pairs, not a sample. A reviewer rejecting more than half the queue would show it.

Revisit in three months, and at once if the model changes, since scores are per model.

Now you

You work in support operations at Wrenpost, the messaging API company with about 12 people in support and about 2,400 business customers. The help centre is about to suggest an article while a customer types a ticket, and the suggestion appears only when the best article scores above a threshold. A threshold set too low shows wrong articles; set too high, customers see nothing and still file the ticket.

Reuse the lab’s outputs where they apply: the 0.55 to 0.75 similarities for a plain-words query, the near 0.9 score for a verbatim match, and the negation pair around 0.90, which warns you that ‘turn on two-factor’ and ‘turn off two-factor’ will look alike. Assume, and say so, how many tickets a day the widget sees and what a deflected ticket saves. Label at least ten query and article pairs yourself.

The decision is needed before the widget goes to a pilot group of customers. Assume the widget uses the lab’s model, so state its prefixes and whether the vectors are normalised. Write the record for the head of support, who approves it, and the engineer who will set the value.

Self-check

DECIDE

You own search for the shop: 50,000 products, queries are short ('red 2m usb-c cable', 'warm jacket mens xl'), half of them contain a size, length, quantity or colour, and the current keyword search misses synonyms ('trainers' never finds 'running shoes'). Latency budget 200 ms. Which approach do you build first?

READING
  1. PAPER
    Efficient Estimation of Word Representations in Vector Space Mikolov, Chen, Corrado, Dean, 2013

    The word2vec paper: where 'distance means meaning' came from, and the king/queen arithmetic. Read for the idea and the training objective; the evaluation sections are of historical interest. Read: sections 1 to 3 and the analogy examples in section 4.

  2. PAPER
    Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks Reimers and Gurevych, 2019

    The step from word vectors to sentence vectors you can compare with cosine, and the 65-hours-to-5-seconds argument for embedding once and comparing many times. Skip the ablations on pooling strategy unless you are training your own. Read: sections 1 to 3; table 1 for the numbers.

  3. PAPER
    Matryoshka Representation Learning Kusupati et al., 2022

    Why you can truncate a modern embedding to its first 256 dimensions and keep most of the quality, and what the training trick is. The introduction and figure 1 give you the idea in ten minutes. Read: sections 1, 3 and figure 1; the rest is evaluation across vision tasks.

  4. CODE
    pgvector README

    The distance operators for cosine, inner product and L2, the operator classes for indexes, the HNSW and IVFFlat options, and the dimension limits. Read the Querying and Indexing sections now; the performance tuning section belongs to module A3.

  5. DOC
    Voyage AI: Text Embeddings

    A current provider's embedding API with the query/document distinction (input_type) and Matryoshka dimensions (output_dimension) exposed as parameters, plus domain-specific models for code, finance and law. Read it to see how the chapter's concepts appear as API fields.

  6. DOC
    OpenAI: Vector embeddings guide

    The other widely used provider's view: the dimensions parameter, the recommendation of cosine similarity, and the note that the vectors are normalised so dot product and cosine agree. Compare the two providers' designs; the ideas are identical and the field names are not.

  7. DOC
    nomic-embed-text-v1.5 model card

    The model the lab uses. The task prefixes (search_query, search_document, clustering, classification) and the Matryoshka quality table at each dimension. The thing the Ollama quick start leaves out.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Project: a document Q&A CLI →