Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  Embeddings
Handbook~15 min readFoundationsworked math + runnable code
The Embeddings Handbook

Meaning,
as geometry.

Computers can't compare the meaning of two sentences — but they're superb at comparing vectors. Embeddings bridge that gap: a model turns text into a point in space so that "how similar are these?" becomes "how close are these points?" Suddenly semantic search, recommendations, clustering, and RAG are all just geometry. This handbook builds the whole idea from one operation — the angle between two vectors — and shows you the arithmetic that every vector database runs a billion times a second.

01

Meaning as vectors

An embedding is a vector — an ordered list of numbers — that stands in for a piece of content: a word, a sentence, a whole document, an image. The magic isn't the vector; it's the training. Embedding models are trained so that content with similar meaning gets nearby vectors. "dog" sits near "puppy"; "bank" (money) drifts away from "bank" (river). Meaning becomes position.

Once meaning is position, hard questions turn easy. "Which of these 10,000 documents is most relevant to my question?" becomes "which vector is closest to the query vector?" — a geometry problem with fast, exact answers. That single reframing is why embeddings underpin semantic search, clustering, deduplication, recommendation, and retrieval-augmented generation. The rest of this handbook is about the one measurement that makes "closest" precise.

The one-sentence version

An embedding turns content into a vector so that similar meaning lands nearby — reducing "how related are these?" to measuring the angle between two vectors.

02

The angle is the answer

The default way to compare two embeddings is cosine similarity — the cosine of the angle between them. It's the dot product of the two vectors divided by the product of their lengths:

cos(a, b)  =  a · b  /  (‖a‖ · ‖b‖)     where   a · b = Σ aᵢbᵢ,   ‖a‖ = √(a · a)

Same direction → cosine 1 (most similar). Perpendicular → cosine 0 (unrelated). Opposite → cosine −1. It runs from −1 to 1.

The crucial property is that cosine measures direction, not magnitude. A long document and a short one about the same topic should count as similar even though one vector is much longer — dividing by the lengths strips magnitude away and leaves only the angle. That's usually exactly what you want for meaning: "aboutness" shouldn't depend on how many words you used. (When magnitude does carry signal, raw dot product or Euclidean distance may be preferred — but for semantic text, cosine is the safe default.)

03

Normalize, then dot

Here's the trick that vector databases live on. Dividing by lengths on every comparison is wasteful when you're doing millions of them. So instead, L2-normalize every vector once — scale it to unit length — up front. After that, the denominator is always 1, and the dot product equals the cosine similarity:

â = a / ‖a‖  (so ‖â‖ = 1)   ⟹   â · b̂  =  cos(a, b)

Normalize once at index time; then ranking by cosine is just ranking by dot product — which is what fast maximum-inner-product search (and indexes like HNSW) are built to do.

Why normalization is the standard move
StoreL2-normalize every document vector once at index time.
QueryNormalize the query vector, then take dot products.
RankDot product now equals cosine — highest dot = most similar.
ScaleMaximum-inner-product search is exactly what ANN indexes accelerate.

This is why so much embedding code normalizes vectors and then never mentions cosine again — the cosine is baked in. It also makes distances behave nicely: on unit vectors, Euclidean distance and cosine similarity become monotonically related, so nearest-by-distance and most-similar-by-cosine agree.

04

More dimensions

Real embeddings aren't 2-D — they're hundreds to thousands of dimensions (384, 768, 1536, 3072 are common). More dimensions give the model more room to separate fine distinctions in meaning, which is why bigger embedding models often retrieve better. But dimensions aren't free: storage and search cost scale with them, and very high dimensions bring the curse of dimensionality — distances between random points concentrate, so "nearest" gets less discriminative unless the embedding genuinely uses those dimensions well.

The practical upshot is a trade-off you tune. Smaller vectors are cheaper to store and faster to search; larger ones can be more accurate. Techniques like quantization compress vectors to reclaim memory, and some modern models support Matryoshka embeddings you can truncate to a shorter prefix for a cheaper approximation. The geometry — cosine on normalized vectors — stays identical no matter the dimension; only the cost and the fidelity change.

RUN IT YOURSELF

Cosine, normalization, nearest

The whole toolkit is a few lines. Cosine similarity is the dot product over the product of lengths, so parallel vectors score 1 and perpendicular ones score 0 — direction, not magnitude. L2-normalization scales a vector to unit length, and once both vectors are normalized their dot product exactly equals the cosine, which is why vector databases store normalized embeddings and just take dot products. Nearest-neighbor search is then: whichever stored vector has the highest cosine with the query is the semantic match. Change the vectors and watch the ranking shift.

