AI ENGINEERING · LLM FOUNDATIONS · FOUNDATIONS · 3 OF 35

Embeddings Explained: How AI Turns Text Into Vectors

How an embedding model turns text into a vector where meaning becomes position, why similar meaning lands close, and a worked cosine similarity on 3-d vectors. Dimensions and storage, normalising, semantic search with a vector index, clustering, dedup, recommendations and classification, embedding versus chat models, one model for queries and documents, and where embeddings fail.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
1 / 18

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Text → vector
  • close = similar
  • cosine on unit vectors
  • same model both sides
  • ANN index
  • hybrid for ids

Notes

The idea

An embedding is a list of numbers that stands for a piece of text. You give an embedding model a word, a sentence or a paragraph, and it returns one vector, always the same length for that model, however long the input was. The numbers are chosen during training with a single goal. Texts that mean similar things should get vectors that sit close together. Texts that mean different things should land far apart.

Text in, vector out
  • input: a word, a sentence, a paragraph, a whole chunk
  • output: one vector, a fixed length list of numbers
  • same model → same length, whatever the input size
  • goal: similar meaning → nearby vectors

Meaning as position

Think of each vector as a point on a map. In this toy two dimensional map, cat and kitten sit side by side, dog and puppy are just next to them, and invoice and receipt are off in a different corner. Distance on the map stands for difference in meaning. A real embedding space works the same way, except it has hundreds or thousands of dimensions instead of two, so it can capture many kinds of similarity at once.

A toy map in 2-d
   ^      kitten  cat
   |         puppy  dog
   |
   |                 invoice
   |              receipt
   +--------------------------->

cat ~ kitten: close
cat ~ invoice: far
real spaces: ~1,000 dimensions

Why close means similar

Why does similar meaning land close? Because the model is trained to make it so. Start from a language model that already understands text. Then show it millions of pairs that belong together, like a question and its answer, a title and its article, or two phrasings of the same thing. Pull each pair's vectors together, and push away the other texts in the same batch. This is called contrastive learning, and closeness becomes a learned stand in for meaning.

How it is trained
  • start from a language model
  • show it millions of pairs
  • that belong together: question → its answer title → its article two ways to say one thing
  • pull each pair close, push
  • other texts in the batch away
  • (contrastive learning)

Cosine similarity

To measure closeness we usually use cosine similarity. It looks at the angle between two vectors, not their length. Multiply the vectors element by element and add the results, that is the dot product. Then divide by the two lengths. A score of one means the same direction, zero means unrelated, at right angles, and minus one means opposite, which is rare for real text. Higher means more similar.

Measuring closeness
cos(a, b) = a · b / (|a| × |b|)

a · b = sum of a[i] × b[i]
|a|   = sqrt(sum of a[i]²)

 1   same direction
 0   unrelated (at right angles)
-1   opposite (rare for text)

it ignores length, only angle

A worked example

Let us do one by hand with tiny vectors. Cancel my order is zero point six, zero point eight, zero. Stop my purchase is four, three, zero. Where is my parcel is zero, three, four. The lengths are one, five and five. The dot product of a and b is two point four plus two point four, which is four point eight. Divide by one times five and you get zero point nine six. For a and c you get zero point four eight. So b is the closer match.

Cosine by hand, 3-d
a "cancel my order"  (0.6, 0.8, 0)
b "stop my purchase" (4, 3, 0)
c "where is my parcel" (0, 3, 4)

|a| = 1    |b| = 5    |c| = 5
a·b = 0.6×4 + 0.8×3 + 0 = 4.8
cos(a,b) = 4.8 / (1×5) = 0.96
a·c = 0 + 0.8×3 + 0 = 2.4
cos(a,c) = 2.4 / (1×5) = 0.48
b is the better match for a

Normalising

Normalising makes this cheaper. Divide each vector by its own length, so every vector has length one. Four, three, zero becomes zero point eight, zero point six, zero. Once vectors are unit length, cosine similarity is just the dot product, and ranking by straight line distance gives the same order. So you normalise once when you store a vector, and every comparison after that is a fast dot product. Many models already return unit vectors, but check rather than assume.

