Vector Embeddings Explained: How AI Turns Meaning Into Math
Vector embeddings let AI compare meaning as geometry. Here's how models create them, how vector search finds matches fast, and where they break.

Vivek Gupta · IIT Delhi alumnus
· 12 min read

Ask ChatGPT, Claude or any modern search box a question and it rarely fails just because you phrased it oddly. Type "cheap place to eat near me" and it can still surface a page that only ever says "budget-friendly restaurant nearby," with no shared keywords. That trick, used everywhere from search engines to recommendation feeds to retrieval-augmented generation (RAG, where a model looks up relevant text before answering), rests on one idea: vector embeddings.
A vector embedding is a list of numbers, usually a few hundred to a few thousand of them, that represents the meaning of a piece of text, an image or a sound as a point in space. Pieces with similar meaning end up as nearby points. Once meaning becomes geometry, "find things like this" becomes a distance calculation a computer can do in milliseconds, even across billions of items.
Key takeaways
- An embedding is a point in space. A model converts text, images or audio into a vector (a list of numbers); items with similar meaning land close together.
- "Close" usually means cosine similarity, a measure of the angle between two vectors, not their length.
- Comparing a query to every stored vector doesn't scale. Real systems use approximate nearest neighbor (ANN) search, commonly a graph method called HNSW, to search millions of vectors in milliseconds.
- Embeddings inherit the biases and blind spots of their training data, and a query must be embedded with the same model as the documents it searches.
- Embeddings are the retrieval half of RAG: they find the relevant text; the language model still has to reason over it.
What is a vector embedding, in plain terms?
Think of a vector embedding as GPS coordinates for meaning. A GPS coordinate turns a location into two numbers (latitude, longitude), and places close in meaning, like two addresses on the same street, end up close in that coordinate space. A text embedding does the same with far more numbers: an embedding model reads a sentence and outputs a vector, a fixed-length list of floating-point numbers, where each number is one coordinate in a high-dimensional space, meaning simply more coordinates than the three we're used to.
OpenAI's current embedding models, for instance, return 1,536 or 3,072 numbers per piece of text by default, and let you shorten that vector to save on storage and compute, as long as you renormalize it afterward (OpenAI's embeddings guide). No single dimension corresponds to a human-readable concept like "is this about food"; meaning is spread across all of them together, in patterns the training process discovered on its own.
This is exactly the representation that sits inside a transformer model before its final output layer; we cover how a transformer builds it in how transformers and attention actually work. An embedding is essentially a snapshot of that internal state, pulled out and used as a standalone, comparable object.
How a model learns to turn meaning into numbers
Embedding models aren't hand-coded. They're trained so that pieces of text used in similar ways end up with similar vectors. A common approach is contrastive training: the model sees pairs of text that are known to be related (a question and its correct answer, two sentences that paraphrase each other) and pairs that are unrelated, and it is nudged to push the vectors of related pairs together and unrelated pairs apart.
This matters because plain language models weren't originally built for this job. A 2019 paper on Sentence-BERT notes that BERT, the influential 2018 language model, was designed to score two sentences' similarity only when fed both together, so finding the most similar pair among 10,000 sentences needed about 50 million comparisons, roughly 65 hours of compute. Sentence-BERT restructured the model so each sentence gets its own independent vector, comparable with simple arithmetic afterward, cutting that search to about 5 seconds with comparable accuracy (Reimers and Gurevych, 2019). That shift, a vector you can compare cheaply instead of a score you can only compute pairwise, is what makes embeddings useful for search at all.
Measuring "closeness": cosine similarity and other distance metrics
Once you have two vectors, how do you tell if they're "close"? The most common measure is cosine similarity: the cosine of the angle between two vectors. It ranges from -1 (pointing in opposite directions) to 1 (pointing in exactly the same direction), and it ignores vector length, only direction matters. That's useful because it means a short, precise sentence and a long, rambling one about the same topic can still score as similar.
Seeing the math
The arithmetic is simple enough to write without any library. Here it is in plain Python, run against small, made-up 4-number vectors (real embeddings have hundreds of dimensions; these are shortened purely to make the numbers readable):
import math
def cosine_similarity(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b)
# Toy 4-dimensional vectors, chosen by hand to illustrate the idea,
# not real output from an embedding model.
king = [0.90, 0.10, 0.80, 0.20]
queen = [0.85, 0.15, 0.10, 0.80]
man = [0.95, 0.05, 0.85, 0.10]
woman = [0.80, 0.20, 0.15, 0.85]
print(round(cosine_similarity(king, queen), 3)) # 0.705
print(round(cosine_similarity(king, man), 3)) # 0.995
Running this (Python 3.11) gives king and man a similarity of 0.995, while king and queen score 0.705, still related, but clearly less so by this toy construction. This is a hand-built illustration of the idea, not a measurement from a real model, but it shows why the geometry is useful: once meaning is a direction in space, "how related are these two things" becomes one line of arithmetic.
Cosine similarity isn't the only option. The table below compares the three metrics you'll actually meet in a vector database, using the names pgvector (the popular Postgres extension for vector search) gives them (pgvector documentation):
| Metric | What it measures | Good for |
|---|---|---|
| Cosine similarity | The angle between two vectors, ignoring length | Text embeddings, where length often reflects document length, not relevance |
| Euclidean (L2) distance | Straight-line distance between two points | Cases where vector magnitude itself carries meaning, such as some image or audio embeddings |
| Dot product (inner product) | Combines angle and length | Embeddings explicitly trained to use magnitude as a signal, such as some recommendation models |
If you're unsure which to use, check your embedding model's documentation. Mixing the wrong metric with a model trained for a different one quietly produces worse results, with no error message to warn you.
Why you can't just compare a query to every vector
The approach above, compute the similarity between a query and every stored vector, then keep the highest-scoring ones, is exact or brute-force search. It's correct: it always finds the true closest matches. It's also linear in the number of stored vectors, so it slows in direct proportion to how much data you have. Pgvector, for example, runs exact search by default and recommends an index only once that scan becomes too slow.
At a few thousand documents, brute force is often fast enough. At tens of millions, a single query touching every vector adds latency (response delay) a user or an API notices, the same scaling problem Sentence-BERT ran into with pairwise sentence comparison, just at the retrieval layer instead of the model layer. The fix is the same: stop comparing against everything, and search smartly instead.
Inside HNSW: how vector search finds matches in a few hops
The standard answer is approximate nearest neighbor (ANN) search: trade a small, controllable amount of accuracy for a large speedup. The most widely used ANN method today is HNSW (Hierarchical Navigable Small World), introduced by Yurii Malkov and Dmitry Yashunin. It builds a graph connecting nearby vectors, stacked into layers: a sparse top layer with a few points and long-range links, growing denser below it, down to a bottom layer holding every vector with short-range links (Malkov and Yashunin, 2016).
A search starts at a fixed entry point in the sparsest top layer and greedily hops to whichever neighbor is closer to the query, the way you'd ask directions by jumping between highways before dropping onto local streets. When no neighbor in the current layer is closer, the search drops down one layer and continues, ending with a fine-grained check among nearby vectors in the bottom layer. The authors report search time that scales logarithmically with the number of vectors: a dataset ten times larger adds only a little search time, not ten times as much.