CPython · WebAssembly
05

Embeddings in the wild

Once you can measure similarity, a lot of products fall out of the same primitive:

Use caseHow embeddings power it
Semantic search / RAGEmbed documents once; embed the query; retrieve the nearest vectors as context for the model.
RecommendationsEmbed items and users; recommend items whose vectors are nearest to what someone liked.
Clustering & dedupGroup nearby vectors; near-duplicate content has near-identical embeddings.
ClassificationEmbed text and compare to labelled centroids, or train a light classifier on the vectors.
Anomaly detectionPoints far from every cluster are outliers worth flagging.

In practice the pipeline is: pick an embedding model, embed and normalize your corpus, store the vectors in an index (with an ANN structure for scale), and at query time embed, normalize, and retrieve by dot product. The vector database handles the index; the embedding model determines quality. Both matter: a great index over bad embeddings retrieves the wrong things quickly.

06

Pitfalls

Embeddings are simple to use and easy to misuse. A few traps worth naming: model mismatch — you must embed queries and documents with the same model (and often the same instruction/prefix); mixing models compares vectors from different spaces, which is meaningless. forgetting to normalize — if you rank by dot product but didn't normalize, longer documents get an unfair boost. domain drift — a general model may not separate your niche jargon well; sometimes a domain-tuned model or a late-interaction retriever helps.

And the deepest one: embeddings capture similarity, not truth or relevance-to-your-task. Two sentences can be semantically close yet one is right and one is wrong; a passage can be on-topic but unhelpful. That's why strong retrieval systems pair embeddings with a reranker and, for questions, a generator that reads the retrieved text. Embeddings get you the right neighborhood fast; the last mile of precision usually needs another step. Used with that awareness, though, this one idea — meaning as geometry — is the most reusable primitive in applied AI.

Worth knowing

Cosine similarity has no absolute scale you can trust across models — a "0.8" from one model isn't comparable to "0.8" from another, and even within a model the useful threshold varies by domain. Calibrate thresholds on your own data rather than copying a magic number.

By the numbers

Worked example: ranking three documents step by step

Take a query q = [1, 2, 2], so ‖q‖ = 3, and three stored documents. Real embeddings have hundreds of dimensions; three keep the arithmetic visible. Compute the length of each document, its raw dot product with the query, its cosine, and the Euclidean distance once both vectors are normalized to unit length.

DocVector‖d‖q · dcos(q, d)Unit distance
A[0.5, 1, 1]1.54.51.00000.0000
B[4, 4, 0]5.657120.70710.7654
C[2, 1, 2]3.080.88890.4714

Rank by raw dot product and you get B (12), then C (8), then A (4.5). Rank by cosine and the order flips: A (1.0), C (0.889), B (0.707). A points in exactly the query’s direction. It only looks weak on the raw dot because it is short. B wins the raw dot because it is long, not because it is close in meaning, which is the “longer documents get an unfair boost” pitfall in numbers. Now normalize first. The unit query is [0.3333, 0.6667, 0.6667], unit B is [0.7071, 0.7071, 0], and their dot product is 0.7071, exactly B’s cosine. The last column is √(2 − 2·cos), the distance between unit vectors. It falls as cosine rises, so it gives the same order: A, C, B. Normalize once at index time and dot product, cosine and Euclidean distance all agree on the ranking. The search itself was 3 documents × 3 dimensions = 9 multiply-adds. A real index does the same arithmetic at N × d, which is the cost the next table is about. Quantization barely moves this ranking. Scale each unit vector by 127 and round to int8: the query becomes [42, 85, 85], A becomes the same, C becomes [85, 42, 85] and B becomes [90, 90, 0]. The integer dot products are 16,214 for A, 14,365 for C and 11,430 for B, still A, C, B. C’s cosine computed from the int8 vectors is 0.8860 against an exact 0.8889, and B’s is 0.7053 against 0.7071. Errors of that size only matter when two documents score almost the same, which is why the top hits are often re-scored at full precision.

Trade-offs

Search cost and storage trade-offs

For a corpus of N vectors of d dimensions. Time is the work per query; Space is the memory for the raw vectors. Figures are for N = 1,000,000 and d = 1,536 unless stated.