Unit vectors
normalise: divide by the length
  b (4, 3, 0) / 5 = (0.8, 0.6, 0)

for unit vectors:
  cosine = dot product
  euclidean ranks the same way

normalise once at write time,
then compare with a fast dot
many models already output unit
vectors: check, do not assume

Dimensions

Real vectors are long, commonly from about three hundred to three thousand numbers. Unlike our toy, no single number means animal or money. Meaning is spread across all of them. Size matters for cost. Stored as four byte floats, a million documents at one thousand and twenty four dimensions take about four gigabytes. Quantising to eight bit integers cuts that about four times, and some models are trained so you can keep only the first few hundred numbers with a small loss.

Real sizes
common sizes: 384, 768, 1,024,
  1,536, 3,072 dimensions
no single number means "animal"

storage, float32 = 4 bytes each:
  1M docs × 1,024 × 4 B ≈ 4 GB
int8: ~4× smaller
binary: ~32× smaller
some models let you truncate
  (1,024 → 256) with small loss

Vector indexes

How do you find the nearest vectors fast? The exact way compares the query with every stored vector. That is order n times d work, and it is fine up to about a hundred thousand vectors. Beyond that you use approximate nearest neighbour search. H N S W builds a layered graph you walk toward the query, and I V F only searches the few clusters closest to it. You give up a little recall, often finding ninety five to ninety nine percent of the true top results, in milliseconds.

Finding the nearest
  • exact: compare with every vector, O(n × d) fine up to ~100k vectors
  • approximate (ANN): HNSW: a layered graph you walk toward the query IVF: search a few clusters
  • ~95–99% recall, milliseconds over millions of vectors

Other uses

Search is only the start. Cluster thousands of support tickets by topic with k means on their vectors. Find near duplicates by flagging pairs above a similarity threshold you tune on real examples. Recommend articles close to what a user already read. Train a small, cheap classifier on top of the vectors instead of calling a chat model for every item. And retrieval augmented generation, covered later in this track, is built on exactly this search.

What else they do
  • clustering: group tickets by topic with k-means
  • dedup: flag pairs above a tuned similarity threshold
  • recommendations: items near what a user liked
  • classification: train a small classifier on the vectors
  • RAG: fetch the chunks a chat model needs to answer

Embedding vs chat model

An embedding model is not a chat model. It reads text and returns one vector. It never writes text, it is usually much smaller, and it is fast and cheap enough to embed millions of chunks in batches. A chat model generates a reply token by token. In a typical system they work as a team. The embedding model finds the five best chunks, and the chat model reads them and writes the answer.

Two different models
  • embedding model text → one vector no text generation small, fast, cheap, batched
  • chat model text → text, token by token slower, pricier per token
  • vectors from two models are not comparable

One model for both

Every embedding model builds its own space. A vector from one model compared with a vector from another is noise, even when both have the same length. So the query and the documents must be embedded by the same model and version. Store the model name with every vector, and plan for re-embedding everything when you upgrade. Some models also expect a short prefix or task instruction on queries versus documents. Follow the model card exactly.

Same model, both sides
  • each model has its own space: model A vectors vs model B
  • vectors = noise, even if the length matches
  • store the model + version with every vector
  • new model → re-embed all
  • some models want a "query:" or task prefix: follow it

Where they fail

Embeddings capture topic well, and some details badly. Hotels with a pool and hotels without a pool share almost every idea, so they land close together. Product codes and error ids that differ by one digit look almost identical. Numbers like under fifty dollars are not treated as a filter. The fixes are well known. Combine vector search with keyword search, known as hybrid search, use metadata filters for prices and dates, and add a reranker to reorder the top results.

Known weak spots
  • negation: "with a pool" and "without a pool" land close
  • exact ids: SKU-48213 vs SKU-48231 look the same
  • numbers: "under 50 USD" is not a filter
  • rare jargon the model never saw in training
  • fix: hybrid search (vector + keyword), metadata filters

