Dense Retrieval and Semantic Similarity
A user types "how far can an e-bike go"; the help article says "Electric bikes have a range of about 60 km". The two share only the word "bike", and so do half the articles. Keyword search with BM25 scores by shared terms, so it ranks this article 6th. Dense retrieval encodes the query and every document into vectors with a neural encoder and ranks documents by vector similarity, so "e-bike" and "electric bike", "range" and "how far", end up close.
This lesson measures both approaches on the same small help centre, fuses them, explains re-ranking with a cross-encoder, and writes the contrastive loss that trains retrieval encoders from scratch. How a sentence becomes one vector (mean pooling, normalisation) is in Sentence Embeddings; how vector indexes find neighbours quickly is in Vector Search. Dense retrieval is the "R" of retrieval-augmented generation.
The pipeline
A bi-encoder encodes queries and documents separately. Documents are encoded once, offline, and stored; a query costs one encoder call plus a nearest-neighbour search. With unit vectors and the score is the cosine similarity, which for unit vectors is just the dot product:
Measuring retrieval
Each of the 12 test queries has exactly one relevant document. If the relevant document of query is at rank (1 = first):
Recall@3 asks "is the answer among the 3 passages we would hand to a language model?"; MRR rewards putting it first. With 12 queries one query is of recall, so these numbers only show tendencies; Evaluating Retrieval and RAG covers building a larger test set.
BM25 on the help centre, from scratch
The corpus is the TAD Bikes help centre used throughout the course: 16 short articles and 12 user questions with the id of the article that answers each. BM25 with , , the idf and the analyser of the keyword-retrieval lesson: lower-case, words of at least 2 characters, a 33-word stop list, Porter stems:
import re
import numpy as np
from nltk.stem import PorterStemmer
docs = [
"Rentals are charged per hour. The first 30 minutes cost 2 euros and every extra hour costs 3 euros.",
"A day pass costs 15 euros and covers unlimited rides for 24 hours from the first unlock.",
"To unlock a bike, scan the QR code on the handlebar with the app and wait for the green light.",
"If the lock does not open, check that Bluetooth is on and move closer to the bike, then try again.",
"Return the bike at any station. Push it into a free dock until the light turns green and you hear a beep.",
"If a station is full, the app shows the nearest station with free docks and adds 15 free minutes.",
"Report a damaged bike in the app under Help, Report a problem, and add a photo of the damage.",
"Electric bikes have a range of about 60 km. The battery level is shown on the display and in the app.",
"Children under 14 may not rent bikes. Riders between 14 and 18 need permission from a parent.",
"Helmets are not included in the rental, but we recommend wearing one on every ride.",
"You can pay with a credit card, a debit card or the app wallet. Cash is not accepted.",
"Refunds for a ride that was charged twice are sent to the original card within five working days.",
"A lost bike must be reported within 24 hours. If it is not found, a fee of 400 euros is charged.",
"Our support team answers chat messages every day from 7 am to 10 pm.",
"Students get 30 percent off the monthly pass with a valid student card uploaded in the app.",
"Bikes can be reserved for up to 10 minutes before unlocking. A reservation is free.",
]
queries = [ # (query, id of the relevant document)
("how much does one hour cost", 0), ("price for a whole day", 1), ("the lock will not open", 3),
("where do I leave the bike when the dock is full", 5), ("my bike has a flat tyre", 6),
("how far can an e-bike go", 7), ("can my 12 year old rent a bike", 8), ("do you take cash", 10),
("I was charged twice", 11), ("what happens if my bike is stolen", 12), ("discount for students", 14),
("can I hold a bike for later", 15),
]
STOP = set("a an and are as at be but by for if in into is it no not of on or such that the their "
"then there these they this to was will with".split())
stem = PorterStemmer().stem
def tokenize(text): # the keyword-retrieval analyser: 2+ char words, stop words out, Porter stems
return [stem(w) for w in re.findall(r"\b\w\w+\b", text.lower()) if w not in STOP]
def bm25_scores(query, docs, k1=1.5, b=0.75):
D = [tokenize(d) for d in docs]
N, avgdl = len(D), np.mean([len(d) for d in D])
scores = np.zeros(N)
for term in set(tokenize(query)):
n = sum(term in d for d in D) # documents containing the term
idf = np.log(1 + (N - n + 0.5) / (n + 0.5))
for i, d in enumerate(D):
f = d.count(term)
scores[i] += idf * f * (k1 + 1) / (f + k1 * (1 - b + b * len(d) / avgdl))
return scores
ranks = []
for q, rel in queries:
order = np.argsort(-bm25_scores(q, docs), kind="stable")
ranks.append(int(np.where(order == rel)[0][0]) + 1)
if ranks[-1] > 1:
print(f"{q!r}: relevant doc {rel} at rank {ranks[-1]}; top hit is doc {order[0]}: {docs[order[0]][:45]}...")
ranks = np.array(ranks)
print(f"BM25: recall@1 {np.mean(ranks <= 1):.3f} | recall@3 {np.mean(ranks <= 3):.3f} | MRR {np.mean(1 / ranks):.3f}")'price for a whole day': relevant doc 1 at rank 3; top hit is doc 11: Refunds for a ride that was charged twice are...
'my bike has a flat tyre': relevant doc 6 at rank 4; top hit is doc 2: To unlock a bike, scan the QR code on the han...
'how far can an e-bike go': relevant doc 7 at rank 6; top hit is doc 15: Bikes can be reserved for up to 10 minutes be...
'what happens if my bike is stolen': relevant doc 12 at rank 6; top hit is doc 2: To unlock a bike, scan the QR code on the han...
BM25: recall@1 0.667 | recall@3 0.750 | MRR 0.743
BM25 puts the right article first for 8 of the 12 queries (recall@1 0.667) and in the top 3 for 9 (recall@3 0.750). It wins where a question reuses the article's words ("charged twice", "cash", "lock", "students"). Its four misses are vocabulary mismatches: "price for a whole day" shares only "day" with the day-pass article, and "days" in the refund article is also stemmed to "day"; "flat tyre" and "stolen" never appear in the corpus, so those queries are left with the common term "bike" and their right articles land at ranks 4 and 6; "e-bike" loses its 1-letter "e" and keeps only "bike", which matches "bikes" in the battery article after stemming but also half the corpus, so that article is 6th behind article 15, which also contains "can". Without stop-word removal and stemming, BM25 scores higher on this tiny set, but mostly by matching function words such as "if", "is" and "can", as keyword-retrieval shows.
Dense retrieval with MiniLM, and fusion
all-MiniLM-L6-v2 is a 6-layer, 384-dimensional sentence encoder trained with the contrastive loss described below on over a billion sentence pairs. The recorded example encodes the 16 articles and 12 queries, ranks by cosine similarity, and then fuses the BM25 and dense rankings two ways:
- Reciprocal rank fusion (RRF): each list gives a document , with the usual , and the sums are re-sorted. It needs only ranks, so the two score scales do not matter.
- Score fusion: min-max normalise each retriever's scores per query to and average them with equal weights.
import re
import numpy as np
from nltk.stem import PorterStemmer
from sentence_transformers import SentenceTransformer
docs = [
"Rentals are charged per hour. The first 30 minutes cost 2 euros and every extra hour costs 3 euros.",
"A day pass costs 15 euros and covers unlimited rides for 24 hours from the first unlock.",
"To unlock a bike, scan the QR code on the handlebar with the app and wait for the green light.",
"If the lock does not open, check that Bluetooth is on and move closer to the bike, then try again.",
"Return the bike at any station. Push it into a free dock until the light turns green and you hear a beep.",
"If a station is full, the app shows the nearest station with free docks and adds 15 free minutes.",
"Report a damaged bike in the app under Help, Report a problem, and add a photo of the damage.",
"Electric bikes have a range of about 60 km. The battery level is shown on the display and in the app.",
"Children under 14 may not rent bikes. Riders between 14 and 18 need permission from a parent.",
"Helmets are not included in the rental, but we recommend wearing one on every ride.",
"You can pay with a credit card, a debit card or the app wallet. Cash is not accepted.",
"Refunds for a ride that was charged twice are sent to the original card within five working days.",
"A lost bike must be reported within 24 hours. If it is not found, a fee of 400 euros is charged.",
"Our support team answers chat messages every day from 7 am to 10 pm.",
"Students get 30 percent off the monthly pass with a valid student card uploaded in the app.",
"Bikes can be reserved for up to 10 minutes before unlocking. A reservation is free.",
]
queries = [ # (query, id of the relevant document)
("how much does one hour cost", 0), ("price for a whole day", 1), ("the lock will not open", 3),
("where do I leave the bike when the dock is full", 5), ("my bike has a flat tyre", 6),
("how far can an e-bike go", 7), ("can my 12 year old rent a bike", 8), ("do you take cash", 10),
("I was charged twice", 11), ("what happens if my bike is stolen", 12), ("discount for students", 14),
("can I hold a bike for later", 15),
]
STOP = set("a an and are as at be but by for if in into is it no not of on or such that the their "
"then there these they this to was will with".split())
stem = PorterStemmer().stem
def tokenize(text): # the keyword-retrieval analyser: 2+ char words, stop words out, Porter stems
return [stem(w) for w in re.findall(r"\b\w\w+\b", text.lower()) if w not in STOP]
def bm25_scores(query, docs, k1=1.5, b=0.75):
D = [tokenize(d) for d in docs]
N, avgdl = len(D), np.mean([len(d) for d in D])
scores = np.zeros(N)
for term in set(tokenize(query)):
n = sum(term in d for d in D)
idf = np.log(1 + (N - n + 0.5) / (n + 0.5))
for i, d in enumerate(D):
f = d.count(term)
scores[i] += idf * f * (k1 + 1) / (f + k1 * (1 - b + b * len(d) / avgdl))
return scores
def ranks_of_relevant(rank_lists):
return np.array([list(r).index(rel) + 1 for r, (_, rel) in zip(rank_lists, queries)])
def report(name, ranks):
print(f"{name:16s} recall@1 {np.mean(ranks <= 1):.3f} | recall@3 {np.mean(ranks <= 3):.3f} | MRR {np.mean(1 / ranks):.3f} | ranks {ranks.tolist()}")
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
D = model.encode(docs, normalize_embeddings=True) # 16 x 384, unit length
Q = model.encode([q for q, _ in queries], normalize_embeddings=True)
print("embeddings:", D.shape, "| norm of the first:", round(float(np.linalg.norm(D[0])), 3))
S = Q @ D.T # cosine similarity = dot product of unit vectors
dense = [np.argsort(-s, kind="stable") for s in S]
bm25 = [np.argsort(-bm25_scores(q, docs), kind="stable") for q, _ in queries]
def rrf(*rank_lists, k=60): # reciprocal rank fusion
fused = []
for lists in zip(*rank_lists):
score = np.zeros(len(docs))
for r in lists:
score[r] += 1 / (k + np.arange(1, len(r) + 1)) # doc at rank p gets 1 / (k + p)
fused.append(np.argsort(-score, kind="stable"))
return fused
report("BM25", ranks_of_relevant(bm25))
report("dense MiniLM", ranks_of_relevant(dense))
report("hybrid (RRF)", ranks_of_relevant(rrf(bm25, dense)))
def minmax(x):
return (x - x.min()) / (x.max() - x.min())
fused = [np.argsort(-(0.5 * minmax(bm25_scores(q, docs)) + 0.5 * minmax(s)), kind="stable") for (q, _), s in zip(queries, S)]
report("hybrid (0.5/0.5)", ranks_of_relevant(fused))
for i in [3, 4, 5]:
q, rel = queries[i]
print(f"{q!r}: dense top-2 {dense[i][:2].tolist()} cos {[round(float(x), 3) for x in S[i][dense[i][:2]]]} | BM25 top-2 {bm25[i][:2].tolist()} | relevant {rel}")embeddings: (16, 384) | norm of the first: 1.0
BM25 recall@1 0.667 | recall@3 0.750 | MRR 0.743 | ranks [1, 3, 1, 1, 4, 6, 1, 1, 1, 6, 1, 1]
dense MiniLM recall@1 0.833 | recall@3 1.000 | MRR 0.917 | ranks [1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1]
hybrid (RRF) recall@1 0.667 | recall@3 0.917 | MRR 0.799 | ranks [1, 1, 1, 2, 3, 2, 1, 1, 1, 4, 1, 1]
hybrid (0.5/0.5) recall@1 0.833 | recall@3 1.000 | MRR 0.917 | ranks [1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1]
'where do I leave the bike when the dock is full': dense top-2 [4, 5] cos [0.551, 0.412] | BM25 top-2 [5, 4] | relevant 5
'my bike has a flat tyre': dense top-2 [4, 6] cos [0.324, 0.283] | BM25 top-2 [2, 3] | relevant 6
'how far can an e-bike go': dense top-2 [7, 12] cos [0.569, 0.357] | BM25 top-2 [15, 10] | relevant 7
| Retriever (12 queries, 16 articles) | recall@1 | recall@3 | MRR |
|---|---|---|---|
| BM25 | 0.667 | 0.750 | 0.743 |
| dense, all-MiniLM-L6-v2 | 0.833 | 1.000 | 0.917 |
| hybrid, reciprocal rank fusion () | 0.667 | 0.917 | 0.799 |
| hybrid, 0.5 BM25 + 0.5 cosine after min-max | 0.833 | 1.000 | 0.917 |
Dense retrieval wins clearly: recall@1 0.833 against 0.667, and every relevant article in its top 3. It finds the paraphrases BM25 misses ("e-bike" is first with cosine 0.569, "whole day" and "stolen" are first as well). Its two misses are near misses: it puts the "return the bike at a station" article above the right one for "leave the bike when the dock is full" and for "flat tyre", because both questions are about returning or damaging a bike, and the encoder sees topic similarity more than the specific condition "full" or "damage". BM25 gets the dock question right, because "dock" and "full" overlap literally.
The two fusions behave differently here. RRF lands between the two (recall@1 0.667, recall@3 0.917): it rewards agreement, so a document that one list ranks badly is pulled down. The e-bike article gets (dense rank 1, BM25 rank 6), less than article 15's (BM25 rank 1, dense rank 3), and drops to 2nd; "stolen" drops to 4th. Score fusion matches dense on the summary numbers (0.833, 1.000, 0.917) with different ranks: BM25's strong literal match fixes the dock question (now rank 1), while the "e-bike" query falls to rank 2. Scores keep the information that one retriever is very confident and the other unsure, which ranks discard. On large corpora, where each retriever's misses are partial (the right document is at rank 5 in one list and 20 in the other), hybrid search usually beats both, which is why it is the default in many RAG stacks. On 12 queries every difference above is one or two queries: measure on your own labelled queries, and choose the fusion and its weight on a different set from the one you report.
Re-ranking with a cross-encoder
A cross-encoder reads the query and one document together, [CLS] query [SEP] document [SEP], and outputs one relevance score from the [CLS] vector, like the sequence classifier of this section. Because every query token can attend to every document token, it notices that "flat tyre" is about damage and "dock is full" about a full station. But nothing can be pre-computed: scoring documents needs forward passes per query. The standard design therefore retrieves the top 20 to 100 with a bi-encoder (or hybrid) and re-ranks only those. No cross-encoder is cached in this course's image, so the code is shown without running:
from sentence_transformers import CrossEncoder
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2") # needs a download, not run here
candidates = dense[4][:5] # top 5 from the bi-encoder
scores = reranker.predict([(queries[4][0], docs[i]) for i in candidates])
reranked = [int(candidates[j]) for j in np.argsort(-scores)]Training a retriever: in-batch negatives
Retrieval encoders are trained on (query, relevant passage) pairs. With a batch of pairs, each query's own passage is the positive and the other passages in the batch serve as in-batch negatives, for free. The loss is softmax cross-entropy over scaled cosine similarities, with the right answers on the diagonal (InfoNCE; MultipleNegativesRankingLoss in sentence-transformers, whose default scale is ):
This is contrastive learning with one positive and many negatives per query. Bigger batches give more and harder negatives, which is why retrieval models are trained with batches of hundreds or thousands, and why hard negatives (passages that look relevant but are not, often mined with BM25) are added to each pair. The NumPy version below learns a linear query encoder for synthetic data: documents are fixed random 16-dimensional vectors, and each query lives in a rotated, distorted and noisy version of the same space, so the raw query vector is useless for search. The code checks the analytic gradient (through the softmax and the normalisation) against a finite difference, then trains with batches of 32:
import numpy as np
rng = np.random.default_rng(0)
dim, n_train, n_test, scale = 16, 384, 100, 20.0
docs = rng.normal(size=(n_train + n_test, dim)) # document embeddings (kept fixed)
M = np.linalg.qr(rng.normal(size=(dim, dim)))[0] + 0.3 * rng.normal(size=(dim, dim)) # a different, distorted space
queries = docs @ M.T + 0.6 * rng.normal(size=docs.shape) # a query lives in a distorted, noisy space
def unit(X):
return X / np.linalg.norm(X, axis=1, keepdims=True)
def mnr_loss(W, Xq, Xd):
"""In-batch negatives: query i must pick document i among the batch's documents."""
Q, D = Xq @ W.T, unit(Xd)
nq = np.linalg.norm(Q, axis=1, keepdims=True); Qn = Q / nq
S = scale * Qn @ D.T # B x B scaled cosine similarities
S = S - S.max(1, keepdims=True)
P = np.exp(S) / np.exp(S).sum(1, keepdims=True)
B = len(Xq)
loss = -np.log(np.diag(P)).mean()
dS = (P - np.eye(B)) / B # softmax cross-entropy with labels 0..B-1
dQn = scale * dS @ D
dQ = (dQn - Qn * (dQn * Qn).sum(1, keepdims=True)) / nq # back through the normalisation
return loss, dQ.T @ Xq
def recall_at_1(W):
Q, D = unit(queries[n_train:] @ W.T), unit(docs[n_train:])
return float(np.mean((Q @ D.T).argmax(1) == np.arange(n_test)))
W = np.eye(dim) # start: use the query vector as it is
loss, grad = mnr_loss(W, queries[:32], docs[:32])
E = np.zeros_like(W); E[2, 5] = 1e-6
num = (mnr_loss(W + E, queries[:32], docs[:32])[0] - mnr_loss(W - E, queries[:32], docs[:32])[0]) / 2e-6
print(f"gradient check dL/dW[2,5]: analytic {grad[2, 5]:.6f} | numeric {num:.6f}")
print(f"before training: batch loss {loss:.3f} (chance would be ln 32 = {np.log(32):.3f}) | test recall@1 {recall_at_1(W):.2f} (100 docs)")
for epoch in range(30):
for idx in rng.permutation(n_train).reshape(-1, 32):
loss, grad = mnr_loss(W, queries[idx], docs[idx])
W -= 0.05 * grad
print(f"after 30 epochs: batch loss {loss:.3f} | test recall@1 {recall_at_1(W):.2f} (100 held-out pairs)")gradient check dL/dW[2,5]: analytic 0.136647 | numeric 0.136647
before training: batch loss 12.210 (chance would be ln 32 = 3.466) | test recall@1 0.01 (100 docs)
after 30 epochs: batch loss 0.036 | test recall@1 0.94 (100 held-out pairs)
Before training the loss (12.210) is far above the of a uniform guess: the raw query vectors point confidently at the wrong documents, and recall@1 among 100 held-out documents is 0.01, chance level. After 30 epochs the learned map finds the right document first for 94 of 100 held-out queries it never trained on. Real retrievers do the same with a transformer instead of , usually sharing one encoder for queries and documents. In sentence-transformers the fine-tuning code is short (not run here: it needs your own training pairs and minutes of compute):
from datasets import Dataset
from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer, losses
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
pairs = Dataset.from_dict({"anchor": train_questions, "positive": train_passages}) # one row per pair
loss = losses.MultipleNegativesRankingLoss(model) # in-batch negatives, scale 20
SentenceTransformerTrainer(model=model, train_dataset=pairs, loss=loss).train()Indexes: brute force and approximate search
The recorded example computed all similarities with one matrix product: brute-force (exact) search. That stays practical up to around a million vectors on a CPU (a million 384-dimensional float32 vectors are 1.5 GB, and one query is one matrix-vector product). Beyond that, approximate nearest-neighbour (ANN) indexes such as IVF (search only the few clusters nearest to the query) or HNSW (a navigable graph) trade a little recall for speed; Vector Search builds an IVF index with k-means. When you switch to ANN, measure recall@k of the index against brute force on your queries, as a separate number from the retriever's recall.
Pitfalls
- Comparing unnormalised vectors with the dot product. Long or frequent texts get larger norms and win everywhere. Normalise (
normalize_embeddings=True) or use cosine. - Mixing encoders. Queries and documents must be encoded by the same model (and the same version). Re-embed the whole index when you change the model.
- Ignoring the length limit. MiniLM truncates at 256 word pieces (it was trained on 128); a long page becomes the embedding of its beginning. Split documents into passages (chunking).
- Asymmetric models without their prefixes. Some retrieval models (E5, BGE and others) expect "query: " and "passage: " prefixes or an instruction on the query side; leaving them out silently costs recall.
- Assuming hybrid always wins. It usually helps on large corpora, but it did not on this one. Keep a labelled query set and measure every change.
- Tuning on the test queries. The fusion weight, of RRF or the re-ranking depth chosen on 12 queries will not transfer; tune on one set, report on another.
Practice
- A query's relevant document is at rank 1 for BM25 and rank 7 for the dense retriever. What is its RRF score with , and how does it compare with a document at rank 3 in both lists?
- Why does the training loop need no explicit negative examples, and what goes wrong if two pairs in a batch share the same passage?
- The dense retriever ranks "return the bike" first for "my bike has a flat tyre". Name two changes that could fix this without dropping dense retrieval.
- Recall@3 is 1.000 for the dense retriever. Why is that not proof that it is better than BM25 for this help centre?
Answers
- against : the document ranked 3 by both wins by a hair. RRF prefers agreement over one strong vote.
- The other passages of the batch act as negatives. If two queries share a passage, that passage is both the positive and a "negative" for each of them, so the loss pushes the right answer away; deduplicate batches (sentence-transformers'
NoDuplicatesBatchSampler). - Re-rank the top candidates with a cross-encoder, add domain words to the training data ("flat tyre" means damage), or fine-tune the encoder on in-domain pairs with hard negatives such as the "return the bike" article.
- Twelve queries: one query is 0.083 of recall, and the queries were written by the same person who wrote the articles. A real comparison needs a few hundred labelled queries and confidence intervals.
Test yourself
Why can a bi-encoder search millions of documents quickly while a cross-encoder cannot?
- The bi-encoder is a larger model
- Document vectors are computed once offline; a query needs one encoder call plus a vector search, while a cross-encoder needs one forward pass per query-document pair
- Cross-encoders cannot run on GPUs
- Bi-encoders do not use attention
On the 12 help-centre queries, BM25 had recall@3 0.750 and MiniLM 1.000. What explains the difference?
- MiniLM is broken
- BM25 needs shared words, so questions phrased differently from their article ('e-bike', 'whole day', 'stolen') fall down its ranking; MiniLM matches meaning and only confuses topically similar articles
- BM25 uses embeddings
- The queries were used to train MiniLM
In the in-batch negatives loss with a batch of pairs, what are the negatives for query ?
- Random vectors
- The other passages in the batch
- All documents in the corpus
- The other queries
With RRF and , why did the e-bike article fall to rank 2 although the dense retriever ranked it first?
- RRF uses the cosine values
- BM25 ranked it 6th, and is smaller than for article 15 (BM25 rank 1, dense rank 3)
- RRF ignores dense scores
- The article was too long