Embeddings (AI Engg #8)
Search “how do I get my money back” and a keyword engine returns documents containing “money” and “back”. It misses your refund policy, which says “returns are accepted within 30 days.” Embeddings catch it, because they compare meaning, not spelling.
An embedding is a fixed-length vector (say 384 or 3072 numbers) that represents a piece of text so that similar meanings land close together in vector space. This chapter covers what that means geometrically, how to compute and compare embeddings correctly, which models to pick, the four workhorse use cases, and the mistakes that silently ruin recall.
Meaning as geometry
An embedding model maps text to a point in \(\mathbb{R}^d\). The map is trained so that semantically similar inputs are near each other and unrelated inputs are far. The consequence:
\[ \text{similarity}(a, b) \approx \text{closeness}(\text{embed}(a), \text{embed}(b)) \]
Closeness is usually cosine similarity, which measures the angle between vectors and ignores their length:
\[ \cos(a,b) = \frac{a \cdot b}{\|a\|\,\|b\|} \]
Range \([-1, 1]\); near 1 means same direction (similar), near 0 means unrelated. You can also use dot product (fast, but mixes in magnitude) or Euclidean distance (common for images). Pick one and be consistent — mixing metrics between indexing and querying is a classic recall bug.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
a/.style={->, thick}]
\draw[->, black!40] (-3,0) -- (3.4,0);
\draw[->, black!40] (0,-1.8) -- (0,2.2);
\draw[a, blue!70!black] (0,0) -- (2.0,1.6) node[above right, font=\small] {cat};
\draw[a, blue!70!black] (0,0) -- (1.5,1.3) node[below right, font=\small] {kitten};
\draw[a, orange!80!black] (0,0) -- (2.4,-1.2) node[right, font=\small] {invoice};
\draw[a, orange!80!black] (0,0) -- (2.0,-1.5) node[below, font=\small] {receipt};
\node[font=\rmfamily\small, text=black!60] at (0.2,2.4) {similar meanings point the same way};
\end{tikzpicture}
Computing embeddings
The two lines that matter: load a model, encode text (with normalization on).
# local, free, fast — the default for a proof of concept
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("all-MiniLM-L6-v2")
texts = ["refund within 30 days", "how do I get my money back", "reset password"]
emb = model.encode(texts, normalize_embeddings=True) # unit vectors
print(util.cos_sim(emb[0], emb[1]).item()) # ~0.6+ (money back ~ refund)
print(util.cos_sim(emb[0], emb[2]).item()) # ~0.1 (unrelated)
# hosted, higher quality, pay per token
from openai import OpenAI
client = OpenAI()
emb = client.embeddings.create(model="text-embedding-3-small",
input=texts).data
Three implementation rules:
- Normalize when using cosine. With
normalize_embeddings=True, dot product is cosine, and vector databases can use fast inner-product search. Most libraries normalize for you; verify. - Use the same model for indexing and querying. Never index with model A and query with model B. Their spaces are unrelated.
- Batch and cache. Embedding thousands of documents is cheaper in batches; cache embeddings so you never pay twice for unchanged text.
Model choices
| Model | Dims | Type | Good for |
|---|---|---|---|
all-MiniLM-L6-v2 (Sentence-Transformers) |
384 | open, local | PoC, speed, low RAM |
bge-m3 / e5-large |
1024 | open, local | multilingual, strong retrieval |
| Jina embeddings | ~1024 | open/hosted | long documents |
text-embedding-3-small (OpenAI) |
1536 | closed | general, cheap, easy |
text-embedding-3-large (OpenAI) |
3072 | closed | max quality |
| Gemini / Cohere embeddings | varies | closed | multimodal / search tuning |
Decision rule: start local and free (MiniLM) to build the pipeline, then benchmark against a hosted model on your retrieval evals. If the hosted model’s recall@5 buys you a few points and the volume is modest, pay for it; otherwise stay local. Note that dimension drives cost — a 3072-dim index is 8× the storage and search cost of a 384-dim one.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=1.7cm, minimum height=0.65cm, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=green!12] (m) at (-3.2,0) {MiniLM\\384d};
\node[b, fill=blue!10] (b) at (0,0) {bge-m3\\1024d};
\node[b, fill=orange!15] (o) at (3.2,0) {OpenAI\\1536–3072d};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-0.75) {more dimensions = more quality potential, more storage \& cost};
\draw[a, black!40] (-3.2,-0.5) -- (3.2,-0.5);
\end{tikzpicture}
The four workhorse use cases
Semantic search. Embed a corpus once; embed the query at runtime; return the top-\(k\) nearest. This is the backbone of RAG.
Classification. Embed labeled examples; class label = the nearest example’s label (k-NN), or train a tiny classifier on the vectors. No fine-tuning needed for small label sets.
Recommendation. “Items similar to this item” = nearest neighbors of the item’s embedding. Cold-start items get an embedding from their description.
Anomaly detection. Embed normal data, learn the region it occupies, flag anything far away. Useful for log lines, support tickets, fraud patterns.
# classification by nearest labeled example — no training required
labeled = {"refund": "money back request", "bug": "app crashes", "billing": "invoice charge"}
lab_emb = {k: model.encode([v], normalize_embeddings=True)[0] for k, v in labeled.items()}
def classify(text):
q = model.encode([text], normalize_embeddings=True)[0]
best = max(lab_emb, key=lambda k: float(q @ lab_emb[k]))
return best
print(classify("I was charged twice for order 42")) # billing
What embeddings are bad at
- Exact identifiers. Part numbers, SKUs, error codes, names — dense vectors blur them. Combine with keyword search (BM25) in a hybrid retriever (Chapter 9).
- Negation and logic. “papers without refs” is hard semantically; filters and structured queries do this better.
- Long documents. A 40-page PDF as one vector is an average of everything and specific to nothing. Chunk first (Chapter 10).
- Freshness. Embeddings are static; a new document needs re-embedding and re-indexing. Build that pipeline early.
Evaluating embeddings
You cannot tune what you do not measure. Keep a set of (query, expected_document_id) pairs and compute recall@k:
def recall_at_k(pairs, embed, k=5):
hits = 0
for query, expected_id in pairs:
qv = embed(query)
scored = sorted(corpus, key=lambda d: -float(qv @ d.vec))
if expected_id in [d.id for d in scored[:k]]:
hits += 1
return hits / len(pairs)
Aim for recall@5 above 0.9 on your golden set before blaming the generator. If recall is low, the problem lives here — in the model, the chunks, or the metric — not in the prompt.
Pitfalls
- Mixing metrics. Indexing with one similarity and querying with another quietly kills recall.
- No normalization with cosine. Cosine on unnormalized vectors is not what you think; normalize or use the library’s correct path.
- Recency blindness. New and updated documents must be re-embedded; stale vectors give stale answers.
- One vector per huge doc. Chunk by structure; evaluate chunking and recall together.
Why can embeddings find “money back” → “refund” when keyword search cannot? What should never be a single embedding?
ASolution
Because they encode meaning as direction in vector space, and the model was trained so paraphrases are close. A whole long document, an exact identifier lookup (SKUs, error codes), or anything requiring negation/logic should not rely on a single dense embedding — chunk documents and pair embeddings with keyword search and structured filters.
Next: Vector Databases (AI Engg #9) — where these vectors live and how nearest-neighbor search stays fast at millions of items.