Common mistakes

The common mistakes. Mixing vectors from different models or versions in one index. Copying a similarity threshold like zero point eight from a blog post, when scores vary a lot between models. Embedding whole documents as one vector, so their meaning blurs into an average. Sending text past the model's input limit, where it is silently cut off. Having no keyword fallback for ids. And never measuring whether the right chunk actually comes back in the top results.

Mistakes to avoid
  • mixing models or versions in one index
  • one fixed threshold (0.8) copied from another model
  • whole documents as one vector: meaning blurs
  • text past the input limit, silently cut off
  • no keyword fallback for ids
  • never measuring recall

Numbers worth knowing

Numbers worth knowing, all ballparks. Vectors of about four hundred to three thousand dimensions. Input limits from about five hundred to eight thousand tokens, with chunks usually a few hundred to a thousand tokens. Four bytes per dimension, so a million vectors of about a thousand dimensions is roughly four gigabytes. Exact search is fine up to around a hundred thousand vectors. Approximate search answers in milliseconds over millions. Embedding costs a small fraction of chat generation.

Numbers worth knowing
dimensions          ~384 – 3,072
input limit      ~512 – 8k tokens
chunk size      ~200 – 1,000 tokens
float32 storage     4 bytes / dim
1M × 1,024 dims          ~4 GB
int8 / binary      ~4× / ~32× less
exact search fine   up to ~100k
ANN query, millions    ~1–10 ms
ANN recall           ~95–99%
cost: a small fraction of chat

Say it like this

How to say it. We chunk documents to about five hundred tokens and embed them with one embedding model, normalised, and stored with the model version. Queries go through the same model. We take the top twenty by cosine similarity from an H N S W index, add keyword search for ids and codes, and rerank. We track recall at five on a labelled set of real questions. That shows you know both the math and the failure modes.

In the interview
  • "We chunk docs to ~500 tokens and embed them with one model, normalised, stored with the model version. The query uses the same model. Cosine top 20 from an HNSW index, plus keyword search for ids, then a reranker. We track recall at 5 on a labelled question set."

Interview questions

Q1What is an embedding?

A fixed-length vector of numbers produced by a model so that texts with similar meaning are close together in the vector space. It lets software compare meaning with simple math instead of matching keywords.

Q2How is cosine similarity calculated and why use it?

Take the dot product of the two vectors and divide by the product of their lengths. It measures the angle between them, from -1 to 1, ignoring magnitude, which is what matters for comparing meaning. For normalised vectors it equals the dot product.

Q3Why do texts with similar meaning get similar embeddings?

Embedding models are trained contrastively on large sets of related pairs, such as questions and their answers, pulling each pair's vectors together and pushing unrelated texts apart. Closeness in the space becomes a learned proxy for semantic similarity.

Q4Why normalise embedding vectors?

Once vectors have length 1, cosine similarity is just the dot product, which is cheaper, and euclidean distance ranks results in the same order. Normalise once at write time so every comparison is a fast dot product.

Q5How does an embedding model differ from a chat model?

An embedding model maps text to one vector and does not generate text; it is smaller, faster and cheaper per token. A chat model generates text token by token. In RAG the embedding model finds relevant chunks and the chat model writes the answer from them.

Q6Can you compare embeddings from two different models?

No. Each model defines its own space, so cross-model similarity scores are meaningless even when dimensions match. Embed queries and documents with the same model and version, store the version with each vector, and re-embed everything when you switch.

Q7How do you search millions of embeddings quickly?

Use an approximate nearest-neighbour index such as HNSW (a layered proximity graph) or IVF (search only the nearest clusters). They return about 95 to 99 percent of the true top results in milliseconds, trading a little recall for large speed gains over exact O(n·d) search.

Q8Where do embeddings perform poorly, and how do you compensate?

They blur negation, exact identifiers like SKUs or error codes, numeric constraints and rare jargon. Combine vector search with keyword search (hybrid), apply metadata filters for prices and dates, and rerank the top candidates.