Slides · Embeddings and vector search
Embeddings and similarity search
1 / 26
Embeddings and similarity search
How a model turns a chunk or a query into one vector, how we measure “close”, and where that ranking breaks.
By the end you can explain embedding geometry, compare cosine, dot product and Euclidean distance, and diagnose the common ways embedding search goes wrong.
Concept
One search works, one fails
- “My parcel arrived smashed” finds the “damaged items” article, with no shared words.
- The exact ticket “ST-48213” returns a hundred look-alike tickets, and not the one asked for.
- Same system, opposite results. The geometry explains both.
- Teams that sell this as “fuzzy keyword search” are surprised by the second case.
Concept
Mental model: a map of meaning
- Every piece of content gets coordinates, like a pin on a map.
- A real map has two axes. An embedding has hundreds or thousands.
- “Dog” and “puppy” land close. “Dog” and “spreadsheet” land far apart, whatever letters they share.
- Search means: drop a pin at the query, list the nearest pins.
Diagram
From text to ranked neighbours
Compare
Two different “embeddings”
| Aspect | Token embedding table (inside an LLM) | Dedicated embedding model (this lesson) |
|---|---|---|
| Input | One token ID | A whole chunk, document or query |
| Output | One vector per token | One vector for the whole input |
| Used for | Feeding the transformer | Search, clustering, deduplication, RAG retrieval |
- The vector’s job is to represent the whole text, so whole texts can be compared, ranked and stored.
- Sentence-BERT was designed so sentence embeddings can be compared with cosine similarity. Over 10,000 sentences, finding the most similar pair dropped from about 65 hours (running BERT on every pair) to about 5 seconds, according to its abstract.
Source[1] Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
Diagram
How the model learns “close”
- Contrastive pre-training on unsupervised data at scale gives high-quality embeddings (Neelakantan et al.). The diagram shows a generic labelled-pair example; pairs can also come from unlabelled text.
- Consequence: “meaning” is whatever the pairs made similar. That is why a general model can misjudge a specialised domain.
Source[2] Text and Code Embeddings by Contrastive Pre-Training
Worked example
Dimensions cost storage
More dimensions can hold more nuance, but every vector costs memory and compute.
| Step | Calculation |
|---|---|
| Bytes per 1,536-dim float32 vector | 1,536×4=6,144 bytes |
| 1 million vectors | 1,000,000×6,144=6.144 GB |
| Same count at 3,072 dims | 1,000,000×3,072×4=12.288 GB |
- This is raw vector storage, before any index overhead.
- OpenAI’s guide lists 1,536 default dimensions for
text-embedding-3-smalland 3,072 fortext-embedding-3-large, and adimensionsparameter to shorten them. Model names and sizes change; check the model you use.
Source[3] Vector embeddings
Compare
Three ways to measure “close”
| Metric | Measures | Bigger score means | Sensitive to length? |
|---|---|---|---|
| Cosine similarity | Angle between vectors | More similar | No |
| Dot product | Angle and length together | More similar | Yes, longer scores higher |
| Euclidean (L2) distance | Straight-line gap between points | Less similar (smaller is closer) | Yes |
- Cosine is the usual default for text.
- For many text models the length carries little meaning; check yours.
Math
Cosine similarity
cos(a,b)a⋅b∥a∥=∥a∥∥b∥a⋅b=a1b1+a2b2+⋯+anbn=a12+a22+⋯+an2| Symbol | Meaning |
|---|---|
| a,b | The two vectors being compared |
| a⋅b | Dot product: multiply matching entries and add them up |
| ∥a∥ | Length (norm) of a |
| cos(a,b) | Score from −1 to 1 |
Dot product divided by the two lengths removes length from the score. Only the angle is left.
Concept
Reading the number as an angle
| Cosine | Angle | In plain words |
|---|---|---|
| 1 | 0 degrees | Point the same way: very similar |
| 0.7 | about 45 degrees | Clearly related |
| 0 | 90 degrees | Unrelated direction |
| -1 | 180 degrees | Opposite, rare for text embeddings in practice |
- A score has no universal meaning. “0.8” from one model is not “0.8” from another.
- Choose thresholds by labelling real pairs, never by guessing.
Worked example
Same data, three rankings
Query q=(3,4), length 5. Four documents, in 2 dimensions for hand calculation.
| Doc | Vector | Dot with q | Cosine | Euclidean distance |
|---|---|---|---|---|
| x | (6,8), length 10 | 50 | 1.000 | 5.000 |
| y | (4,3), length 5 | 24 | 0.960 | 1.414 |
| z | (1,0.5) | 5 | 0.894 | 4.031 |
| w | (0,5), length 5 | 20 | 0.800 | 3.162 |
Arithmetic for y: dot =3×4+4×3=24; cosine =24/(5×5)=0.96; distance =1+1=1.414.
| Metric | Best to worst |
|---|---|
| Cosine | x, y, z, w |
| Dot product | x, y, w, z |
| Euclidean distance | y, w, z, x |
Document x points exactly where the query points but is long, so cosine ranks it first and Euclidean distance ranks it last.
Diagram
Try it: move the query
Text summary
This plot has seven made-up items as points in 2 dimensions, such as “Ending your plan” at (2, 1), and one query point you can move. A real embedding model has hundreds or thousands of dimensions, so this is a drawing of the idea, not a real model.
For each item, a table gives cosine similarity, dot product and Euclidean distance to the query, and the rank each metric gives it. With the query at (2, 2), where it starts, cosine similarity ranks “Cancel a subscription” first, because it points almost the same way as the query. Euclidean distance ranks “Ending your plan” first, because it is the nearest point.
The dot product ranks “Quarterly report (a long vector)” first, because that vector is long and the dot product grows with length. The metrics disagree here because the item vectors have different lengths. If every item vector had length 1, all three would give the same order.
The interactive version needs JavaScript. The text summary above says what it shows.
Move the query point and watch the three metrics re-rank the same items. When item vectors have different lengths, the metrics disagree. If every item vector had length 1, all three would give the same order.
Math
Why unit length makes cosine cheap
If ∥a∥=1 and ∥b∥=1:
cos(a,b)∥a−b∥2=a⋅b=2−2(a⋅b)| Result | Consequence |
|---|---|
| Cosine equals the dot product | A plain dot product is fast on hardware |
| Distance squared falls as the dot product rises | Euclidean distance gives the same order as cosine |
- OpenAI’s guide says its embeddings are normalized to length 1, so cosine and Euclidean distance give identical rankings and a dot product is slightly faster.
- Other models may not normalize. Check the model card, and configure the vector index with the metric the model expects.
Source[3] Vector embeddings
Worked example
Checking the identity by hand
Take two unit vectors: a=(1,0) and b=(0.6,0.8).
| Quantity | Calculation | Result |
|---|---|---|
| Length of b | 0.36+0.64 | 1 |
| Dot product | 1×0.6+0×0.8 | 0.6 |
| Cosine | 0.6/(1×1) | 0.6 |
| Squared distance | (0.4)2+(0.8)2=0.16+0.64 | 0.8 |
| 2−2(a⋅b) | 2−1.2 | 0.8 |
Both formulas agree, so the two metrics order any set of unit vectors the same way.
Code
Cosine in code
Python
import numpy as np
def cosine_similarity(a, b):
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
q = np.array([3.0, 4.0])
y = np.array([4.0, 3.0])
print(cosine_similarity(q, y)) # 0.96
print(np.linalg.norm(y)) # 5.0, so y is not unit lengthnp.dotis the top of the formula.np.linalg.normgives each length.- For vectors that are already unit length, the division is by 1, so plain
np.dotis enough. - Printing the norm of your own model’s vectors tells you whether that shortcut is safe.
Concept
Where embedding search fails
- Exact identifiers and numbers.
- Rare terms and new vocabulary.
- Domain shift: a general model blurs a specialised field.
- Related, but not useful: right topic, not the answer.
- Mixed models: documents and queries embedded differently.
Embedding search is semantic, not lexical. That is why it wins on paraphrases and loses on exact strings.
Concept
Exact IDs and rare terms
- A product code such as
KB-87-TKLcarries little learned meaning. Nearby vectors are other products with similar-looking codes, not the exact one. - Product names, internal jargon and new acronyms may be missing from the training data, so they land in arbitrary places.
- Fix: hybrid search. Run keyword search (BM25) next to vector search, then merge the lists.
- Vector databases such as Weaviate describe search that uses both semantic similarity and keywords.
- A model trained on your own domain also helps with rare vocabulary. Measure before you fine-tune.
Concept
Related, but not useful
- Embeddings find text on the same topic. That is different from text that answers the question.
- Fix: retrieve more candidates, then rerank with a model that reads the query and each candidate together.
Concept
Domain shift
- “Meaning” is whatever the training pairs made similar, so a general model may treat all legal clauses, or all medical notes, as roughly alike.
- Symptom: everything in a specialised collection scores about the same, so the ranking looks arbitrary.
- Fix: measure on your own queries first, then try another model, and consider fine-tuning only after measuring.
- Hybrid search and reranking do not repair a space that cannot tell your documents apart.
Concept
Mixed models give meaningless scores
- Each embedding model builds its own space. Two models can both output 1,536 numbers and still not be comparable.
- Failure is silent: the index accepts the vectors and returns scores.
- Typical cause: upgrading the model but re-embedding only new documents.
- Fix: store the model name and version with the index, and re-embed everything when it changes.
Diagram
Triage a bad result
Check yourself
Check: which one is closer?
Query q=(1,0). Document d1=(2,0) and document d2=(0.8,0.6). Which document does cosine similarity prefer, and which does Euclidean distance prefer?
Answer
Cosine: d1 scores 1.0 and d2 scores 0.8, so cosine prefers d1. Euclidean distance: d1 is 1.0 away and d2 is 0.04+0.36=0.632 away, so Euclidean prefers d2. d1 points exactly the same way as q but is twice as long, which only distance notices. If both were scaled to length 1, the two metrics would agree.
Check yourself
Check: the legal archive
A team embeds 20,000 contract clauses with a general-purpose model. Searches for “limitation of liability” return clauses on indemnity, termination and warranties with almost the same scores as the right ones. What failure is this, and what do you do first?
Answer
This is domain shift: a general model treats most contract clauses as roughly similar. First build a small set of real queries with known right clauses and measure. Then try another embedding model, and consider fine-tuning only if measurement shows a gap. Switching the metric will not separate clauses the model cannot tell apart.
Check yourself
Check: sizing a corpus
You will store 5 million chunks, each embedded as 768 float32 values. How much raw vector storage is that, and what does halving the dimensions do?
Answer
768×4=3,072 bytes per vector, and 5,000,000×3,072=15.36 GB. Halving to 384 dimensions gives 7.68 GB, because storage scales with dimension count. That excludes index overhead, and shorter vectors may lose some quality, so measure retrieval on your own queries before choosing.
Summary
Recap
- A dedicated embedding model maps a whole chunk or query to one vector; contrastive training makes matching pairs close.
- Dimensions and vector count set storage: count x dimensions x bytes.
- Cosine ignores length, dot product and Euclidean distance do not; on unit-length vectors all three agree.
- Embedding search is semantic, not lexical: use hybrid search for exact IDs and rare terms, reranking for related-but-unhelpful, and one embedding model for both index and queries.
- Use the metric the model expects and configure the index to match.
References
References & Sources
Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks (opens in a new tab)
Nils Reimers, Iryna Gurevych2019EMNLP 2019Paper
arXiv 1908.10084 (opens in a new tab)https://arxiv.org/abs/1908.10084
Used for Sentence-BERT was built to produce sentence embeddings that can be compared with cosine similarity, and cut similar-pair search over 10,000 sentences from about 65 hours to about 5 seconds.
Text and Code Embeddings by Contrastive Pre-Training (opens in a new tab)
Arvind Neelakantan, Tao Xu, Raul Puri, Alec Radford, et al.2022Preprint
arXiv 2201.10005 (opens in a new tab)https://arxiv.org/abs/2201.10005
Used for Contrastive pre-training on unsupervised data at scale gives high-quality text and code vector representations.
Vector embeddings (opens in a new tab)
OpenAI2026Documentation
https://developers.openai.com/api/docs/guides/embeddings
Used for OpenAI's guide lists 1536 default dimensions for text-embedding-3-small and 3072 for text-embedding-3-large, a dimensions parameter, and says its embeddings are normalized to length 1, so cosine and Euclidean give identical rankings.
Weaviate Database | Weaviate Documentation (opens in a new tab)
Weaviate2026Documentation
https://docs.weaviate.io/weaviate
Used for Weaviate describes search that uses both semantic similarity and keywords (hybrid search).
Keys: ← → move, Home End first and last, F full screen.