AS·159
Embeddings
Representing meaning as geometry: from one-hot vectors to dense embeddings, the distributional hypothesis and word2vec, contextual and sentence embeddings from Transformers, how embedding models are trained with contrastive learning and in-batch negatives, cosine similarity, dot product and Euclidean distance and when they agree, normalisation, exact nearest-neighbour search, semantic search end to end, asymmetric queries and documents with instruction prefixes, bi-encoders vs cross-encoders, Matryoshka and binary embeddings, multilingual, code and multimodal (CLIP) embeddings, choosing and evaluating models (MTEB and your own data), versioning and re-embedding, other uses (clustering, deduplication, classification, anomaly detection, recommendations), and code in Python, TypeScript, Java, Go and Rust.
Start here: meaning as a list of numbers
The tiffin FAQ in the Start Here chapter was searched by matching words. That fails as soon as a customer writes "money back" instead of "refund". An embedding is a list of numbers (a vector) produced by a model so that texts with similar meaning get similar vectors, whatever words they use.
A three-number example
Real embeddings have hundreds or thousands of numbers; here are made-up three-number ones to show the idea:
| Text | Vector |
|---|---|
| "refund" | [0.9, 0.1, 0.0] |
| "money back" | [0.8, 0.3, 0.1] |
| "delivery" | [0.1, 0.9, 0.2] |
Cosine similarity measures how closely two vectors point the same way (1 = same direction, 0 = unrelated):
cos("money back", "refund") = 0.963
cos("money back", "delivery") = 0.464
cos("refund", "delivery") = 0.214
So a search for "money back" finds the refunds paragraph even though the word "refund" never appears. Semantic search is exactly this: embed every document once, embed the question, and return the documents whose vectors are closest.
What this chapter measures
The lab builds real embeddings from this textbook (5,346 chunks, 879 glossary questions) using a classical method, and compares them with keyword search. The honest finding is that keyword search (BM25) beat the classical embeddings, and that combining both helped; modern neural embedding models are what make semantic search beat keywords, and the lab explains how to verify that on your own data rather than assume it.
How deep to go in embeddings
Volume 17 defines six mastery levels; for embeddings they look like this:
| Level | You can… |
|---|---|
| L1 | explain embeddings, cosine similarity and semantic search |
| L2 | embed a corpus with a library model and search it |
| L3 | explain contrastive training, bi- versus cross-encoders, normalisation and dimension trade-offs |
| L4 | diagnose poor retrieval: domain mismatch, chunking, query/document prefixes, identifiers, language |
| L5 | choose and evaluate an embedding model on your own golden set, including cost, latency and storage |
| L6 | run embedding pipelines at scale: re-embedding migrations, versioning, multi-tenant indexes |
From symbols to vectors
Computers compare strings by characters: "car" and "automobile" share nothing; "bank" (river) and "bank" (money) look identical. An embedding maps an item (word, sentence, document, image, product, user) to a dense vector in ℝᵈ (d typically 256–4096) such that similar meaning ⇒ nearby vectors.
- One-hot vectors (a 1 in the position for each vocabulary item) are sparse, huge, and every pair is equally distant: no notion of similarity.
- Sparse lexical vectors (bag of words, TF-IDF, BM25) capture word overlap but not synonyms or paraphrase.
- Dense learned embeddings capture semantic similarity: "How do I reset my password?" lands near "I forgot my login credentials".
The distributional hypothesis
"You shall know a word by the company it keeps" (J. R. Firth, 1957). Words used in similar contexts have similar meanings. word2vec (Mikolov et al., 2013) learned word vectors by predicting context words (skip-gram) or a word from its context (CBOW); GloVe factorised co-occurrence statistics. They exhibited linear structure (king − man + woman ≈ queen) but gave each word one vector regardless of context.
Contextual embeddings from Transformers (chapter 154) give each token a vector that depends on its sentence, so "bank" by a river differs from "bank" with a loan. Sentence/text embedding models pool token vectors (mean pooling or a special token) into one vector per text and are trained specifically so that the geometry reflects semantic similarity.
How embedding models are trained
Modern text embedding models start from a pre-trained Transformer encoder (or decoder) and are trained with contrastive learning on pairs that should be close: (question, answer passage), (title, body), (query, clicked document), paraphrases, translations, and synthetic pairs generated by LLMs.
InfoNCE / in-batch negatives: for a batch of B pairs (qᵢ, dᵢ), compute similarities sᵢⱼ = cos(qᵢ, dⱼ)/τ for all i, j; train with cross-entropy so each qᵢ picks its own dᵢ among the B candidates. The other documents in the batch serve as negatives for free; larger batches give more negatives. Hard negatives (documents that look relevant but aren't, mined with BM25 or a previous model) teach finer distinctions. The temperature τ (≈ 0.01–0.05) sharpens the softmax.
import numpy as np
def info_nce(Q, D, tau=0.05):
"""Q, D: [B, d] L2-normalised query and positive-document embeddings."""
S = Q @ D.T / tau # [B, B] scaled cosine similarities
S = S - S.max(1, keepdims=True)
log_probs = S - np.log(np.exp(S).sum(1, keepdims=True))
return -np.mean(np.diag(log_probs)) # each query should pick its own document
rng = np.random.default_rng(0)
norm = lambda X: X / np.linalg.norm(X, axis=1, keepdims=True)
Q = norm(rng.normal(size=(8, 64)))
info_nce(Q, norm(Q + 0.1 * rng.normal(size=Q.shape))) # aligned pairs → ≈ 0.00002
info_nce(Q, norm(rng.normal(size=(8, 64)))) # random pairs → ≈ 4.3: worse than uniform guessing (ln 8 ≈ 2.1)
Similarity measures
For vectors a, b:
| Measure | Formula | Notes |
|---|---|---|
| Dot product | a · b | Fast; sensitive to vector length; some models are trained for it |
| Cosine similarity | a · b / (‖a‖‖b‖) | Angle only, in [−1, 1]; the default for text embeddings |
| Euclidean (L2) distance | ‖a − b‖ | Straight-line distance |
For unit-length (L2-normalised) vectors these are equivalent rankings: ‖a − b‖² = 2 − 2(a · b) and cosine = dot product. So: normalise embeddings once at write time, then use dot product (the cheapest). Use whichever metric the model card specifies; some models (and some recommendation embeddings) deliberately encode importance in vector length.
a, b = rng.normal(size=384), rng.normal(size=384)
an, bn = a / np.linalg.norm(a), b / np.linalg.norm(b)
np.isclose(np.sum((an - bn) ** 2), 2 - 2 * an @ bn) # True: L2² = 2 − 2·cos for unit vectors
Similarity scores are relative: a cosine of 0.78 has no absolute meaning across models; one model's "relevant" may be 0.45, another's 0.85. Calibrate thresholds per model on labelled data.
Nearest neighbours and semantic search
Semantic search = embed the corpus once, embed each query, return the documents whose vectors are nearest the query vector.
Exact (brute-force) search computes the similarity with every vector: O(N·d) per query. With normalised vectors in a matrix, that's one matrix-vector product: practical up to roughly a million vectors on a CPU (and much more on GPUs). Beyond that, approximate nearest-neighbour (ANN) indexes (chapter 160) trade a little recall for orders-of-magnitude speed.
A self-contained semantic search with a toy embedding (hashed character n-grams and TF-IDF-like weighting, standing in for a neural model so the example runs offline):
import re, hashlib
def toy_embed(texts, dim=512):
"""Hashing-trick embedding of word and character trigrams. A stand-in for a real model."""
out = np.zeros((len(texts), dim))
for i, t in enumerate(texts):
words = re.findall(r"\w+", t.lower())
grams = words + [w[j:j + 3] for w in words for j in range(max(1, len(w) - 2))]
for g in grams:
h = int(hashlib.md5(g.encode()).hexdigest(), 16)
out[i, h % dim] += 1 if (h >> 64) & 1 else -1
return out / np.maximum(np.linalg.norm(out, axis=1, keepdims=True), 1e-9)
docs = ["How to reset your password from the login page",
"Download invoices and receipts from the billing section",
"Request a refund within 30 days of purchase",
"Locked out after too many sign-in attempts? Wait 15 minutes",
"Change the email address on your account settings page"]
D = toy_embed(docs)
def search(query, k=2):
q = toy_embed([query])[0]
scores = D @ q # cosine, since all vectors are unit length
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 3), docs[i]) for i in top]
search("forgot my password") # top hit: the password-reset document
search("too many login attempts") # top hit: the locked-out document
A hashing embedding only matches overlapping words and sub-words; a neural model would also match "can't sign in" to the password document with no shared words. That is the point of learned embeddings.
Queries vs documents
Queries are short and question-like; documents are long and declarative. Many retrieval models are asymmetric: they expect instruction prefixes such as "query: " / "passage: ", or a task instruction ("Represent this question for retrieving supporting documents: "), or separate query and document encoders. Using the wrong prefix measurably hurts retrieval; follow the model card.
Bi-encoders and cross-encoders
| Bi-encoder (embedding model) | Cross-encoder (reranker) | |
|---|---|---|
| How | Encode query and document separately into vectors; compare with dot product | Encode the pair together; full attention between query and document tokens; output a relevance score |
| Pre-computation | Document vectors computed once, indexed | Nothing can be precomputed |
| Speed | Milliseconds over millions of documents (with ANN) | One model call per (query, document) pair |
| Quality | Good | Better: sees token-level interactions |
| Use | First-stage retrieval (recall) | Second-stage reranking of the top 20–100 (precision) (chapter 161) |
Late interaction models (ColBERT and successors) keep one vector per token and score with MaxSim (each query token's best match summed): quality closer to cross-encoders with precomputable document representations, at the cost of much more storage.
Dimensions, Matryoshka and compression
- Storage = N × d × bytes: 10 million chunks × 1024 dims × 4 bytes (float32) ≈ 41 GB of raw vectors, before index overhead.
- Matryoshka representation learning trains models so that the first k dimensions form a usable embedding on their own: truncate 3072 → 512 dimensions (then re-normalise) with a modest quality loss. Many current API and open models support this.
- Quantisation: float16 (½ size), int8 scalar quantisation (¼), binary (1 bit per dimension: 1/32 size, compare with Hamming distance), product quantisation (chapter 160). A common pattern: search binary or int8 vectors for speed and memory, then rescore the top candidates with full-precision vectors.
def truncate(E, k): # Matryoshka-style truncation (meaningful only for MRL-trained models)
T = E[:, :k]; return T / np.linalg.norm(T, axis=1, keepdims=True)
def binarize(E): return np.packbits(E > 0, axis=1) # 1 bit per dimension
def hamming(a, B): return np.unpackbits(a ^ B, axis=1).sum(1)
Eb = binarize(D); qb = binarize(toy_embed(["forgot my password"]))
np.argsort(hamming(qb[0], Eb))[:2] # binary search candidates, then rescore with float vectors
Beyond English text
- Multilingual embeddings map translations close together, enabling cross-lingual search (query in Telugu, documents in English). Check per-language quality; low-resource languages lag.
- Code embeddings for code search, clone detection and retrieval over repositories.
- Multimodal embeddings: CLIP (2021) trained image and text encoders contrastively on image-caption pairs so both land in one space: text-to-image search, zero-shot classification ("a photo of a {label}"), image deduplication. Newer models embed documents as page images (screenshots) to retrieve PDFs with charts and tables without OCR (chapter 161, 173).
- Domain embeddings: products, users and items in recommender systems (two-tower models), graph node embeddings, audio embeddings.
Choosing and evaluating an embedding model
- Shortlist from the MTEB leaderboard (Massive Text Embedding Benchmark: retrieval, classification, clustering, reranking, STS across many languages), considering size, dimensions, max input tokens, licence, multilingual needs, and hosting (API vs self-hosted).
- Evaluate on your data: build 50–200 real queries with known relevant documents; measure recall@k and NDCG@k (chapter 149, 162). Leaderboard rank often doesn't transfer to specialised domains.
- Consider latency and cost: embedding the corpus once is cheap compared with query-time latency at scale; small models (100–300M parameters) on CPUs or GPUs are often enough.
- Fine-tune an open embedding model on in-domain pairs (thousands of examples, contrastive loss, hard negatives) when general models underperform: often a large retrieval gain.
Operational rules
- Never mix vectors from different models (or versions) in one index: their spaces are incompatible. Store the model name and version with each vector.
- Re-embedding the corpus is required when changing models: plan for it (dual-write to a new index, backfill, switch reads, then delete the old one).
- Respect the model's max input length: text beyond it is silently truncated; chunk accordingly (chapter 161).
- Normalise consistently; record the metric in the index configuration.
- Embeddings of sensitive text are sensitive data: inversion attacks can reconstruct approximate text from embeddings; apply the same access controls.
Other uses of embeddings
| Use | How |
|---|---|
| Clustering and topic discovery | k-means/HDBSCAN on embeddings; label clusters with an LLM |
| Deduplication | Cosine above a threshold → near-duplicate (chapter 150) |
| Classification | Logistic regression on embeddings: strong, cheap baseline with few labels |
| Anomaly / drift detection | Distance from cluster centroids; distribution shift in embedding space (chapter 177) |
| Recommendations | Nearest items to a user's history vector |
| Semantic caching | Return a cached LLM answer when a new query's embedding is very close to a previous one (chapter 179) |
| Routing | Nearest prototype queries decide which tool or model handles a request |
Embeddings across languages
# Python: sentence-transformers (open models) or provider SDKs
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("BAAI/bge-small-en-v1.5")
docs_emb = model.encode(docs, normalize_embeddings=True) # [N, 384]
q_emb = model.encode(["can't sign in"], prompt="Represent this sentence for searching relevant passages: ",
normalize_embeddings=True)
scores = docs_emb @ q_emb[0]
// TypeScript: Transformers.js runs ONNX embedding models in Node or the browser
import { pipeline } from "@huggingface/transformers";
const embed = await pipeline("feature-extraction", "Xenova/bge-small-en-v1.5");
const out = await embed(["can't sign in"], { pooling: "mean", normalize: true });
const vec = Array.from(out.data); // Float32 → number[]
// Java: Spring AI EmbeddingModel abstraction (OpenAI, Ollama, ONNX, Bedrock, ...)
@Service
class Embedder {
private final EmbeddingModel model;
Embedder(EmbeddingModel model) { this.model = model; }
float[] embed(String text) { return model.embed(text); }
List<float[]> embedAll(List<String> texts) { return model.embed(texts); }
}
// Go: call an embeddings HTTP API (provider or a self-hosted TEI/Ollama server)
type embedReq struct{ Model string `json:"model"`; Input []string `json:"input"` }
body, _ := json.Marshal(embedReq{Model: "nomic-embed-text", Input: []string{"can't sign in"}})
resp, err := http.Post("http://localhost:11434/api/embed", "application/json", bytes.NewReader(body))
// Rust: fastembed-rs (ONNX Runtime) for local embeddings
use fastembed::{TextEmbedding, InitOptions, EmbeddingModel};
let model = TextEmbedding::try_new(InitOptions::new(EmbeddingModel::BGESmallENV15))?;
let embeddings = model.embed(vec!["can't sign in"], None)?; // Vec<Vec<f32>>
Lab: embeddings for this textbook, measured
Setup. scikit-learn 1.9.1 and rank_bm25 on the lab machine (2 vCPUs). Corpus: the main chapter files of Volumes 1–14, quizzes and diagrams removed, split into 5,346 chunks of about 200 words across 159 chapters. Golden set: 879 glossary entries from the revision sheets; each entry is a query, and the right answer is the chapter it came from (the revision sheets themselves are not in the corpus). Scoring: rank chunks, collapse to chapters, report recall@1, recall@5 and MRR@10.
Substitute, stated plainly: the lab can't download neural embedding models, so the dense vectors are LSA (TF-IDF followed by truncated SVD), the classical pre-neural embedding. The method of evaluation is exactly what you'd use for a modern model; the absolute numbers are not what a modern model would give.
Experiment 1: keywords vs embeddings vs both
| Method | Query = glossary term: R@1 / R@5 / MRR | Query = definition text: R@1 / R@5 / MRR | ms per query |
|---|---|---|---|
| BM25 | 0.431 / 0.768 / 0.575 | 0.457 / 0.752 / 0.586 | 2–11 |
| TF-IDF cosine (sparse) | 0.356 / 0.733 / 0.513 | 0.336 / 0.702 / 0.490 | 1.5 |
| LSA 64-d | 0.259 / 0.602 / 0.401 | 0.259 / 0.646 / 0.418 | 2 |
| LSA 256-d | 0.298 / 0.660 / 0.450 | 0.311 / 0.701 / 0.473 | 4 |
| hybrid (reciprocal rank fusion of BM25 + LSA 256) | 0.364 / 0.727 / 0.517 | 0.435 / 0.778 / 0.576 | 7–20 |
On this corpus, keyword search beat classical embeddings at every cut-off. That is common for technical text full of distinctive terms ("bcrypt", "NetworkPolicy", "pg_last_wal_replay_lsn"), and it is why production RAG systems keep a keyword index alongside the vector index. The hybrid gave the best recall@5 for longer queries but lost to BM25 alone on short term queries; fusion isn't automatically better, which is why you measure.
Experiment 2: what LSA learned
Nearest words in the LSA space (cosine between term vectors):
latency -> 314, retransmits, completed, p99, hedged, explodes
password -> passwords, breached, bcrypt, rainbow, lockout, competition
kubernetes-> kube, ingress, gke, 4c, networkpolicy, ons
gradient -> descent, backpropagation, curvature, 146, adam, differentiation
replica -> hadn, lagging, readerfor, queryrowcontext, lsn, pg_last_wal_replay_lsn
The space captures co-occurrence (words that appear in the same chunks), which mixes real associations (bcrypt, p99, backpropagation) with accidents of this corpus (chapter numbers like "146", code identifiers, the truncated "hadn"). Neural models learn from far more data, which averages such accidents away, but they still inherit their training data's associations.
Ten paraphrase queries sharing few words with the target chapter (e.g. "make a copy of the database that follows the main one" → replication) found a chunk containing the concept word with BM25 4/10 times and LSA 2/10. This is the case neural embeddings are trained for; it is the first thing to test when you evaluate one.
Experiment 3: dimensions, precision and storage
Recall@5 on definition queries, 5,346 vectors:
| Representation | R@5 | Storage |
|---|---|---|
| 16 leading dimensions | 0.493 | 0.34 MB |
| 32 | 0.569 | 0.68 MB |
| 64 | 0.638 | 1.37 MB |
| 128 | 0.661 | 2.74 MB |
| 256 float32 | 0.701 | 5.47 MB |
| 256 int8 | 0.702 | 1.37 MB |
| 256 one bit per dimension (signs) | 0.653 | 0.17 MB |
| 256 raw dot product without normalising | 0.687 | — |
- SVD orders dimensions by importance, so keeping the leading ones degrades smoothly: the same property Matryoshka-trained neural models are designed to have.
- int8 quantisation lost nothing measurable at a quarter of the memory; 1-bit vectors kept 93% of the recall at 1/32 of the memory, which is why binary quantisation plus re-scoring with full vectors is a common trick at scale.
- Without normalisation, dot product favoured vectors with large norms; here, the largest-norm chunks were short (21–59 words vs a median of 133). Normalise, or use a model trained for dot product.
Experiment 4: why high dimensions work
Mean and maximum |cosine| between 1,000 pairs of random unit vectors:
| Dimensions | mean | max |
|---|---|---|
| 2 | 0.644 | 1.000 |
| 16 | 0.198 | 0.744 |
| 256 | 0.047 | 0.212 |
| 1,536 | 0.021 | 0.091 |
In high dimensions random vectors are almost orthogonal, so there is room for many distinct meanings, and a cosine of 0.3 can be a strong signal. It also means similarity scores have no universal threshold: their distribution depends on the model, so thresholds (like Start Here's "I don't know" cut-off) must be calibrated per model on labelled data.
Try it yourself
- If you can access a neural embedding model, embed the same chunks and rerun Experiment 1. Does it beat BM25 on the paraphrase queries? On the term queries?
- Change the chunk size to 100 and 400 words and remeasure. Which queries improve?
- Replace reciprocal rank fusion with a weighted sum of normalised scores, and tune the weight on half the golden set; test on the other half.
- Plot the score distribution of correct and incorrect top results, and choose an "I don't know" threshold.
Revision sheet: embeddings
Key ideas
- An embedding maps content to a vector so that similar meanings are close; similarity is usually cosine (or dot product on normalised vectors).
- Modern text embeddings are trained contrastively: pull matching pairs (question/answer, title/body) together, push in-batch negatives apart.
- Bi-encoders embed query and document separately (fast, indexable); cross-encoders read them together (accurate, slow; used to rerank).
- Many models need prefixes or instructions ("query:" vs "passage:"); using the wrong one quietly lowers quality.
- Dimensions trade quality for memory and speed; Matryoshka models allow truncation; int8 and binary quantisation cut storage further.
- Embeddings are weak on exact identifiers, rare terms, negation and numbers; keep keyword search alongside.
- Changing the embedding model means re-embedding everything; vectors from different models aren't comparable.
- Choose a model by measuring it on your own golden set, not by leaderboard rank alone.
Numbers to remember
- Lab: BM25 R@5 0.768 vs LSA 256-d 0.660 on term queries; hybrid 0.778 on definition queries.
- Lab: int8 kept recall at ¼ memory; 1-bit kept 93% at 1/32.
- Random unit vectors at 1,536 dimensions: mean |cos| ≈ 0.02.
- float32 storage = vectors × dimensions × 4 bytes (1 M × 1,024-d ≈ 4 GB).
Pitfalls
- Mixing vectors from two models or model versions in one index.
- Forgetting query/document prefixes, or normalising inconsistently.
- Using a fixed similarity threshold copied from another model.
- Dropping keyword search and losing exact matches on IDs and error codes.
- Embedding text in a language or domain the model wasn't trained on without testing.
Glossary
- Embedding: a vector representation of content.
- Cosine similarity: dot product of length-normalised vectors.
- Contrastive learning: training by pulling positives together and pushing negatives apart.
- Bi-encoder / cross-encoder: separate vs joint encoding of query and document.
- Matryoshka embedding: a vector whose leading dimensions are useful on their own.
- LSA: latent semantic analysis; SVD of a term–document matrix.