Lesson 4.1: What an embedding is
An embedding turns text into numbers so similar meanings sit close together. Learn how to compare embeddings, what they miss and what they cost to store.
Search the help centre of almost any app for "money back" and you will often get nothing, because the article you need is titled "Refund policy". The words are different, the meaning is the same, and a program that only compares letters cannot see it. Embeddings are the standard way modern AI applications get around this. By the end of this lesson you will be able to explain what an embedding is without hand-waving, compute how close two embeddings are with three different measures, say which measure most systems use and why, estimate how much memory and money a collection of embeddings will take, and name the things embeddings are bad at so that they do not surprise you in production. You should have read the earlier lessons in this track, especially the one on tokens and context windows, because an embedding model reads tokens too. You do not need advanced mathematics; if you can multiply and add, you can do every calculation below, and the simulators will do the arithmetic for you.
The problem: computers compare letters, people mean things
Start with how a basic search works. A keyword search breaks your query into words and looks for documents that contain those words. It is fast, predictable and easy to explain, and for many jobs it is exactly right: finding an invoice number, a person's name or an error code. But it has a blind spot. Suppose a bank's help centre has these four articles.
"How to get a refund for a failed UPI payment"
"Changing your registered mobile number"
"What to do if your debit card is blocked"
"Understanding your loan EMI schedule"
A customer types: "my transaction failed and I want my money back". A keyword search looks for "transaction", "failed", "money" and "back". The first article contains "failed" and "refund" but not "money" or "back", so it matches on only one word, and an article about a blocked card might match on a different stray word. The system has no idea that "money back" and "refund" are the same idea, or that "transaction" and "payment" are close cousins.
You could patch this with a list of synonyms, and many search systems do. But synonym lists are never finished. People write "paisa wapas", "chargeback", "reversal", "amount deducted but not credited", and each new phrase needs a new entry. What we want is a system that has learned, from a huge amount of text, which phrases tend to mean the same thing, and can express that learning as something a computer can compare quickly.
That is the job of an embedding.
The core idea: a position in meaning-space
An embedding is a list of numbers that represents a piece of content, usually a piece of text, in such a way that content with similar meaning gets similar numbers. The list is called a vector, and the number of entries in it is its dimension.
The easiest way to picture this is a map. Every place in India can be described by two numbers, latitude and longitude. Two places with similar numbers are near each other. Mumbai and Pune are close on the map; Mumbai and Guwahati are far. The map does not need to "know" anything about the cities; closeness in the numbers is closeness in the world.
An embedding does the same trick for meaning instead of geography. A model reads a sentence and outputs, say, 768 numbers. Those 768 numbers are a position in a 768-dimensional space. In that space, "How to get a refund for a failed UPI payment" and "my transaction failed and I want my money back" end up near each other, while "Changing your registered mobile number" ends up elsewhere. Nobody wrote a rule saying so. The model learned to put them there.
Two things are worth holding on to right away.
1. The individual numbers mean nothing on their own. Dimension 17 is not "about money" and dimension 400 is not "formal tone". The meaning is in the pattern across all the numbers, and in the distances between vectors. You cannot read an embedding the way you read a spreadsheet row.
2. Closeness is the only thing you use. Everything an application does with embeddings comes down to asking, "which stored vectors are closest to this one?" The next two lessons in this module build on exactly that question.
Predict first: a model gives each of three sentences a position. Sentence A is "Pay my electricity bill", sentence B is "Settle the power bill online" and sentence C is "Book a train ticket to Pune". Which pair do you expect to be closest, and which pair furthest? Think about it before reading on.
The pair A and B should be closest, because they describe the same task in different words. C is about a different task entirely, so it should sit far from both. If a model got this wrong, you would not use it. That simple test, "does it put obviously similar things close and obviously different things far?", is the first check you can run on any embedding model.
How an embedding model is made and used
An embedding model is a neural network, like the chat models you met earlier, but trained for a different job. A chat model is trained to predict what text comes next. An embedding model is trained to produce a vector, and the training pushes vectors of related texts together and vectors of unrelated texts apart. The details of the training methods vary and are beyond this lesson. What matters for an engineer is how you use one.
The workflow has three steps.
1. Embed your documents once. You split your content into pieces (the next lessons cover how to choose the pieces), send each piece to the embedding model, and store the vector it returns next to the original text.
2. Embed each query when it arrives. The customer's question goes through the same model and becomes a vector.
3. Find the nearest stored vectors. You compare the query vector to the stored ones and return the closest few, together with their text.
Notice the division of labour. The expensive, slow part, running the model, happens once per document and once per query. The comparison afterwards is simple arithmetic on numbers, which computers do extremely fast.
A few rules follow from this, and breaking them is the source of many silent bugs.
Use the same model for documents and queries. Vectors from different models live in different spaces. Comparing a vector from model X with one from model Y is like comparing a latitude from a map of India with a coordinate from a map of a football pitch. The numbers will compute, and the answer will be meaningless.
Record which model produced each vector. If you switch models later, you must re-embed everything. Store a model name and version beside the vectors so you know what you have.
Vectors have a fixed length per model. A model that outputs 768 numbers always outputs 768. Your storage must be designed for that number.
The text goes to whoever runs the model. If you call a hosted embedding service, your documents and queries are sent to that provider. Check what your data rules allow before embedding customer messages or internal papers.
There is a limit on how much text one embedding can describe. Each model reads only up to a maximum number of tokens. Long documents have to be cut into pieces, and one vector for a whole book would blur everything together.
Measuring closeness: three ways
Once you have two vectors, you need a number that says how close they are. Three measures are in common use. We will work each one out by hand using tiny two-dimensional vectors, so that you can see the arithmetic. Real vectors have hundreds of entries, but the formulas are the same.
Take vector A = (3, 4) and vector B = (4, 3).
Dot product
Multiply matching entries and add them up: 3 × 4 + 4 × 3 = 12 + 12 = 24. A large dot product means the vectors point the same way and are also long. The weakness is that it mixes direction with length. A long vector scores high against almost everything.
Euclidean distance
This is the ordinary straight-line distance from the geometry you learnt in school. Subtract matching entries, square them, add, and take the square root: the differences are (3 − 4) = −1 and (4 − 3) = 1, so the distance is the square root of 1 + 1, which is about 1.41. Here a smaller number means closer. This is intuitive, but it also depends on length.
Cosine similarity
This measures only the angle between the two vectors, ignoring their length. You take the dot product and divide by the length of each vector. The length of A is the square root of 3 × 3 + 4 × 4 = 25, which is 5. The length of B is also 5. So the cosine similarity is 24 divided by (5 × 5), which is 0.96. The result is always between −1 and 1: 1 means they point the same way, 0 means they are unrelated (at right angles), and −1 means they point in opposite directions.
Most text-search systems use cosine similarity, or an equivalent. The reason is that the length of a vector often reflects accidental things, such as how long the text was, rather than what it was about. Cosine ignores those accidents. Some embedding models return vectors already scaled to a length of exactly 1, and for such vectors the dot product and the cosine are the same number. Your model's documentation says which it does.
Three worked examples
Here are three pairs, so you can see how the measures behave.
Pair · Vectors · Dot product · Euclidean distance · Cosine similaritySame direction, same length · (3, 4) and (3, 4) · 25 · 0 · 1.00
Same direction, B twice as long · (3, 4) and (6, 8) · 50 · 5 · 1.00
At right angles · (3, 4) and (−4, 3) · 0 · 7.07 · 0.00
Look at the second row. B is exactly A stretched to double its length. Euclidean distance says they are 5 units apart, which sounds far. Cosine says they are identical in direction, a perfect 1.00. If these were embeddings of a short sentence and a long paragraph on the same subject, cosine would give the answer a human wants. The third row shows the opposite: two vectors at right angles score 0 on cosine and also 0 on dot product, meaning "no relationship".
Try the numbers yourself. The first output below is the cosine similarity.
Try setting B to exactly double A, then watch the Euclidean distance grow while the cosine stays at 1. That is the reason cosine is the usual choice.
A worked example: ranking help-centre articles
Now let us put real-looking text through the idea. Imagine an embedding model has scored five help-centre snippets against the customer's query "my transaction failed and I want my money back". The scores below are illustrative: we made them up to show the shape of the result, and a real model would give different numbers.
Three lessons come out of this picture.
First, the top two results contain almost none of the customer's words. "Refund" and "debited but not confirmed" are the right answers, found by meaning rather than spelling. This is what keyword search could not do.
Second, no result scores 0. The EMI article gets 0.31 even though it has nothing to do with the question. Embeddings give a score to everything, because every pair of vectors has some angle between them. This matters later: a system that always returns "the top three" will return three results even when none is any good. You will need a threshold, or a way to say "I found nothing relevant".
Third, the blocked-card article scores higher (0.41) than the mobile-number article (0.22). Both are wrong answers, but the card one is at least in the same neighbourhood, payments and cards. Embeddings capture a sense of topic and not only of exact meaning, which is useful for "find related articles" and a risk for "find the exact answer".
Predict first: if you ran the same query against a different embedding model, would you expect the scores to be the same? Decide, then read on.
You should not. A different model has a different space. The ranking of the top results will often agree if both models are decent, but the actual numbers are not comparable across models. A score of 0.82 from one model can be a weaker match than 0.65 from another. Never set a threshold by copying a number from a blog post; measure on your own data with your own model.
Dimensions, size and cost
Every vector you store takes space, and for a product with millions of text pieces the space adds up. The arithmetic is simple. Each entry is a number, usually stored in 4 bytes (a standard "float32" number). So one vector costs the number of dimensions multiplied by 4 bytes.
A single vector of 768 dimensions takes 3,072 bytes, about 3 kilobytes. That sounds like nothing. Now multiply. A company has 50,000 documents and cuts each into about 20 pieces. That is 1,000,000 vectors. At 768 dimensions and 4 bytes each, the vectors alone take 1,000,000 × 768 × 4 = 3,072,000,000 bytes, roughly 3.07 gigabytes. Double the dimensions and you double the storage. Store the numbers in half the space (2 bytes) and you halve it, at some cost in precision. The simulator lets you try these choices.
Notice that the one-time cost is separate from the storage. You pay to embed each piece when you first add it, and again whenever you change models or change how you cut the text. You also pay a small amount to embed every query, but queries are short, so the query cost is usually far smaller than the cost of embedding the documents.
Why more dimensions is not always better
A vector with more dimensions can hold finer distinctions, so larger models and larger vectors often perform better on difficult searches. But the gain shrinks while the costs rise in a straight line: more memory, slower comparisons, a larger bill for the database. Some embedding models let you shorten a vector deliberately and keep most of the quality; check your model's documentation to see if yours does. The right answer is the smallest vector that meets your quality bar on your own test questions, which the evaluation lessons later in this track will show you how to build.
What embeddings capture, and what they miss
An embedding compresses a piece of text into a fixed list of numbers. Compression always loses something. Knowing what is lost lets you predict where your system will fail.
They capture topic and rough meaning. "Refund", "money back" and "reversal of a failed payment" cluster together. This is a strength for natural-language questions.
They are weak on exact strings. Order numbers, invoice IDs, PAN formats, error codes and product SKUs have little "meaning" to the model. Searching for "ERR-40291" by embedding may return articles about other errors that merely look similar. For exact strings, a keyword search is better. Many production systems run both and combine the results, which a later lesson on retrieval quality covers.
They can blur negation. "Loans are available to salaried people" and "Loans are not available to salaried people" are nearly identical in words and often land close together. The vector captures what the sentence is about more strongly than whether it says yes or no. Do not rely on embedding similarity to tell a statement from its opposite.
They can struggle with numbers and units. "Interest of 12% a year" and "interest of 21% a year" are close in the space even though the difference matters enormously to a borrower. If numbers decide the answer, check them in a second step.
They reflect their training data. A model trained mostly on general English web text may handle your lending jargon, or Hindi written in Roman letters, less well than your own test shows you. Some models are trained on many languages and place the same idea in different languages near each other, but how well they do this varies. Test with the languages and the vocabulary your users really write.
They carry the biases of their data. If the training text associates certain words or groups with certain ideas, the space can reflect that. For anything that affects people, such as ranking applicants, check results for unfair patterns rather than assuming the geometry is neutral.
"Close" does not mean "correct". An embedding finds text that is about the same thing. It cannot tell you whether that text is true, current or the right answer to the question. The retrieval and grounding lessons that follow deal with this.
More than text
The word embedding is not limited to text. Models exist that embed images, audio, product listings and even rows of a table. Some embed text and images into the same space so that you can search pictures with a sentence. The idea is always the same: turn the thing into a vector so that similar things land close together. In this track we focus on text because that is where most LLM applications start.
A second worked example: finding duplicate support tickets
Embeddings are useful beyond search. Suppose a lender's support team receives 400 tickets a day and many are the same issue phrased differently: "NACH mandate failed", "auto-debit not registered", "my EMI mandate was rejected". A team could embed each new ticket and compare it with the open ones. If the cosine similarity to an existing ticket is above a chosen threshold, the system suggests "possible duplicate of ticket 8812".
How do you choose the threshold? Not by guessing. The team takes 200 pairs of tickets that a human has labelled "same issue" or "different issue", computes the cosine for each pair, and looks at the two groups of scores. If the "same" pairs mostly score between 0.80 and 0.95 and the "different" pairs mostly score below 0.60, a threshold around 0.75 will catch most duplicates and rarely group unrelated tickets. Where the two groups overlap, the team must decide what costs more: merging two different tickets by mistake, or missing a duplicate. That is a business decision, and the embedding can only give the score.
Other uses follow the same pattern: clustering feedback into themes, recommending similar products, checking whether a new question is already in the FAQ, and detecting text that is far from anything the system has seen. Each is "turn things into vectors, then measure closeness".
A third worked example: choosing the number of results to return
When you search, you usually take the top k nearest vectors, where k is a small number such as 3 or 5. How should you choose k? Consider a chatbot that will paste the retrieved pieces into a prompt. Each piece is about 200 tokens. With k = 3 you add 600 tokens; with k = 10 you add 2,000 tokens. Since you pay for every token you send and the model must read them all, a larger k costs more money and slows the response. But a larger k also raises the chance that the right piece is among them.
Suppose that on a test set of 100 questions, the right piece was in the top 1 for 62 questions, in the top 3 for 84, in the top 5 for 91 and in the top 10 for 95. Going from 3 to 5 gains seven questions for 400 extra tokens per query, while going from 5 to 10 gains four questions for 1,000 extra tokens. The numbers are invented to show the method, but the method is real: measure the hit rate at several values of k, price the tokens, and pick where the gain stops being worth the cost. You will do this properly when you reach the evaluation module.
Common mistakes
Mixing models. Embedding documents with one model and queries with another gives meaningless distances. Always store the model name with the vectors.
Treating a similarity score as a probability. A cosine of 0.8 does not mean "80 per cent likely to be right". It is a position, not a probability.
Copying thresholds from elsewhere. The scale of the scores depends on the model and the data. Measure your own.
Embedding giant documents whole. One vector for a long report blurs its parts. Cut into pieces first.
Using embeddings for exact lookups. IDs, codes and names are better served by keyword search or a normal database query.
Trusting nearness to mean truth. The nearest text may be outdated, from the wrong product or simply wrong.
Forgetting that every query returns something. Without a minimum score or a "nothing relevant" path, the system will always show results.
Ignoring the bill. Re-embedding a large collection after each small change is a common source of a surprise cost. Plan changes in batches.
Skipping a quick sanity check. Before building anything, embed a handful of sentences you understand and see if the nearest ones make sense.
Key takeaways
An embedding is a list of numbers that places a piece of content in a space where similar meanings are close together.
The individual numbers have no meaning alone; only distances and angles between vectors matter.
Cosine similarity compares direction and ignores length, which is why most text search uses it.
Use the same embedding model for documents and queries, and store which model made each vector.
Memory grows in a straight line with the number of vectors, the dimensions and the bytes per number.
Embeddings find related text, not true text, and they are weak on exact strings, negation and numbers.
Always choose thresholds and the number of results from your own test data.
Check yourself
1. Why does a keyword search miss "money back" when the article says "refund"?
It compares the actual words, and the two phrases share none, so it cannot see that they mean the same thing.
2. For vectors (3, 4) and (6, 8), what is the cosine similarity, and what does it tell you?
It is 1.00, because the vectors point in exactly the same direction; the second is just longer.
3. A team embeds its documents with one model and later embeds queries with a newer one. What goes wrong?
The two models use different spaces, so the distances between a query and a document no longer mean anything.
4. A collection has 200,000 pieces, 1,024 dimensions and 4 bytes per number. Roughly how much memory do the vectors need?
200,000 × 1,024 × 4 is about 819 million bytes, so roughly 0.8 GB.
5. Name two kinds of search where an embedding is a poor choice on its own.
Exact lookups such as order numbers or error codes, and questions where a negation or a specific number decides the answer.
6. Why should you not set a similarity threshold by copying a number from an article?
Score scales depend on the model and the data, so a good threshold has to be measured on your own labelled examples.
Try this
Set aside 30 to 45 minutes. You need a spreadsheet and, if you like, an embedding service you are allowed to use; the first four steps need neither.
1. Invent a list of eight short help-centre titles for an app you know, for example a payments app or a food delivery app. Write three customer questions that should match different titles.
2. Make up a two-dimensional vector for each title and each question, using numbers between −10 and 10 so that related items point in similar directions. Put them in your spreadsheet.
3. In three more columns, compute the dot product, the Euclidean distance and the cosine similarity of each question against each title. In the cosine formula, divide the dot product by the product of the two lengths.
4. For each question, rank the titles by cosine and by Euclidean distance. Find at least one case where the two rankings differ. Write one sentence on why, using the idea of vector length.
5. Use the memory simulator to size a collection you might actually build: your own number of documents, pieces per document and a dimension of your choice. Write down the memory and the one-time embedding cost, and note which input you are least sure of.
6. Optional, if you have access to an embedding service: embed your eight titles and three questions, compute cosine in the spreadsheet or a short script, and compare with your invented ranking. Note where the real model surprised you, especially on a pair with a negation or a number.
A good result is a spreadsheet where you can point to a case where cosine and distance disagree and explain why, a size estimate with its assumptions written down, and, if you did step 6, a short list of two or three places where the real model's idea of "close" differed from yours.
Tags: AI Engineering Embeddings Semantic search Vector search LLM basics