This is approximate, not exact: a tiny number of true nearest neighbors can be missed because the greedy search commits to a path early. The quality of the result is measured as recall, the share of the real top matches the search actually returns, and it's a dial you can turn. Pgvector exposes this as a tunable parameter (hnsw.ef_search) that trades query speed for higher recall, and offers IVFFlat as an alternative index that builds faster and uses less memory but gives a worse speed-to-recall trade-off than HNSW for the same settings.
Distance metrics and index types at a glance
| Approach | Accuracy | Speed at scale | When to use it |
|---|---|---|---|
| Exact (brute force) | Perfect, always finds the true nearest vectors | Slows linearly as data grows | Small collections, or when correctness matters more than speed |
| IVFFlat index | Approximate, tunable via probes |
Fast to build, moderate query speed | Memory-constrained setups, or collections that change often |
| HNSW index | Approximate, tunable via ef_search |
Slower to build, fastest queries at high recall | Most production search and RAG systems at meaningful scale |
Where embeddings go wrong
Embeddings feel like magic until you hit one of their real limits:
- Query and document must share a model. A vector from one embedding model isn't comparable to one from another; OpenAI's own guidance is explicit that swapping models means re-embedding your entire collection, not just new queries.
- They inherit bias from training data. A well-known 2016 study found that word embeddings trained on ordinary news text encoded gender stereotypes "to a disturbing extent," for instance associating "receptionist" with "female" more strongly than warranted, while keeping correct associations like "queen" with "female." The same researchers showed this can be partly, not fully, corrected with a dedicated debiasing step (Bolukbasi et al., 2016). Don't assume an off-the-shelf model is neutral.
- Similarity isn't correctness. Two sentences can sit close in vector space while one contradicts the other, since embeddings capture topic and style more reliably than logical relationships like negation.
- Stale indexes drift quietly. If source documents change and you don't re-embed them, search quality degrades with no error to flag it.
- Shortened vectors need renormalizing. Truncate an embedding's dimensions by hand instead of using a model's built-in option, and you must renormalize the result or your distance math breaks.
Before shipping a feature built on vector search, check:
- Every document and query use the exact same model and dimension count.
- Your distance metric matches what the model was trained to optimize for.
- You've chosen a recall-versus-speed tradeoff deliberately, tested against real queries, not a demo.
- You have a plan to re-embed documents when the underlying content changes.
- You've tested queries related to, but not synonymous with, your source text, to catch "close" vectors that aren't useful matches.
From embeddings to RAG: how this fits into a bigger system
Embeddings rarely show up alone. In a RAG system, they handle retrieval: turning a question and a store of documents into vectors, then using similarity search to pull out the passages most likely to help. The language model reads those passages and writes an answer grounded in them, instead of relying only on what it memorized during training. To build one of these end to end, see build a RAG app from scratch, which covers the embedding and search steps here in working code. And since an embedding model has to read raw text before it can do anything, it depends on the same step covered in how tokenization works.
Agents that search a knowledge base, a ticket history or a codebase before acting are doing the same thing under the hood: embed, search, retrieve, then reason. Understanding the geometry underneath makes it far easier to debug an agent that keeps retrieving the wrong document, instead of just swapping vector databases and hoping.
How to go deeper
Reading about embeddings gets you the intuition; building with them makes it stick. Try brute-force cosine search over a few hundred of your own notes or emails, the way the code example above does, before reaching for a vector database. You'll feel exactly where it starts to slow down, the moment ANN search stops being abstract and becomes obviously necessary.
For structured, hands-on practice with retrieval, tool use and the rest of what goes into a working AI system, that's the core of our AI Automation & Agents Bootcamp: a live, online, lab-heavy program where you build retrieval over your own documents, get your work reviewed by instructors, and leave with a portfolio project and a verifiable certificate.
Frequently asked questions
What's the difference between an embedding and a vector database?
An embedding is a single vector representing one piece of content. A vector database (or a vector index inside a regular database, like pgvector in Postgres) stores millions of embeddings and quickly answers "which of these are closest to this new vector," usually with an ANN method like HNSW.
Is cosine similarity always the best metric to use?
No. It's the common default for text embeddings because it ignores vector length, but some models are trained for dot product or Euclidean distance instead. Check your model's documentation, and don't mix metrics across models trained for a different one.
How many dimensions should an embedding have?
It depends on the model, typically a few hundred to a few thousand. More dimensions capture finer distinctions but cost more to store and search. Several current models let you request a shorter vector directly, usually better than truncating one yourself.
Can embeddings be biased or wrong?
Yes. They reflect whatever patterns exist in their training data, including social biases, and they measure similarity, not logical truth, so two vectors can sit close even when the underlying statements disagree. Test retrieval quality against real examples from your own use case.
Do I need a GPU to generate embeddings?
Not necessarily. Many providers offer embeddings through an API call, so computation happens on their infrastructure. Running an open-source model locally over a large collection is faster with a GPU, but a CPU handles smaller collections fine, just more slowly.
Vector embeddings turn a question most people find intuitive, what does this mean and what else is like it, into arithmetic a machine can do at scale. Once that geometry is clear, search, recommendations, RAG and much of what gets called an AI agent's "memory" stop looking like separate tricks and start looking like one idea applied in different places.
Found this useful?
Next cohort starts 2 Dec
AI Automation & Agents Bootcamp
Design, build and run AI agents and automations in production.
- Mondays and Wednesdays, 7–10 PM IST
- 6 weeks · 12 sessions · 36 live hours · Online
- For: Operations, product and technical teams, developers and analysts
- ₹44,999 per seat, taxes extra

About the author
Vivek Gupta · IIT Delhi alumnus
Vivek Gupta is an IIT Delhi alumnus and PhD scholar, an AI researcher and serial entrepreneur with 14 years of building technology at MakeMyTrip, Goibibo, Wissen and Jubilant FoodWorks.
Discussion
No comments yet. Start the discussion.