What Are Embeddings in AI? Tokens, Vectors and Semantic Search Explained with Python
By Skillancy Editorial Team · 24 November 2026 · 34 min read
Reviewed by Rishav Kumar, Principal Data Analyst, Walmart Global Tech

Embeddings are lists of numbers that represent the meaning of a piece of text, so that a computer can measure how similar two pieces of text are. They are the reason an AI search box understands that "I want my money back" is a refund request even though the word "refund" never appears. Every RAG chatbot, semantic search engine, recommendation system and AI agent memory you have used is built on them. This guide explains what embeddings are in AI, how they differ from tokens and vectors, how cosine similarity works, and how to choose an embedding model. Then it runs real experiments in Python on an Indian shopping app's help centre, in English, Hinglish and Hindi. Every output is copied from a real run, including the queries where embeddings failed.
| Question | Short answer |
|---|---|
| What is an embedding in simple words? | A list of numbers that captures what a text means, so similar texts get similar numbers |
| Embeddings vs tokens? | Tokens are integer IDs for pieces of words (the model's input). An embedding is a list of decimals that represents meaning (the model's output) |
| Embeddings vs vectors? | Every embedding is a vector. "Embedding" means a vector that was learned to represent meaning |
| How big is an embedding? | Usually 384 to 3,072 numbers. Our model makes 384 |
| How do you compare embeddings? | Cosine similarity. On normalised vectors, cosine, dot product and Euclidean distance give the same ranking |
| Where are embeddings stored? | In a vector database or a vector column, such as Postgres with pgvector |
| What are embeddings used for? | Semantic search, RAG, recommendations, clustering, duplicate detection, classification and agent memory |
| Do I need a paid API? | No. The models in this guide are free, run on a laptop CPU and embedded 1,000 texts in under 1.2 seconds |
| Who should learn this? | Anyone learning Generative AI, data science or building RAG apps and AI agents |
Learn it live: Want to build semantic search and RAG apps with a mentor reviewing your code? Explore our Generative AI program, or talk to a mentor for a plan that fits your background.
What are embeddings in AI?
An embedding is a numeric representation of data, usually text, in which distance means difference in meaning. A text embedding model reads a sentence and returns a vector, such as 384 decimal numbers. Two sentences about refunds get vectors that are close together. A sentence about refunds and a sentence about cricket get vectors that are far apart.
The idea is easiest to see with a map. A city's location can be written as two numbers, latitude and longitude, and cities that are close on the map are close in those numbers. An embedding does the same for meaning, except it uses hundreds of dimensions instead of two, and nobody chose what each dimension means. The model learned them by reading huge numbers of example pairs.
Here is what that looks like for real. We embedded 24 short sentences from four topics and squashed the 384 dimensions down to 2 so they fit on a screen:

The six cricket sentences sit together on the far right, away from every customer support question. Delivery questions gather at the top left and account questions at the bottom. The groups overlap in places ("Money debited but order not placed" lands among the delivery questions), partly because the model sees a real link between payments and orders, and partly because a 2D picture keeps only 26% of the variation in the 384 dimensions. The full vectors separate them better than the picture can.
Why do we need embeddings at all?
Because computers compare numbers, not meanings. Older search engines compared words: a document matched if it contained the words you typed. That fails in two common ways:
1. Different words, same meaning. "I want my money back" and "How to get a refund" share no useful words. A keyword search scores them as unrelated.
2. Same word, different meaning. "Bank account blocked" and "the bank of the Ganga" share the word "bank". A keyword search scores them as related.
Embeddings fix both, because they compare meaning. They are not perfect, as our experiments show, but they are the reason modern search and RAG work as well as they do.
Tokens vs embeddings vs vectors vs vector databases
These four terms are the most common source of confusion, so here they are side by side.
| Term | What it is | Example | Who makes it |
|---|---|---|---|
| Token | A piece of a word, stored as an integer ID | "refund" → ref + ##und → [25416, 8630] | A tokenizer, using fixed rules |
| Vector | Any ordered list of numbers | [0.2, -1.4, 3.0] | Anything |
| Embedding | A vector learned to represent meaning | 384 decimals for "When will my refund arrive?" | An embedding model |
| Embedding model | A neural network that turns text into embeddings | all-MiniLM-L6-v2, OpenAI text-embedding-3-small | Trained by a lab, then you download or call it |
| Vector database | A store that saves embeddings and finds the nearest ones fast | pgvector, Qdrant, Chroma, Pinecone | You run it, or rent it |
So the order is: text → tokens → embedding model → embedding → stored in a vector database → searched by similarity.

Token embeddings vs sentence embeddings
You will meet the word "embedding" in two places, and they are not the same thing:
- Token embeddings live inside every LLM. The first layer of a model like GPT or Llama looks up a vector for each token ID. These vectors are part of the model and you rarely touch them.
- Sentence (text) embeddings are what you use in applications. An embedding model reads the whole text and returns one vector for all of it, usually by averaging the vectors of its tokens after they pass through the transformer. This is what semantic search, RAG and agent memory use.
There is also an older idea, word embeddings, made famous by Word2Vec in 2013. It gave every word one fixed vector, which is how the famous "king − man + woman ≈ queen" example worked. Its weakness was that "bank" got one vector whether it meant money or a river. Modern embedding models are built on transformers, so the same word is read in the context of the whole sentence.
How do embedding models learn meaning?
Most modern text embedding models are trained with contrastive learning. The model sees pairs of texts that belong together, such as a question and its answer, or two paraphrases. It is rewarded for making their vectors close, and for pushing them away from other texts in the same batch. Repeat that over hundreds of millions of pairs and the geometry of the vector space starts to reflect meaning.
The model we use, all-MiniLM-L6-v2, was trained this way on over 1 billion sentence pairs, according to its model card. The approach comes from Sentence-BERT (2019), which showed how to turn a BERT-style transformer into a model that produces sentence embeddings you can compare with cosine similarity.
Two practical consequences follow:
1. A model only understands what it was trained on. all-MiniLM-L6-v2 was trained mostly on English. You will see what that means for Hindi below.
2. Different models make incompatible vectors. You cannot compare a vector from one model with a vector from another. If you switch models, you re-embed everything.
What we will build
A small semantic search engine for the help centre of an imaginary Indian shopping and payments app, and a set of experiments that show where embeddings shine and where they break:
- 40 short help articles ("Money was debited from my bank account but the order was not placed", "UPI payment failed with error code U30", and so on)
- 20 customer questions with known right answers: 11 English paraphrases, 1 exact error code, 5 in Hinglish and 3 in Hindi (Devanagari)
- Three search engines compared on the same questions: keyword search (TF-IDF), an English embedding model and a multilingual embedding model
All text in the dataset is invented for this tutorial. Everything runs on a laptop CPU, with no API key.
Step 0: set up your environment
You need Python 3.10 or later. We used Python 3.13 on a laptop.
mkdir embeddings && cd embeddings
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install sentence-transformers==6.3.0 scikit-learn matplotlibTwo free models download on first use from Hugging Face: all-MiniLM-L6-v2 (English, 384 dimensions, about 90 MB) and paraphrase-multilingual-MiniLM-L12-v2 (50+ languages, 384 dimensions, about 450 MB).
Mac users: on Apple Silicon, passdevice="cpu"toSentenceTransformer. The Apple GPU backend has crashed for us with these small models, and the CPU is fast enough for this tutorial.
The full code for every step, with the dataset, is in the code folder for this article. Each step below shows the script and its real output.
Step 1: from text to tokens
Before a model can read text, a tokenizer splits it into tokens and maps each one to an integer ID from a fixed vocabulary. Let's look at the same question in English, Hinglish and Hindi.
# step1_tokens.py: text -> tokens -> token IDs
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
for text in ["When will my refund arrive?",
"Refund kab aayega?",
"रिफंड कब आएगा?"]:
ids = tok(text)["input_ids"]
print(text)
print(" tokens:", tok.convert_ids_to_tokens(ids))
print(" ids: ", ids)
# The multilingual model uses a different tokenizer, trained on 50+ languages
multi = AutoTokenizer.from_pretrained("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
ids = multi("रिफंड कब आएगा?")["input_ids"]
print("multilingual tokenizer:", multi.convert_ids_to_tokens(ids))Real output:
When will my refund arrive?
tokens: ['[CLS]', 'when', 'will', 'my', 'ref', '##und', 'arrive', '?', '[SEP]']
ids: [101, 2043, 2097, 2026, 25416, 8630, 7180, 1029, 102]
Refund kab aayega?
tokens: ['[CLS]', 'ref', '##und', 'ka', '##b', 'aa', '##ye', '##ga', '?', '[SEP]']
ids: [101, 25416, 8630, 10556, 2497, 9779, 6672, 3654, 1029, 102]
रिफंड कब आएगा?
tokens: ['[CLS]', '[UNK]', 'क', '##ब', 'आ', '##ए', '##ग', '##ा', '?', '[SEP]']
ids: [101, 100, 1315, 29865, 1312, 29850, 29853, 29876, 1029, 102]
multilingual tokenizer: ['<s>', '▁रिफंड', '▁कब', '▁आए', 'गा', '?', '</s>']What this teaches.
- Tokens are not words. "refund" became two tokens,
refand##und(the##means "joined to the previous piece").[CLS]and[SEP]are special markers for the start and end. - Hinglish gets chopped into meaningless pieces. "kab aayega" became
ka,##b,aa,##ye,##ga. The English model has never learned what those pieces mean together. - The English model cannot read Hindi. रिफंड became
[UNK](token ID 100, "unknown"), and the other words were broken into single letters. Whatever the model does with that, it is not understanding the question. We will see the cost of this in Step 4. - The multilingual tokenizer keeps Hindi words whole:
▁रिफंड,▁कब. That is the first sign it will do better on Hindi.
Tokens are only IDs. They carry no meaning by themselves: ID 25416 is not "closer" to ID 25417 in any useful way. Turning them into meaning is the embedding model's job.
Step 2: your first embedding
# step2_first_embedding.py: your first embedding
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2", device="cpu")
vec = model.encode("When will my refund arrive?")
print("type:", type(vec).__name__, "| shape:", vec.shape, "| dtype:", vec.dtype)
print("first 8 numbers:", vec[:8].round(4))
print("length (L2 norm):", round(float((vec ** 2).sum() ** 0.5), 4))Real output:
type: ndarray | shape: (384,) | dtype: float32
first 8 numbers: [-0.0729 -0.0385 0.0355 0.0552 0.0302 -0.0087 0.0214 0.0127]
length (L2 norm): 1.0What this teaches.
- The whole sentence became one NumPy array of 384 decimal numbers. Any sentence, short or long, gets exactly 384, so they can all be compared.
- No single number means anything on its own. You cannot point at position 3 and say "that is the refund dimension". Meaning lives in the pattern across all 384.
- The vector's length is 1.0. This model normalises its output, which matters for the next step: for vectors of length 1, cosine similarity is just a dot product.
Step 3: cosine similarity, explained with real numbers
Cosine similarity measures the angle between two vectors. If they point the same way, the score is 1. If they are at right angles (unrelated), it is 0. If they point in opposite directions, it is −1. In practice, text embeddings rarely go far below 0, so read it as "0 means unrelated, higher means more similar".
The formula is the dot product divided by the two lengths:
cosine(A, B) = (A · B) / (‖A‖ × ‖B‖)
Here we compare six pairs of sentences with three methods: keyword overlap (TF-IDF, a classic way to turn text into word-count vectors), the English embedding model and the multilingual model.
# step3_similarity.py: cosine similarity, embeddings vs keyword (TF-IDF)
from sentence_transformers import SentenceTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
english = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2", device="cpu")
multi = SentenceTransformer("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2", device="cpu")
pairs = [
("I want a refund", "Give me my money back"),
("I want a refund", "How do I reset my UPI PIN?"),
("My parcel has not arrived", "Where is my order?"),
("My parcel has not arrived", "Best batsman in IPL history"),
("Refund kab aayega?", "When will my refund arrive?"),
("रिफंड कब आएगा?", "When will my refund arrive?"),
]
def cos(model, a, b):
va, vb = model.encode([a, b], normalize_embeddings=True)
return float(va @ vb)
def tfidf_cos(a, b):
m = TfidfVectorizer().fit_transform([a, b])
return float(cosine_similarity(m[0], m[1])[0, 0])
print(f"{'Sentence A':<28} {'Sentence B':<30} {'TF-IDF':>7} {'MiniLM':>7} {'Multi':>7}")
for a, b in pairs:
print(f"{a:<28} {b:<30} {tfidf_cos(a, b):7.3f} {cos(english, a, b):7.3f} {cos(multi, a, b):7.3f}")Real output:
Sentence A Sentence B TF-IDF MiniLM Multi
I want a refund Give me my money back 0.000 0.612 0.694
I want a refund How do I reset my UPI PIN? 0.000 0.208 0.268
My parcel has not arrived Where is my order? 0.127 0.480 0.422
My parcel has not arrived Best batsman in IPL history 0.000 0.066 0.045
Refund kab aayega? When will my refund arrive? 0.151 0.422 0.384
रिफंड कब आएगा? When will my refund arrive? 0.000 0.051 0.824The same numbers as a table:
| Pair | Keyword (TF-IDF) | English model | Multilingual model |
|---|---|---|---|
| "I want a refund" vs "Give me my money back" | 0.000 | 0.612 | 0.694 |
| "I want a refund" vs "How do I reset my UPI PIN?" | 0.000 | 0.208 | 0.268 |
| "My parcel has not arrived" vs "Where is my order?" | 0.127 | 0.480 | 0.422 |
| "My parcel has not arrived" vs "Best batsman in IPL history" | 0.000 | 0.066 | 0.045 |
| "Refund kab aayega?" vs "When will my refund arrive?" | 0.151 | 0.422 | 0.384 |
| "रिफंड कब आएगा?" vs "When will my refund arrive?" | 0.000 | 0.051 | 0.824 |
What this teaches.
- Keyword matching is blind to paraphrase. "I want a refund" and "Give me my money back" share no words, so TF-IDF gives 0.000. Both embedding models give over 0.6, while the unrelated UPI PIN question stays near 0.2 and cricket near 0.
- Scores are relative, not absolute. 0.48 for "parcel has not arrived" vs "where is my order" is a strong match even though it is below 0.5. There is no universal "similar" threshold. You set one by testing on your own data.
- The English model cannot connect Hindi to English (0.051). The multilingual model, trained on translated sentence pairs, scores the Hindi and English versions of the same question at 0.824, the highest number in the table.
- Hinglish is hard for both. Romanised Hindi ("kab aayega") is neither proper English nor Hindi script, so neither model was trained much on it. The match here comes mostly from the shared word "refund".
Cosine vs dot product vs Euclidean distance
You will see three ways to compare vectors in vector databases. For normalised vectors (length 1, as most embedding models return), they give the same ranking:
# step3b_metrics.py: cosine vs dot product vs Euclidean distance
import numpy as np
from sentence_transformers import SentenceTransformer
from dataset import DOCS
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2", device="cpu")
ids = list(DOCS)
D = model.encode([DOCS[i] for i in ids], normalize_embeddings=True)
q = model.encode("I want my money back", normalize_embeddings=True)
cosine = D @ q / (np.linalg.norm(D, axis=1) * np.linalg.norm(q))
dot = D @ q
euclid = np.linalg.norm(D - q, axis=1)
top = lambda s, reverse=True: [ids[j] for j in (np.argsort(-s) if reverse else np.argsort(s))[:5]]
print("top 5 by cosine similarity :", top(cosine))
print("top 5 by dot product :", top(dot))
print("top 5 by Euclidean distance:", top(euclid, reverse=False))
print("check: distance² = 2 - 2·cosine ->", bool(np.allclose(euclid ** 2, 2 - 2 * cosine, atol=1e-5)))Real output:
top 5 by cosine similarity : [1, 2, 16, 3, 11]
top 5 by dot product : [1, 2, 16, 3, 11]
top 5 by Euclidean distance: [1, 2, 16, 3, 11]
check: distance² = 2 - 2·cosine -> TrueSame five articles, in the same order. For unit vectors, Euclidean distance squared equals 2 − 2 × cosine, so the smallest distance is always the highest cosine. Use dot product on normalised vectors: it is the cheapest to compute. If your vectors are not normalised, use cosine, because a dot product would favour longer vectors.
Same word, different meaning
# step3c_context.py: same word, different meaning. Keyword search vs embeddings
from sentence_transformers import SentenceTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2", device="cpu")
query = "my bank account is blocked"
docs = ["We sat on the bank of the Ganga and watched the sunset",
"SBI froze the savings I keep there. How do I get access again?"]
tfidf = TfidfVectorizer().fit(docs + [query])
kw = cosine_similarity(tfidf.transform([query]), tfidf.transform(docs))[0]
q, *d = model.encode([query] + docs, normalize_embeddings=True)
print(f"query: {query!r}")
for doc, k, e in zip(docs, kw, d @ q):
print(f" keyword {k:.3f} | embedding {e:.3f} | {doc}")Real output:
query: 'my bank account is blocked'
keyword 0.073 | embedding 0.133 | We sat on the bank of the Ganga and watched the sunset
keyword 0.000 | embedding 0.421 | SBI froze the savings I keep there. How do I get access again?Keyword search prefers the riverbank sentence, because it contains "bank". The embedding model ranks the SBI sentence three times higher, even though it shares no words with the query. It has learned that "SBI", "froze" and "savings" belong with "bank account blocked".
Step 4: keyword search vs semantic search on 40 help articles
Now the real test. Semantic search embeds every document once, embeds each incoming question, and returns the documents with the highest cosine similarity. We compare it with keyword search on 20 customer questions. For each question we check two things: was the right article ranked first (hit@1), and was it in the top 3 (hit@3)? Hit@3 matters for RAG, where you usually send the top few results to an LLM.
# step4_search.py: keyword search vs semantic search on 40 help articles
import numpy as np
from sentence_transformers import SentenceTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from dataset import DOCS, QUERIES
ids = list(DOCS)
texts = [DOCS[i] for i in ids]
def keyword_search():
vec = TfidfVectorizer().fit(texts)
D = vec.transform(texts)
return lambda q: (vec.transform([q]) @ D.T).toarray()[0]
def semantic_search(name):
model = SentenceTransformer(name, device="cpu")
D = model.encode(texts, normalize_embeddings=True) # 40 x 384, done once
return lambda q: D @ model.encode(q, normalize_embeddings=True)
engines = {
"Keyword (TF-IDF)": keyword_search(),
"all-MiniLM-L6-v2": semantic_search("sentence-transformers/all-MiniLM-L6-v2"),
"multilingual-MiniLM-L12-v2": semantic_search("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"),
}
results = {}
for name, score in engines.items():
rows = []
for q, gold, kind in QUERIES:
s = score(q)
order = [ids[j] for j in np.argsort(-s, kind="stable")]
top = order[0] if s.max() > 0 else None # TF-IDF: no shared word = no result
rank = order.index(gold) + 1 if s[ids.index(gold)] > 0 else None # a zero score is not a match
rows.append((q, gold, kind, top, rank))
results[name] = rows
# ... the full script then prints the summary table and the top result for each questionThe semantic search engine is the three lines inside semantic_search. Embed the documents once, embed the question, take a dot product. Everything else is measurement.
Real output (summary):
== Hit@1 and hit@3 by query type (20 queries)
engine English paraphrase (11) Exact code (1) Hinglish (5) Hindi (3) all (20)
Keyword (TF-IDF) 1/11 | 6/11 1/1 | 1/1 2/5 | 3/5 0/3 | 0/3 4 | 10
all-MiniLM-L6-v2 8/11 | 10/11 1/1 | 1/1 2/5 | 3/5 0/3 | 0/3 11 | 14
multilingual-MiniLM-L12-v2 6/11 | 10/11 0/1 | 1/1 2/5 | 3/5 2/3 | 3/3 10 | 17The same results as a table (hit@1, then hit@3):
| Query type | Keyword (TF-IDF) | English model (all-MiniLM-L6-v2) | Multilingual model |
|---|---|---|---|
| English paraphrase (11) | 1 · 6 | 8 · 10 | 6 · 10 |
| Exact error code "U30" (1) | 1 · 1 | 1 · 1 | 0 · 1 |
| Hinglish (5) | 2 · 3 | 2 · 3 | 2 · 3 |
| Hindi, Devanagari (3) | 0 · 0 | 0 · 0 | 2 · 3 |
| All 20 questions | 4 · 10 | 11 · 14 | 10 · 17 |

Some individual questions from the full output:
[English paraphrase] 'can I pay in monthly instalments without interest' -> correct: #15 'No cost EMI options on credit cards'
✗ Keyword (TF-IDF) #16 Pay later limit and how to repay the pay later bill
✓ all-MiniLM-L6-v2 #15 No cost EMI options on credit cards
✓ multilingual-MiniLM-L12-v2 #15 No cost EMI options on credit cards
[English paraphrase] 'how do I get the tax bill for my purchase' -> correct: #34 'How to download the GST invoice for my order'
✗ Keyword (TF-IDF) #1 How to get a refund for a cancelled order
✓ all-MiniLM-L6-v2 #34 How to download the GST invoice for my order
✗ multilingual-MiniLM-L12-v2 #16 Pay later limit and how to repay the pay later bill
[English paraphrase] "they sent me someone else's product" -> correct: #30 'I received the wrong item in my package'
✗ Keyword (TF-IDF) #29 I received a damaged or broken product
✗ all-MiniLM-L6-v2 #29 I received a damaged or broken product
✗ multilingual-MiniLM-L12-v2 #8 The delivery partner marked my order delivered but I did not receive it
[Hindi] 'पैसे कट गए लेकिन ऑर्डर नहीं हुआ' -> correct: #2 'Money was debited from my bank account but the order was not placed'
✗ Keyword (TF-IDF) (no result: no shared words)
✗ all-MiniLM-L6-v2 #20 How to complete KYC for the wallet using Aadhaar or PAN
✓ multilingual-MiniLM-L12-v2 #2 Money was debited from my bank account but the order was not placed
[Hinglish] 'paisa kat gaya par order nahi hua' -> correct: #2 'Money was debited from my bank account but the order was not placed'
✗ Keyword (TF-IDF) #1 How to get a refund for a cancelled order
✗ all-MiniLM-L6-v2 #34 How to download the GST invoice for my order
✗ multilingual-MiniLM-L12-v2 #31 An item is missing from my orderWhat this teaches.
1. Embeddings win clearly on paraphrases. The English model found the right article first for 8 of 11 English paraphrases, against 1 of 11 for keyword search. "Monthly instalments without interest" found "No cost EMI", and "tax bill" found "GST invoice", with no shared words.
2. The English model is lost in Hindi. It sent all three Hindi questions to the same wrong article (#20, KYC). Step 1 showed why: the Hindi text became [UNK] and stray letters, so the three questions ended up with similar meaningless vectors.
3. The multilingual model reads Hindi but gives up a little English. It got 2 of 3 Hindi questions first and all 3 in the top 3, and it had the best top-3 score overall (17 of 20). It also slipped on some English questions the English model got right, such as "tax bill". A bigger model is not automatically better at everything: test on your own questions.
4. Hinglish beat every model. Romanised Hindi like "paisa kat gaya" scored 2 of 5 first for all three engines, and the two successes ("order cancel kaise kare", "upi pin bhool gaya") worked because they contain English words. If your users type Hinglish, which is common in Indian apps, try a model trained on code-mixed text, translate or transliterate the query first, or add Hinglish phrasings of each article to the index.
5. Embeddings are not a magic fix. "they sent me someone else's product" failed on every engine: the models matched "product" and "sent" to damage and delivery articles instead of "wrong item". Exact codes are fragile too: the multilingual model ranked the "U30" article second, not first. This is why production systems combine embeddings with keyword search (hybrid search) and add a reranker.
6. 20 questions is a teaching set, not a benchmark. With so few questions, one result changes a score by 5 points. The method is what matters: build a labelled test set from real user questions and measure before you choose a model.
Step 5: how fast and how big are embeddings?
# step5_speed.py: how fast and how big? 1,000 short texts on a laptop CPU
import time, numpy as np
from sentence_transformers import SentenceTransformer
from dataset import DOCS
texts = [f"{t} (article {i})" for i in range(25) for t in DOCS.values()] # 1,000 texts
for name in ["sentence-transformers/all-MiniLM-L6-v2",
"sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"]:
model = SentenceTransformer(name, device="cpu")
model.encode(texts[:32]) # warm-up
t0 = time.perf_counter()
E = model.encode(texts, batch_size=64, normalize_embeddings=True)
secs = time.perf_counter() - t0
params = sum(p.numel() for p in model.parameters()) / 1e6
print(f"{name.split('/')[1]}: {params:.0f}M parameters, {E.shape[1]} dims, "
f"{len(texts)} texts in {secs:.2f}s ({len(texts)/secs:.0f}/s), "
f"float32 storage {E.astype(np.float32).nbytes/1e6:.2f} MB")Real output (Apple M1 Pro laptop, CPU only):
all-MiniLM-L6-v2: 23M parameters, 384 dims, 1000 texts in 0.54s (1839/s), float32 storage 1.54 MB
paraphrase-multilingual-MiniLM-L12-v2: 118M parameters, 384 dims, 1000 texts in 1.14s (877/s), float32 storage 1.54 MBWhat this teaches.
- Small embedding models are cheap to run. A 23-million-parameter model embedded about 1,800 short texts a second on a laptop CPU. For comparison, chat LLMs have billions of parameters. Speed will be lower on long documents and older laptops, so measure on yours.
- Storage depends on dimensions, not on the model's size. Both models make 384 numbers per text, at 4 bytes each: 1,536 bytes per text, or about 1.5 GB for a million texts. A 1,536-dimensional embedding needs four times that.
- Embedding is a one-time cost per document. You embed your documents once (and again only when they change or you switch models). Each search then embeds one short question.
Free local model or paid API?
| Free local model (this guide) | Hosted embedding API | |
|---|---|---|
| Examples | all-MiniLM-L6-v2, multilingual-MiniLM, BGE, E5 | OpenAI text-embedding-3-small and -large, Google, Cohere, Voyage |
| Cost | Your own CPU or GPU | Pay per token. OpenAI lists text-embedding-3-small at US$0.02 per million tokens |
| Data privacy | Text never leaves your machine | Text is sent to the provider |
| Dimensions | Often 384 to 1,024 | Often 768 to 3,072 (text-embedding-3-small: 1,536) |
| Best for | Learning, prototypes, private data, high volume | Strong quality with no infrastructure to run |
To put the API price in rupees: 10,000 help articles of about 50 tokens each is 500,000 tokens, which costs about US$0.01, roughly one rupee at current exchange rates. For most learning projects, cost is not the deciding factor. Quality on your own data, privacy and language support are. Check the provider's pricing page before you build, because prices change.
How to choose an embedding model
1. Start with your languages. If users write in Hindi or another Indian language, an English-only model will fail, as Step 4 showed. Use a multilingual model, and test Hinglish separately.
2. Check the MTEB leaderboard, then test on your data. The Massive Text Embedding Benchmark (MTEB) ranks models on many tasks, and its authors found that no single model wins everywhere. Pick 2 or 3 candidates for your task type (retrieval, clustering or classification) and run them on 30 to 50 real questions with known answers, as we did.
3. Respect the input limit. all-MiniLM-L6-v2 truncates input after 256 word pieces, and the multilingual model after 128. Text beyond the limit is ignored, so long documents must be chunked into passages before embedding.
4. Balance dimensions against cost. More dimensions can capture more detail but cost more storage and search time. 384 is plenty for learning and many real apps.
5. Read the model card. Some models need a prefix such as query: or passage: before the text. Forgetting it quietly lowers quality.
6. Never mix models. Embeddings from different models live in different spaces. Store the model name with your vectors, and re-embed everything when you switch.
What are embeddings used for?
| Use | How embeddings help | Example |
|---|---|---|
| Semantic search | Find documents by meaning, not exact words | A help centre that understands "money back" |
| RAG (retrieval-augmented generation) | Fetch the most relevant passages and give them to an LLM as context | A chatbot that answers from your company's policies |
| Recommendations | Suggest items whose embeddings are close to what a user liked | "Similar products" on a shopping app |
| Clustering and topic discovery | Group thousands of texts by meaning without labels | Finding the top complaint themes in app reviews |
| Duplicate detection | Flag near-identical questions or tickets | Merging repeat customer support tickets |
| Classification | Use embeddings as features for a simple classifier | Tagging tickets as refund, delivery or account |
| Agent memory | Store facts and recall the relevant ones later | An AI tutor that remembers your weak topics |
For data analysts, the clustering and classification uses are the quickest wins: embed a column of free-text survey answers or reviews, run K-means, and you have themes in minutes instead of reading thousands of rows.
Where embeddings go next: vector databases and RAG
Our search compared the question with all 40 articles one by one. That is fine for thousands of documents, but not for millions. Vector databases use approximate nearest neighbour indexes, such as HNSW, to find the closest vectors without comparing every one. You do not always need a new database: Postgres with the pgvector extension stores embeddings next to your normal tables and supports cosine distance and HNSW indexes.
In a RAG app, the steps are the ones you just ran, plus one more: chunk the documents, embed the chunks, store them, embed the user's question, retrieve the top few chunks, and pass them to an LLM to write the answer. The quality of the final answer depends heavily on that retrieval step, which is why the failures in Step 4 matter. Read RAG vs Fine-Tuning to decide when RAG is the right tool, and how to evaluate an LLM app to measure retrieval properly.
Common mistakes with embeddings
- Comparing vectors from different models. The numbers look similar but mean nothing together.
- Embedding whole documents without chunking. Text past the model's limit is silently cut off, and one vector for a 20-page PDF blurs every topic together.
- Assuming one threshold works everywhere. 0.48 was a strong match in our test. Tune thresholds on your own labelled examples.
- Using an English-only model for Indian users. Our English model sent every Hindi question to the same wrong article.
- Trusting embeddings for exact codes and IDs. Error codes, PAN or IFSC formats and product SKUs are better matched with keyword search. Combine both.
- Skipping evaluation. Without a test set of real questions, you cannot tell whether a model change helped or hurt.
- Forgetting to normalise before a dot product. Unnormalised vectors make the dot product favour longer vectors, not closer meanings.
Interview questions on embeddings
Embeddings come up in almost every GenAI, RAG and data science interview. Practise these out loud.
1. What is an embedding? A learned, fixed-length vector that represents meaning, so that similar inputs are close together in the vector space.
2. What is the difference between tokens and embeddings? Tokens are integer IDs for pieces of text, made by a tokenizer with fixed rules. Embeddings are dense vectors of decimals, made by a trained model, that represent meaning.
3. Why cosine similarity instead of Euclidean distance? Cosine compares direction and ignores length. For normalised vectors the two give the same ranking, so many systems use a dot product because it is fastest.
4. How are text embedding models trained? Usually with contrastive learning on pairs of related texts, pulling matching pairs together and pushing other texts apart.
5. Word embeddings vs sentence embeddings? Word2Vec gives each word one fixed vector regardless of context. Sentence embeddings from transformers represent a whole text, and the same word is read in its context.
6. How would you choose an embedding model for a Hindi and English support bot? Shortlist multilingual models from MTEB, check input length and licence, then measure hit@k on a labelled set of real Hindi, English and Hinglish questions.
7. Why might semantic search miss an exact product code? Codes are rare tokens with little learned meaning. Add keyword search (hybrid search) or exact-match filters.
8. What happens if you change your embedding model? All stored vectors become incompatible, so you must re-embed the whole corpus.
9. How do you store and search millions of embeddings? In a vector database or pgvector, using an approximate nearest neighbour index such as HNSW.
10. How do you evaluate retrieval quality? A labelled test set with metrics such as hit@k, recall@k and MRR, as in Step 4.
Learn it live: Want to explain embeddings and RAG confidently in an interview? Join a cohort of the Generative AI program or book a mock interview to practise with a mentor.
Why embeddings are a career skill
Embeddings sit underneath almost every AI feature companies are building: search, RAG chatbots, recommendations and agents. Knowing how to call an LLM is common. Knowing why retrieval returned the wrong passage, and how to fix it by changing the model, the chunks or the search method, is what separates someone who built a demo from someone who can ship it.
It is also a natural skill for data people. Choosing an embedding model is model evaluation. Building a test set of questions is labelling. Clustering embeddings of customer reviews is exploratory analysis. That is why embeddings appear in both our Generative AI program (weeks 1 to 9: embeddings, vector databases, semantic search and RAG) and our Data Science with AI course (tokenization, embeddings and RAG for a customer support agent).
Your 2-week plan to learn embeddings
| Days | Focus | Output |
|---|---|---|
| 1–2 | Run Steps 1 to 3. Try your own sentence pairs and see where the scores surprise you | Notes on what "similar" means to the model |
| 3–5 | Rebuild Step 4 with 50 real questions from a domain you know (your college FAQ, a product's help pages) | Your own hit@1 and hit@3 table |
| 6–8 | Try a third model from the MTEB leaderboard and a multilingual one. Compare on your test set | A model choice you can justify with numbers |
| 9–11 | Store the vectors in Postgres with pgvector and query them with SQL | A semantic search API |
| 12–14 | Add an LLM to answer from the top 3 results: your first RAG app | A portfolio project with an evaluation table |
Key takeaways
- An embedding is a learned vector that represents meaning. Similar meanings get vectors that point the same way.
- Tokens are integer IDs for word pieces. Embeddings are the model's output. A vector database stores embeddings and finds the nearest ones fast.
- Compare embeddings with cosine similarity. On normalised vectors, cosine, dot product and Euclidean distance rank results identically.
- In our test, embeddings found the right help article first 11 times out of 20, against 4 for keyword search.
- Language matters. The English model failed every Hindi question. The multilingual model got all three into the top 3. Hinglish was hard for every model.
- Embeddings still miss things. Combine them with keyword search, test on real questions, and never mix vectors from different models.
Frequently asked questions
What are embeddings in AI in simple words?
Embeddings are lists of numbers that represent the meaning of text, images or other data. Texts with similar meaning get similar lists of numbers, so a computer can find related content by comparing numbers instead of matching exact words.
What is the difference between embeddings and tokens?
Tokens are integer IDs for pieces of words, produced by a tokenizer using fixed rules, and they are the input to a model. Embeddings are vectors of decimal numbers produced by a trained model, and they represent meaning. For example, "refund" becomes the tokens ref and ##und, but the whole sentence becomes one embedding of 384 numbers.
What is the difference between embeddings and vectors?
A vector is any ordered list of numbers. An embedding is a vector that a model has learned so that its position represents meaning. Every embedding is a vector, but not every vector is an embedding.
What are embeddings in RAG?
In retrieval-augmented generation, documents are split into chunks and each chunk is turned into an embedding. When a user asks a question, the question is embedded too, the closest chunks are retrieved by cosine similarity, and those chunks are given to the LLM as context to write the answer.
What is cosine similarity in embeddings?
Cosine similarity measures the angle between two vectors. A score near 1 means the texts have very similar meaning, and a score near 0 means they are unrelated. For normalised embeddings it equals the dot product of the two vectors.
How many dimensions does an embedding have?
It depends on the model. Small open-source models such as all-MiniLM-L6-v2 produce 384 numbers. Many models produce 768 or 1,024, and OpenAI's text-embedding-3-small produces 1,536. More dimensions can capture more detail but need more storage.
Which is the best embedding model for RAG?
There is no single best model. Shortlist a few from the MTEB leaderboard for retrieval in your languages, then test them on 30 to 50 real questions with known answers. In our test, the English model was best on English questions and the multilingual model was best on Hindi.
Do embedding models work for Hindi and Indian languages?
English-only models do not. In our test, an English model sent every Hindi question to the same wrong article. A multilingual model put the right article in the top 3 for all three Hindi questions. Romanised Hinglish was hard for every model we tried, so test it separately.
Are embeddings free to use?
Yes, if you run an open-source model yourself. The models in this guide are free and embedded 1,000 short texts in about half a second to a little over a second on a laptop CPU. Hosted APIs charge per token, but embedding is cheap: OpenAI lists text-embedding-3-small at US$0.02 per million tokens.
What is the difference between semantic search and keyword search?
Keyword search matches the words in your query, so it misses synonyms and paraphrases. Semantic search compares embeddings, so it matches meaning. Keyword search is still better for exact codes and IDs, which is why many systems combine both in hybrid search.
What is a vector database?
A vector database stores embeddings and finds the ones closest to a query quickly, usually with an approximate nearest neighbour index such as HNSW. Examples include Qdrant, Chroma, Pinecone and Postgres with the pgvector extension.
Do I need to know maths to use embeddings?
Not much. You need the idea of a vector as a list of numbers, and that cosine similarity measures how closely two vectors point the same way. Libraries such as sentence-transformers handle the rest, as the code in this guide shows.
What is the difference between word embeddings and sentence embeddings?
Word embeddings, such as Word2Vec, give each word one fixed vector, so "bank" has the same vector in every sentence. Sentence embeddings from transformer models represent a whole piece of text, reading each word in its context.
Recommended reading and practice on Skillancy
- RAG vs Fine-Tuning: What Should You Use for Generative AI Applications?
- AI Agent Memory Explained: Types and a Working Python Example
- How to Evaluate an LLM App: Build an Eval Harness in Python
- Generative AI Roadmap
- Prompt Engineering for LLMs
- Semantic Layer + MCP for AI Analytics Agents
- Python for Data Science
- How to Become an AI Engineer in India
Practice: Python interview questions · Python compiler · Free Python tutorial
Sources
- Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks (arXiv 1908.10084): sentence embeddings compared with cosine similarity
- Efficient Estimation of Word Representations in Vector Space, Word2Vec (arXiv 1301.3781)
- MTEB: Massive Text Embedding Benchmark (arXiv 2210.07316) and the MTEB leaderboard: no single embedding method dominates across tasks
- all-MiniLM-L6-v2 model card: 384 dimensions, trained on over 1 billion sentence pairs, input truncated at 256 word pieces
- paraphrase-multilingual-MiniLM-L12-v2 model card: 50+ languages, 384 dimensions, maximum sequence length 128
- Sentence Transformers documentation
- OpenAI text-embedding-3-small model page and New embedding models and API updates (OpenAI)
- pgvector on GitHub: vector similarity search in Postgres, with HNSW indexes
Reproducibility note
All code in Steps 1 to 5 was run on Python 3.13.9 with sentence-transformers 6.3.0, transformers 5.23.0, tokenizers 0.23.3, torch 2.15.0, numpy 2.5.5, scikit-learn 1.9.1 and matplotlib 3.11.2, on an Apple M1 Pro laptop running macOS 14.7, on CPU. The models were sentence-transformers/all-MiniLM-L6-v2 and sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2. Every output block was copied from those runs on 24 November 2026. The help-centre articles and questions are invented for this tutorial. Hit rates come from 20 questions and will change with other models, questions or library versions, so treat them as an illustration of the method, not a benchmark. Timings depend on hardware. The API price is the provider's listed price at the time of writing, and the rupee figure is a rough conversion. Check current documentation and pricing for the versions you use.
Learn it live: Ready to build semantic search, RAG and AI agents on top of embeddings? Explore the Generative AI program or Data Science with AI, or talk to a mentor. Learn. Build. Get hired.
Get the Skillancy field notes
One email a week: AI and analytics guides, cohort dates and hiring signals. No spam, unsubscribe anytime.