CaseTimeSpaceWhy
Exact search (brute force)O(N·d): 1.536 billion multiply-adds per queryO(N·d): 6.144 GB in float32Perfect recall and no index to build. Fine for small corpora or as the ground truth you measure an ANN index against.
Normalize at index timeO(d) once per vector; each comparison is then one dot productNo extra spaceDrops the two length computations from every comparison and makes dot product equal cosine.
ANN index (e.g. HNSW)Visits a small fraction of the corpus; grows roughly logarithmically with N in practiceThe vectors plus a neighbour graphOrders of magnitude faster, but approximate: recall is below 100% and is tuned against speed.
Fewer dimensions (768)Half the work per comparison3.072 GBCheaper and faster. Whether retrieval quality holds is an eval question, not a given.
int8 quantizationFaster, cache-friendlier arithmetic1.536 GB (4× smaller)Small accuracy loss. Often paired with re-scoring the top hits at full precision.
Binary quantizationBitwise comparisons192 MB (32× smaller)A coarse first pass. Re-rank its candidates with the full vectors.
Reranker on the top candidatesOne model call per candidate: slow, so only on the top tens to hundredsA second model to host or pay forReads query and passage together, so it judges relevance, not just closeness. The last-mile precision step the pitfalls section points to.
Matryoshka truncation to 256One sixth of the work1.024 GBOnly for models trained for it. Re-normalize after truncating.

Every lever trades fidelity for cost except normalization, which is free. That is why it is universal. The usual production stack layers several: a quantized or truncated ANN pass to fetch a few hundred candidates, then full-precision vectors or a reranker on just those. Measure recall at each layer against exact search on your own queries. And do the N × d × bytes sum before you pick a database: whether the vectors fit in one machine’s memory decides more of the architecture than any index setting.

Self-check

Check yourself

What are the cosine and the dot product of [3, 4] and [6, 8]? What is the dot product after you normalize both?

Dot product: 3·6 + 4·8 = 50. Lengths are 5 and 10, so cosine = 50 / 50 = 1: same direction, one vector just twice as long. Normalized, both become [0.6, 0.8] and the dot product is 1, equal to the cosine, as it always is for unit vectors.

You store 10 million 768-dimension embeddings. How much memory do the raw vectors need in float32, and in int8?

10,000,000 × 768 × 4 bytes = 30.72 GB in float32. At 1 byte per dimension, int8 needs 7.68 GB. Index structures come on top of both, so the float32 version will not fit on a 32 GB machine once anything else runs.

Two unit vectors have cosine 0.8. What is the Euclidean distance between them, and does ranking by distance change the order?

For unit vectors, distance = √(2 − 2·cos) = √0.4 ≈ 0.632. The function only goes down as cosine goes up, so nearest-by-distance and most-similar-by-cosine give the same order. That is why an index built for Euclidean distance works on normalized embeddings.

Your HNSW index reports recall@10 of 0.9 against exact search. What does that mean, and how do you raise it?

On average, 9 of the true 10 nearest vectors appear in the index’s top 10; one is missed. Raise the search breadth (HNSW’s ef_search, or the equivalent knob in your database) so each query visits more of the graph, at the cost of latency. Or fetch a larger candidate pool and re-score it exactly. Measure recall on your own queries, because it varies with the data.

A team truncates normalized 1,536-d Matryoshka embeddings to their first 256 numbers and keeps ranking by dot product. What goes wrong, and what is the fix?

The truncated vectors are no longer unit length. Each keeps only part of its squared length, and different vectors keep different amounts. So the dot product stops being the cosine and the length bias from the worked example comes back. Re-normalize after truncating, the same as at index time. Also re-check retrieval quality, because a shorter prefix is a cheaper approximation, not a free one.

Frequently asked

Quick answers

What is an embedding?

A vector that represents content so that similar meaning maps to nearby vectors — turning questions about meaning into geometry.

What is cosine similarity?

The cosine of the angle between two vectors (dot product over the product of lengths) — it measures direction, not magnitude, from −1 to 1.

Why normalize?

After L2-normalizing to unit length, the dot product equals the cosine, so you can rank by fast dot products (maximum-inner-product search).

How do embeddings power RAG?

Embed documents once, embed the query, retrieve the nearest vectors, and feed those documents to the model as context.

Finished this one? 0 / 209 Handbooks done
NextEncoder vs Decoder Models Next on the “How models actually work” ladder · rung 4 of 11

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks