How do sparse and dense embeddings differ?
- Authors
- Name
- Amit Shekhar
- Published on
A sparse embedding has one position for every word in the vocabulary with almost all zeros, whereas a dense embedding has a small fixed number of non-zero positions.
In this blog, we will learn about Sparse Embeddings vs Dense Embeddings. We will also see how they differ from each other and when to use which one.
We will cover the following:
- What is an embedding?
- What is a Sparse Embedding?
- What is a Dense Embedding?
- The same sentence, both ways
- How each one decides that two things match
- Where sparse embeddings win
- Where sparse embeddings fail
- Where dense embeddings win
- Where dense embeddings fail
- How each one is stored and searched
- Learned sparse embeddings
- Sparse vs Dense embeddings
- Hybrid search
- How to combine the two scores
- When to use which one
- A complete code example
I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.
I teach AI and Machine Learning at Outcome School.
Let's get started.
What is an embedding?
An embedding is a list of numbers that represents a piece of text.
We turn text into numbers because a computer can compare numbers very fast, and it cannot compare meaning directly.
"the refund policy" ---> [ 0.2, -0.5, 0.8, ... ]
Once both a question and a document are lists of numbers, finding the closest document is arithmetic.
Sparse and dense embeddings do this in different ways. The difference starts with how long the list is, and how many of the numbers are zero.
We have a detailed blog on What are Embeddings? that explains this in depth.
What is a Sparse Embedding?
A sparse embedding has one position for every word in the vocabulary, and almost all of those positions are zero.
THE VOCABULARY
position 0 "a"
position 1 "about"
position 2 "account"
...
position 8,412 "refund"
...
position 24,109 "policy"
...
position 49,999 "zebra"
50,000 positions in total
Now we take a sentence and fill in the positions.
"the refund policy"
position 8,412 ("refund") -> 2.8
position 24,109 ("policy") -> 2.1
position 41,203 ("the") -> 0.1
every other position -> 0
That is 3 non-zero values out of 50,000.
99.994 percent of the vector is zero.
That is why it is called sparse, which means mostly empty.
The numbers are not counts. They are weights, and the classic method for producing them is BM25, which follows two intuitions.
+---------------------------------------------------+
| 1. A word that appears more often in this |
| document matters more. |
+---------------------------------------------------+
| 2. A word that appears in FEWER documents |
| overall matters much more. |
+---------------------------------------------------+
"the" appears in every document -> weight ~0
"refund" appears in 2% of documents -> high weight
"XJ-7741" appears in 1 document -> enormous weight
A rare word carries more information than a common word. And every position has a name. Position 8,412 always means "refund".
This was all about Sparse Embeddings. Now, it's time to learn about Dense Embeddings.
What is a Dense Embedding?
A dense embedding has a small fixed number of positions, and essentially all of them are non-zero.
"the refund policy"
-> [ 0.21, -0.53, 0.08, 0.77, -0.12, 0.44, ... ]
768 positions. All of them filled with a real number.
The size is fixed, usually somewhere between 256 and 4,096, and it has nothing to do with the vocabulary size.
No position has a name.
position 0 = ???
position 1 = ???
position 2 = ???
Nobody assigned meanings to these. They came out of training a neural network, and the meaning is spread across all of them together rather than living in any one.
HOW A DENSE EMBEDDING IS PRODUCED
text ---> a trained neural network ---> 768 numbers
The network was trained on millions of examples of
"these two texts mean the same thing" and "these two
do not", and it learned to place similar meanings at
similar coordinates.
So a dense embedding is a position in a learned space of meaning, and a sparse embedding is a record of which words appeared.
We have a detailed blog on how an embedding model works that explains how this network is trained step by step.
The same sentence, both ways
Let's put them next to each other.
SENTENCE: "How do I get my money back?"
SPARSE
+--------------------------------------------------+
| 50,000 positions |
| 0 0 0 ... 0 1.9 ("money") 0 0 ... 0 |
| 0 0 ... 0 2.4 ("back") 0 0 0 ... 0 |
| 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... |
| |
| 5 non-zero values, 49,995 zeros |
| every non-zero has a NAME |
+--------------------------------------------------+
DENSE
+--------------------------------------------------+
| 768 positions |
| 0.21 -0.53 0.08 0.77 -0.12 0.44 0.31 -0.66 ... |
| |
| 768 non-zero values, 0 zeros |
| no position has a name |
+--------------------------------------------------+
How each one decides that two things match
This is where the practical difference comes from.
SPARSE MATCHING
query: "refund policy"
document: "our refund policy allows 30 days"
Do they share non-zero positions?
position 8,412 ("refund") query 2.8 x doc 2.4 = 6.72
position 24,109 ("policy") query 2.1 x doc 1.9 = 3.99
total 10.71
HIGH SCORE, because they share exact terms.
Now a different document:
document: "how to get your money returned"
Shared positions: none.
Score: 0.
The sparse method sees NO relationship at all.
DENSE MATCHING
query: "refund policy" -> a point in the space
document: "how to get your money
returned" -> another point
How close are those two points?
Usually very close, because the network learned during
training that these mean the same thing.
HIGH SCORE, with zero shared words.
Here, we can see that sparse matches words, and dense matches meaning.
Planning your move into AI?
No matter which tech domain you work in today, with your effort, you can transition to these roles:
- AI Engineer
- Forward Deployed Engineer
- AI Agent Engineer
- Harness Engineer
- Voice AI Engineer
- AI Architect
- LLM Engineer
- LLM Inference Engineer
- Gen AI Engineer
- MLOps Engineer
- ML Engineer
- Deep Learning Engineer
Our AI and Machine Learning Program at Outcome School takes you there.
Where sparse embeddings win
Exact terms, and especially rare ones.
query: "error ERR_4471"
Sparse: ERR_4471 is a rare term, so it has an enormous
weight, and only documents containing that exact
string score highly.
-> exactly right
Dense: ERR_4471 was never in the training data. It gets
chopped into meaningless fragments and lands
somewhere vague, near ERR_4472 and ERR_4481.
-> can return the wrong error code
Identifiers, product codes, part numbers, names, and version numbers all behave this way, and they are common in real queries.
Out of domain content. A sparse method needs no training, so it works the same way on medical text, legal text, and an internal codebase. A dense model usually works best on text similar to what it was trained on.
Interpretability. We can see exactly why a document matched, because every dimension has a name. Debugging a sparse search is easy. Debugging a dense search is hard, because its 768 numbers mean nothing individually.
No training and no cost to build. The weights come from counting. There is no model to run, no graphics card, and no embedding call per document.
Long documents. Sparse handles them naturally, because more text simply means more non-zero positions. A dense embedding has to compress a long document into the same 768 numbers as a short one, so details get averaged away.
Where sparse embeddings fail
The vocabulary mismatch problem, which is the classic failure.
query: "how do I get my money back"
document: "refund procedure"
No shared words. Score: zero.
+--------------------------------------------------+
| Sparse retrieval cannot see: |
| |
| synonyms car / automobile |
| paraphrases "money back" / "refund" |
| related concepts "laptop" / "notebook" |
| other languages entirely |
| misspellings "recieve" / "receive" |
+--------------------------------------------------+
Short queries are also weak. A two word query has two non-zero positions, so there is very little to match on.
Where dense embeddings win
Meaning without shared words.
query: "my laptop won't turn on"
document: "troubleshooting power issues on portable
computers"
Shared words: essentially none.
Dense score: high.
Short and vague queries. Two words are enough to place a point in the space, and that point can be close to a well written document.
Across languages. A multilingual dense model places the same meaning in the same place regardless of the language, so a Hindi question can find an English document. Sparse cannot do this at all, because the words do not overlap.
Robust to wording. Rephrasing the question barely moves the point, so the results stay stable.
Where dense embeddings fail
Rare and unseen terms, which is exactly where sparse wins.
The model can only place a term meaningfully if it
saw that term meaningfully during its own training.
Our product names, internal codenames, error codes,
and part numbers were never in that training.
Exact matching. Dense retrieval generalizes by design, so it is not precise about a specific string. SKU-88213 and SKU-88219 are nearly identical points.
Out of domain content. A model trained on general web text performs noticeably worse on legal, medical, or scientific text, and worse still on an internal codebase.
Long documents. Everything gets averaged into one fixed size vector, so a precise sentence inside a long chunk gets diluted.
Cost and maintenance. Every document needs a model call to embed. And changing the embedding model means re-embedding the entire corpus, because vectors from two models cannot be compared.
Opacity. When a wrong result comes back, it is hard to explain why.
A quick note for you
No matter which tech domain you work in, get familiar with these topics:
- LLM
- RAG
- MCP
- Agent
- Fine-tuning
- Quantization
We put it all together in one video:
AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization
No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.
Now, let's get back to the topic.
How each one is stored and searched
The storage structures are as different as the vectors, and this affects real systems.
SPARSE: AN INVERTED INDEX
+--------------------------------------------------+
| "refund" -> doc 4, doc 19, doc 88, doc 204 |
| "policy" -> doc 4, doc 55, doc 88 |
| "ERR_4471" -> doc 991 |
+--------------------------------------------------+
To search: look up each query term, take the documents
that appear, and score them.
We never touch documents that share no terms, so the
search cost depends on how rare the query terms are.
A rare term makes the search faster.
DENSE: AN APPROXIMATE NEAREST NEIGHBOR INDEX
+--------------------------------------------------+
| A graph or a set of clusters over every vector, |
| built so we can walk toward the closest points |
| without comparing against all of them. |
+--------------------------------------------------+
To search: convert the query to a vector, then walk
the structure.
Every search touches the structure regardless of the
query, so the cost is roughly the same for every query.
We have a detailed blog on Approximate Nearest Neighbor (ANN) search that covers how this structure is built and walked.
The practical consequences:
+--------------------------------------------------+
| MEMORY |
| Sparse: proportional to non-zero values, which |
| is small. Compresses well. |
| Dense: 768 numbers per document, always. For |
| 10 million documents that is tens of gigabytes. |
+--------------------------------------------------+
| UPDATES |
| Sparse: adding a document updates a few lists. |
| Cheap and immediate. |
| Dense: adding a vector modifies a graph, and |
| deleting is awkward and needs periodic |
| compaction. |
+--------------------------------------------------+
| MATURITY |
| Sparse: decades of production search engines. |
| Dense: newer, and evolving quickly. |
+--------------------------------------------------+
To learn Embeddings and Vector Databases, and how they are stored and searched at scale, we cover them in depth in our AI and Machine Learning Program at Outcome School.
Learned sparse embeddings
There is a third option, which reduces the vocabulary mismatch problem while keeping the sparse shape.
A learned sparse embedding uses a neural network to decide the weights, and it can add terms that were not in the text.
THE TEXT
"how do I get my money back"
CLASSIC SPARSE (BM25)
"money" 1.9 "back" 2.4 "get" 0.7
LEARNED SPARSE
"money" 1.9
"back" 2.4
"get" 0.7
"refund" 2.1 <- ADDED by the model, not in the text
"return" 1.6 <- ADDED
"payment" 1.1 <- ADDED
"policy" 0.8 <- ADDED
Here, we can see that the text now matches queries containing "refund" even though the word never appeared, and the vector is still sparse, still named, and still stored in an inverted index.
+--------------------------------------------------+
| WHAT WE GET |
| synonym matching, like dense |
| exact term matching, like sparse |
| interpretability, like sparse |
| a normal inverted index, like sparse |
+--------------------------------------------------+
| WHAT IT COSTS |
| a model call per document at indexing time |
| a larger index, because more terms are non-zero |
| the same out-of-domain weakness as dense, since |
| the expansion comes from a trained model |
+--------------------------------------------------+
SPLADE is a well-known method in this family.
Sparse vs Dense embeddings
Let me tabulate the differences between Sparse and Dense embeddings for your better understanding.
| Property | Sparse | Dense |
|---|---|---|
| Length of the vector | vocabulary size, 30k+ | fixed, 256 to 4,096 |
| Non-zero values | a handful | all of them |
| Dimensions have meaning | yes, each is a word | no |
| Produced by | counting, or a model | a trained neural network |
| Matches on | shared exact terms | position in meaning space |
| Synonyms and paraphrases | no | yes |
| Rare terms and identifiers | excellent | poor |
| Across languages | no | yes |
| Out of domain text | works unchanged | degrades |
| Short queries | weak | strong |
| Long documents | handles them well | dilutes them |
| Misspellings | fails | tolerant |
| Interpretable | fully | not at all |
| Needs training | no | yes |
| Cost to index | very low | a model call per document |
| Storage | very small | large and fixed |
| Updates and deletes | cheap | more involved |
| Index type | inverted index | approximate neighbor graph |
| Changing the model | not applicable | re-embed everything |
Hybrid search
Here, we can see that the two methods fail in almost opposite places.
+--------------------------------------------------+
| SPARSE FAILS ON DENSE FAILS ON |
| synonyms rare terms |
| paraphrases identifiers |
| other languages out of domain |
| short vague queries long documents |
| misspellings exact matching |
+--------------------------------------------------+
So, we can combine them. This is called hybrid search.
HYBRID SEARCH
question
|
+-------------------------+
| |
↓ ↓
+---------------+ +---------------+
| SPARSE | | DENSE |
| exact terms | | meaning |
+---------------+ +---------------+
| |
top 30 top 30
| |
+------------+------------+
|
↓
+------------------+
| MERGE the two |
+------------------+
|
↓
+------------------+
| RERANK |
+------------------+
|
↓
top 5
Hybrid search often works better than either method alone, because real users ask both kinds of question.
If we want to go deep into RAG and build an AI Tutor from scratch, check out our AI and Machine Learning Program at Outcome School.
How to combine the two scores
This detail is important, because the two scores are not comparable.
sparse score an unbounded number, typically 0 to 40
dense score a similarity, typically 0 to 1
Adding them means the sparse score dominates completely.
Normalizing them is unstable, because the sparse range
depends on the query.
The reliable answer is to combine by rank rather than by score.
Reciprocal Rank Fusion is a common method for this.
For each result, add up: 1 / (k + rank) from each list
with k usually set to 60
EXAMPLE
document sparse rank dense rank score
-------- ----------- ---------- -----
doc A 1 8 1/61 + 1/68 = 0.0311
doc B 3 absent 1/63 = 0.0159
doc C absent 1 1/61 = 0.0164
doc D 5 4 1/65 + 1/64 = 0.0310
Here, we can see the behavior we want.
Document A ranks top overall, because both methods liked it. Document D nearly ties it, because both methods liked it reasonably. Documents B and C score lower, because only one method found them.
Rank fusion needs almost no tuning, no normalization, and no knowledge of the score ranges.
A weighted combination is worth trying afterwards, where we normalize both scores and weight them, because it lets us favor one method for our specific query mix. It needs tuning on our own data, and it can beat rank fusion when tuned well.
Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.
When to use which one
Let me tabulate this clearly.
| Situation | Use |
|---|---|
| A general production search system | Hybrid |
| Queries contain identifiers, codes, or part numbers | Hybrid, weighted to sparse |
| A technical or internal domain with its own jargon | Hybrid, weighted to sparse |
| Users ask in natural conversational language | Hybrid, weighted to dense |
| We serve several languages | Hybrid, dense is essential |
| We cannot run a model at indexing time | Sparse only |
| We need to explain why a result matched | Sparse, or learned sparse |
| The corpus updates constantly | Sparse handles it better |
| Documents are very long | Sparse, or chunk for dense |
| We have no labeled data to tune anything | Hybrid with rank fusion |
| We want one index with synonym matching | Learned sparse |
| A quick prototype, one domain, natural language | Dense alone is fine |
A good default is to start with hybrid search using rank fusion, and add a reranker. It needs very little tuning, and it handles both query types.
A complete code example
Let's see the code for all three approaches and the fusion. We can write the code as below:
import math
from collections import Counter, defaultdict
# ---------- SPARSE: BM25 ----------
class BM25:
def __init__(self, docs, k1=1.5, b=0.75):
self.docs = [d.lower().split() for d in docs]
self.k1, self.b = k1, b
self.avg_len = sum(len(d) for d in self.docs) / len(self.docs)
# an inverted index: term -> the documents containing it
self.index = defaultdict(list)
for i, doc in enumerate(self.docs):
for term, count in Counter(doc).items():
self.index[term].append((i, count))
# a rare term carries far more weight than a common one
n = len(self.docs)
self.idf = {t: math.log(1 + (n - len(p) + 0.5) / (len(p) + 0.5))
for t, p in self.index.items()}
def search(self, query, top_k=30):
scores = defaultdict(float)
# only documents sharing a term are ever touched
for term in query.lower().split():
for doc_id, count in self.index.get(term, []):
length = len(self.docs[doc_id])
norm = 1 - self.b + self.b * length / self.avg_len
scores[doc_id] += (self.idf[term] * count * (self.k1 + 1)
/ (count + self.k1 * norm))
return sorted(scores.items(), key=lambda x: -x[1])[:top_k]
# ---------- DENSE ----------
def build_dense(docs, model):
# one model call per document, and a fixed size vector each
return model.encode(docs, normalize_embeddings=True)
def dense_search(query, vectors, model, top_k=30):
q = model.encode([query], normalize_embeddings=True)[0]
sims = vectors @ q # cosine, since both are normalized
top = sims.argsort()[::-1][:top_k]
return [(int(i), float(sims[i])) for i in top]
# ---------- COMBINE BY RANK, NOT BY SCORE ----------
def reciprocal_rank_fusion(rankings, k=60):
"""The two score scales are not comparable, so we use position."""
fused = defaultdict(float)
for ranking in rankings:
for rank, (doc_id, _score) in enumerate(ranking, start=1):
fused[doc_id] += 1.0 / (k + rank)
return sorted(fused.items(), key=lambda x: -x[1])
# ---------- THE FULL HYBRID PIPELINE ----------
def hybrid_search(query, docs, bm25, vectors, model, reranker, top_k=5):
sparse_hits = bm25.search(query, top_k=30)
dense_hits = dense_search(query, vectors, model, top_k=30)
fused = reciprocal_rank_fusion([sparse_hits, dense_hits])[:20]
# the reranker reads the query and the document together, which is
# usually more accurate than either vector comparison
candidates = [docs[i] for i, _ in fused]
scored = reranker.rank(query, candidates)
return scored[:top_k]
# ---------- EXAMPLE QUERIES ----------
QUERIES = {
"error ERR_4471": "sparse finds it, dense cannot",
"how do I get my money back": "dense finds it, sparse cannot",
"SKU-88213 warranty": "sparse is essential here",
"laptop will not start": "dense is essential here",
}
# Both query types appear in real traffic, which is the whole
# argument for running both.
Here, we can notice the following:
- We built an inverted index for the sparse method, so a search only ever touches documents that share a term with the query.
- We weighted rare terms far more heavily than common ones, which is what makes an identifier match so precisely.
- We normalized the dense vectors, so the similarity is a simple dot product.
- We retrieved a wide set from both methods rather than a narrow one, because the fusion needs candidates to work with.
- We combined by rank rather than by score, because a BM25 score and a cosine similarity are on completely different scales and cannot be added.
- We reranked the fused list, because a model reading the query and the document together is usually more accurate than either vector comparison.
- We kept both methods because real query traffic contains both kinds of question.
Now we must have understood Sparse Embeddings vs Dense Embeddings, and when to use which one.
Frequently Asked Questions
Is BM25 a sparse embedding?
Yes. BM25 is the classic method for producing the weights in a sparse embedding. It gives a word more weight when it appears more often in the document, and much more weight when it appears in fewer documents overall. Every non-zero position still names one word in the vocabulary.
What is the vocabulary mismatch problem?
The vocabulary mismatch problem is when a query and a document mean the same thing but share no words, like "how do I get my money back" and "refund procedure". A sparse method scores them zero. It also cannot see synonyms, paraphrases, misspellings, or other languages. Dense embeddings and learned sparse embeddings reduce this problem.
Is SPLADE a sparse or a dense embedding?
SPLADE is a learned sparse embedding. It uses a neural network to decide the weights and can add terms that were not in the text, like "refund" for "money back". The vector is still sparse, every position still names a word, and it is still stored in a normal inverted index.
Can we compare dense embeddings from two different models?
No. Vectors from two different embedding models cannot be compared. That is why changing the embedding model means re-embedding the entire corpus, with a model call for every document. A sparse method like BM25 has no model, so it does not have this cost.
Do we still need a reranker with hybrid search?
Yes, it is a good default. Start with hybrid search using rank fusion, and add a reranker on the fused list. The reranker reads the query and the document together, which is usually more accurate than either vector comparison, so the final top results get better.
That's it for now.
Thanks
Amit Shekhar
Founder @ Outcome School
You can connect with me on:
Follow Outcome School on:
