Comparing Two Embedding Models
Score two embedding models on the same 20 labelled queries with recall@k and MRR, read their failures, measure latency and cost per 1,000 documents in code, check whether the gap is bigger than the noise, and record a decision you can defend.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: A small labelled query set
- Step 2: One interface for local and hosted models
- Step 3: Score both models on the same queries
- Step 4: Read the failures
- Step 5: Measure latency and cost
- Step 6: Is the difference bigger than the noise?
- Step 7: Write down the decision
- Troubleshooting
- Check your understanding
- Apply it (stretch)
- Review prompt
Lessons of Embeddings
- From Text to Vectors, and What Vectors Are For Concept · 15 min
- Similarity by Hand and in NumPy Worked example · 20 min
- Lab: Embed a Corpus in Batches Lab · 25 min
- Comparing Two Embedding Models Lab · 25 min
- Check: Similarity and Model Choice Knowledge check · 6 questions
What you will learn
- Compare two embedding models on a small labeled query set and justify the choice by quality, cost and latency.
Prerequisites: Data Handling
01. Goal and setup
Your help centre is in English, but about a third of your users write in Vietnamese. Should search use all-MiniLM-L6-v2, the small English model from the earlier lessons, or the larger, multilingual intfloat/multilingual-e5-small? This lab collects four kinds of evidence: quality on the same labelled queries, overall and per language; the failures behind the numbers; latency and cost per 1,000 documents; and whether the difference is bigger than the noise of 20 queries.
Two metrics are enough here; the RAG retrieval evaluation skill covers them in depth. recall@k is the share of a query's relevant documents found in the top k, so with one relevant document it asks "was it in the top k?". MRR@10 averages 1 / rank of the first relevant document: 1 for first place, 0.5 for second, 0 beyond tenth.
Use the environment from the previous lab. The multilingual model is a download of about 470 MB on first use. If OPENAI_API_KEY and OPENAI_EMBED_MODEL are set, the scripts add a hosted model as a third candidate.
compare-lab/
eval_data.py 30 documents, 20 labelled queries
embedders.py one interface for local and hosted models
quality.py recall@1, recall@3, MRR@10 per model and language
failures.py the queries each model got wrong
speed_cost.py seconds and dollars per 1,000 documents
paired.py is the difference bigger than the noise?
results/02. Step 1: A small labelled query set
The query set decides what "better" means, so build it from your traffic, not from your documents. Write questions the way users write them, which is usually shorter and vaguer than the article and in other words; mix the languages in roughly the proportions you see; and label at least one relevant document for each question. Twenty queries is a starting point for a first decision, not a verdict.
# A help centre of 30 short articles and 20 labelled queries (14 English, 6 Vietnamese).
DOCS = {
'd01': 'Reset your password from the sign-in page with "Forgot password".',
'd02': 'Two-factor codes expire after 30 seconds; check your phone clock.',
'd03': 'Accounts lock for 15 minutes after five failed sign-in attempts.',
'd04': 'Single sign-on users sign in through their company identity provider.',
'd05': 'Invoices are emailed to the billing contact on the 1st of each month.',
'd06': 'Edit your billing profile to change the VAT number on invoices.',
'd07': 'Refunds for annual plans are prorated and take 5 to 10 days.',
'd08': 'Upgrade or downgrade your plan at any time under Billing > Plan.',
'd09': 'We accept Visa, Mastercard and bank transfer, but not PayPal.',
'd10': 'Export any report to CSV or Parquet from the Reports menu.',
'd11': 'Scheduled exports run nightly at 02:00 UTC and are kept 30 days.',
'd12': 'Import contacts from a CSV file with a header row, up to 50 MB.',
'd13': 'Invite teammates under Settings > Members; invites expire in 7 days.',
'd14': 'Admins can remove a member; their data stays in the workspace.',
'd15': 'Owners manage billing, admins manage members, editors edit data.',
'd16': 'Create API keys under Settings > API; each key is shown only once.',
'd17': 'Rotate a key by creating a new one, then deleting the old key.',
'd18': 'Each API key may send 100 requests per minute; extra calls get 429.',
'd19': 'Webhooks retry failed deliveries with backoff for up to 24 hours.',
'd20': 'Verify webhook signatures with the secret in the X-Signature header.',
'd21': 'The mobile app works offline and syncs when you reconnect.',
'd22': 'Turn off push notifications per project in the mobile app.',
'd23': 'Delete your account under Settings > Privacy.',
'd24': 'Download a copy of all your personal data under Settings > Privacy.',
'd25': 'Customer data is stored in the EU (Frankfurt) region.',
'd26': 'Dark mode follows your system setting or can be set in Appearance.',
'd27': 'Change the interface language under Settings > Language.',
'd28': 'Press ? anywhere in the app to see all keyboard shortcuts.',
'd29': 'The status page lists current incidents and planned maintenance.',
'd30': 'Chat support is open on weekdays, 08:00 to 18:00 Vietnam time.',
}
# (query id, language, text, ids of the relevant documents)
QUERIES = [
('q01', 'en', 'I forgot my password', ['d01']),
('q02', 'en', 'my authenticator code keeps getting rejected', ['d02']),
('q03', 'en', "locked out after typing the wrong password", ['d03']),
('q04', 'en', 'money back for a yearly subscription', ['d07']),
('q05', 'en', 'can I pay with PayPal', ['d09']),
('q06', 'en', 'the tax ID on my bill is wrong', ['d06']),
('q07', 'en', 'get my numbers into a spreadsheet', ['d10']),
('q08', 'en', 'add a colleague to our workspace', ['d13']),
('q09', 'en', 'the API says too many requests', ['d18']),
('q10', 'en', 'how long are nightly exports kept', ['d11']),
('q11', 'en', 'which country is my data hosted in', ['d25']),
('q12', 'en', 'replace a leaked API key', ['d17']),
('q13', 'en', 'is there a dark theme', ['d26']),
('q14', 'en', 'who is allowed to change our payment details', ['d15']),
('q15', 'vi', 'Tôi quên mật khẩu', ['d01']),
('q16', 'vi', 'Làm sao để xuất báo cáo ra file CSV?', ['d10']),
('q17', 'vi', 'Hoàn tiền cho gói năm mất bao lâu?', ['d07']),
('q18', 'vi', 'Làm thế nào để xoá tài khoản?', ['d23']),
('q19', 'vi', 'Ứng dụng có dùng được khi không có mạng không?', ['d21']),
('q20', 'vi', 'Giờ làm việc của bộ phận hỗ trợ', ['d30']),
]In English, the Vietnamese queries ask: "I forgot my password", "How do I export a report to CSV?", "How long does an annual-plan refund take?", "How do I delete my account?", "Does the app work offline?" and "Support team working hours". Several English queries avoid the article's words on purpose (tax ID for VAT number, spreadsheet for CSV).
03. Step 2: One interface for local and hosted models
Every candidate gets the same two methods, documents and queries, both returning unit-length vectors, plus a tokens counter for billing. The local wrapper passes the prefixes a model needs; the hosted wrapper batches requests and adds up usage.total_tokens. A third candidate is one more line.
import numpy as np
from openai import OpenAI
from sentence_transformers import SentenceTransformer
class LocalEmbedder:
"""A sentence-transformers model on this machine; no per-token bill."""
def __init__(self, name: str, revision: str, query: str = '', document: str = ''):
self.name = name
self.tokens = 0
self.model = SentenceTransformer(
name, revision=revision, prompts={'query': query, 'document': document}
)
def documents(self, texts: list[str]) -> np.ndarray:
return self.model.encode_document(
texts, batch_size=64, normalize_embeddings=True
)
def queries(self, texts: list[str]) -> np.ndarray:
return self.model.encode_query(texts, normalize_embeddings=True)
class HostedEmbedder:
"""An embeddings API; counts the tokens it is billed for."""
def __init__(self, name: str, batch_size: int = 256):
self.name = name
self.tokens = 0
self.batch_size = batch_size
self.client = OpenAI() # OPENAI_API_KEY from the environment
def _embed(self, texts: list[str]) -> np.ndarray:
vectors = []
for start in range(0, len(texts), self.batch_size):
batch = texts[start : start + self.batch_size]
response = self.client.embeddings.create(model=self.name, input=batch)
self.tokens += response.usage.total_tokens
items = sorted(response.data, key=lambda item: item.index)
vectors += [item.embedding for item in items]
matrix = np.asarray(vectors, dtype=np.float32)
return matrix / np.linalg.norm(matrix, axis=1, keepdims=True)
documents = _embed
queries = _embed # this API uses no query or document prefix04. Step 3: Score both models on the same queries
quality.py ranks all 30 documents for every query with each model and keeps one row per query and model: the rank of the first relevant document, the top result, recall@1, recall@3 and the reciprocal rank. Steps 4 and 6 need those per-query rows, not just averages.
import os
import numpy as np
import pandas as pd
from embedders import HostedEmbedder, LocalEmbedder
from eval_data import DOCS, QUERIES
DOC_IDS = list(DOCS)
def per_query(embedder) -> pd.DataFrame:
D = embedder.documents(list(DOCS.values()))
Q = embedder.queries([text for _, _, text, _ in QUERIES])
ranking = np.argsort(-(Q @ D.T), axis=1) # best document first, per query
rows = []
for (qid, lang, _, relevant), order in zip(QUERIES, ranking):
ranked = [DOC_IDS[j] for j in order]
rank = 1 + min(ranked.index(d) for d in relevant) # first relevant hit
rows.append({
'model': embedder.name, 'qid': qid, 'lang': lang, 'rank': rank,
'top1': ranked[0],
'recall@1': len(set(relevant) & set(ranked[:1])) / len(relevant),
'recall@3': len(set(relevant) & set(ranked[:3])) / len(relevant),
'rr@10': 1 / rank if rank <= 10 else 0.0,
})
return pd.DataFrame(rows)
def build_embedders() -> list:
embedders = [
LocalEmbedder('sentence-transformers/all-MiniLM-L6-v2',
'1110a243fdf4706b3f48f1d95db1a4f5529b4d41'),
LocalEmbedder('intfloat/multilingual-e5-small',
'614241f622f53c4eeff9890bdc4f31cfecc418b3',
query='query: ', document='passage: '),
]
if os.environ.get('OPENAI_EMBED_MODEL'): # e.g. text-embedding-3-small
embedders.append(HostedEmbedder(os.environ['OPENAI_EMBED_MODEL']))
return embedders
if __name__ == '__main__':
results = pd.concat([per_query(e) for e in build_embedders()])
os.makedirs('results', exist_ok=True)
results.to_csv('results/per_query.csv', index=False)
both = pd.concat([results.assign(lang='all'), results]) # 'all' plus each language
table = both.groupby(['model', 'lang'])[['recall@1', 'recall@3', 'rr@10']].mean()
table = table.rename(columns={'rr@10': 'MRR@10'}).round(2).reset_index()
print(table.to_string(index=False)) model lang recall@1 recall@3 MRR@10
intfloat/multilingual-e5-small all 0.60 1.00 0.76
intfloat/multilingual-e5-small en 0.43 1.00 0.65
intfloat/multilingual-e5-small vi 1.00 1.00 1.00
sentence-transformers/all-MiniLM-L6-v2 all 0.55 0.80 0.67
sentence-transformers/all-MiniLM-L6-v2 en 0.71 1.00 0.85
sentence-transformers/all-MiniLM-L6-v2 vi 0.17 0.33 0.25Read the table from the bottom up, because the overall rows hide the story:
- English: MiniLM ranks the right article first for 10 of 14 queries (0.71), e5 for only 6 (0.43). Both find every English answer within the top 3.
- Vietnamese: e5 is perfect. MiniLM ranks the answer first once and within the top 3 twice, out of six.
- Overall: e5 leads on MRR, 0.76 to 0.67, but that average mixes an English loss with a large Vietnamese win in the proportions of this test set, not of your traffic.
Decide which k matters for your product, too. A RAG pipeline that passes the top 3 chunks to an LLM needs recall@3, where e5 missed no query in this set; a search box that shows one "best answer" needs recall@1, where MiniLM is better in English.
05. Step 4: Read the failures
Averages say how often a model fails; only the failures say why. List every query whose relevant document was not ranked first, with the document that beat it:
import textwrap
import pandas as pd
from eval_data import DOCS
results = pd.read_csv('results/per_query.csv')
for model, misses in results[results['rank'] > 1].groupby('model'):
print(model)
for row in misses.itertuples():
top = textwrap.shorten(DOCS[row.top1], 64, placeholder=' ...')
print(f' {row.qid} rank {row.rank:>2} top: {top}')intfloat/multilingual-e5-small
q02 rank 2 top: Reset your password from the sign-in page with "Forgot ...
q03 rank 2 top: Reset your password from the sign-in page with "Forgot ...
q06 rank 2 top: Reset your password from the sign-in page with "Forgot ...
q07 rank 3 top: Import contacts from a CSV file with a header row, up to 50 MB.
q08 rank 3 top: Admins can remove a member; their data stays in the workspace.
q11 rank 3 top: Download a copy of all your personal data under Settings > ...
q12 rank 3 top: Create API keys under Settings > API; each key is shown only ...
q14 rank 3 top: Edit your billing profile to change the VAT number on invoices.
sentence-transformers/all-MiniLM-L6-v2
q03 rank 2 top: Reset your password from the sign-in page with "Forgot ...
q08 rank 2 top: Admins can remove a member; their data stays in the workspace.
q12 rank 3 top: Create API keys under Settings > API; each key is shown only ...
q14 rank 2 top: Edit your billing profile to change the VAT number on invoices.
q15 rank 11 top: Customer data is stored in the EU (Frankfurt) region.
q16 rank 2 top: Chat support is open on weekdays, 08:00 to 18:00 Vietnam time.
q17 rank 30 top: Chat support is open on weekdays, 08:00 to 18:00 Vietnam time.
q18 rank 12 top: Chat support is open on weekdays, 08:00 to 18:00 Vietnam time.
q19 rank 21 top: Chat support is open on weekdays, 08:00 to 18:00 Vietnam time.Two patterns stand out, and neither shows in the averages:
- MiniLM ranks the support-hours article first for five of the six Vietnamese questions, though it answers only one of them. It is the only document that mentions Vietnam: the model matches the language, not the meaning, and the refund question falls to rank 30 of 30.
- e5 ranks the password-reset article first for three English questions it does not answer. One document that attracts many unrelated queries, a "hub", is a known weakness of dense retrieval and a reason to try a larger model or add keyword search.
Other misses are near misses: for q08 both models put remove a member above invite teammates. If you find a wrong label, fix it, but decide the rule before you look at which model the fix helps.
06. Step 5: Measure latency and cost
speed_cost.py times the embedding of 1,000 documents (the 30 articles repeated, to keep realistic lengths) after a warm-up call, since the first call pays one-off costs such as loading weights. It also times 20 single queries, which is what a user waits for. Cost has two sources:
- hosted: tokens billed × price per million tokens, read from
HOSTED_USD_PER_MTOK. Take it from your provider's pricing page; the default of 0.02 is the list price oftext-embedding-3-smallon OpenAI's pricing page (checked on 17 November 2026). - local: machine time × the hourly cost of the machine, in
LOCAL_USD_PER_HOUR. The 0.10 default is a placeholder for a small cloud VM; a machine you already pay for adds little.
import json
import os
import statistics
import time
from embedders import HostedEmbedder
from eval_data import DOCS, QUERIES
from quality import build_embedders
LOCAL_USD_PER_HOUR = float(os.environ.get('LOCAL_USD_PER_HOUR', '0.10'))
HOSTED_USD_PER_MTOK = float(os.environ.get('HOSTED_USD_PER_MTOK', '0.02'))
BENCH = (list(DOCS.values()) * 34)[:1000] # 1,000 documents of realistic length
def measure(embedder) -> dict:
embedder.documents(BENCH[:8]) # warm-up: first calls pay one-off setup costs
embedder.tokens = 0
start = time.perf_counter()
embedder.documents(BENCH)
seconds = time.perf_counter() - start
query_ms = []
for _, _, text, _ in QUERIES:
start = time.perf_counter()
embedder.queries([text])
query_ms.append((time.perf_counter() - start) * 1000)
if isinstance(embedder, HostedEmbedder):
usd = embedder.tokens / 1e6 * HOSTED_USD_PER_MTOK
else:
usd = seconds / 3600 * LOCAL_USD_PER_HOUR
return {
'model': embedder.name,
'seconds_per_1k_docs': round(seconds, 2),
'median_query_ms': round(statistics.median(query_ms), 1),
'usd_per_1k_docs': round(usd, 6),
}
if __name__ == '__main__':
rows = [measure(e) for e in build_embedders()]
with open('results/speed_cost.json', 'w', encoding='utf-8') as f:
json.dump(rows, f, indent=2)
for row in rows:
name = row['model'].split('/')[-1]
print(f"{name:<22} {row['seconds_per_1k_docs']:>5.1f} s/1k docs "
f"{row['median_query_ms']:>5.1f} ms/query "
f"${row['usd_per_1k_docs']:.6f}/1k docs")all-MiniLM-L6-v2 11.2 s/1k docs 21.8 ms/query $0.000311/1k docs
multilingual-e5-small 24.8 s/1k docs 51.1 ms/query $0.000689/1k docsAbsolute timings depend on the machine and on what else it is doing; on this one, repeat runs differed by up to a factor of two. The ratio was stable: e5-small needs a little over twice as long as MiniLM to embed documents and to answer a query, which fits its 12 transformer layers against MiniLM's 6. Both are fast enough for a search box.
For a hosted comparison, the 1,000 benchmark documents come to 13,636 tokens with the tokenizer of OpenAI's text-embedding-3 models, about $0.0003 at $0.02 per million tokens, plus a network round trip for every query. At this scale cost barely separates the candidates. It starts to matter with millions of long documents, larger hosted models or frequent re-embedding, so record it now in the same units.
07. Step 6: Is the difference bigger than the noise?
With 20 queries, one query moves recall@1 by 0.05, so a small gap can be luck. Both models answered the same queries, so compare them query by query (a paired comparison), and estimate how far the mean difference could move with a bootstrap: resample the queries with replacement 10,000 times and take the range holding the middle 95% of the means.
import numpy as np
import pandas as pd
A = 'sentence-transformers/all-MiniLM-L6-v2'
B = 'intfloat/multilingual-e5-small'
results = pd.read_csv('results/per_query.csv')
rr = results.pivot(index='qid', columns='model', values='rr@10')
lang = results.drop_duplicates('qid').set_index('qid')['lang']
slices = {'all': lang.index}
slices |= {code: lang.index[lang == code] for code in ('en', 'vi')}
rng = np.random.default_rng(0)
for name, qids in slices.items():
diff = (rr[B] - rr[A]).loc[qids].to_numpy() # positive: B ranked the answer higher
wins, losses = int((diff > 0).sum()), int((diff < 0).sum())
resample = rng.integers(0, len(diff), size=(10_000, len(diff)))
low, high = np.percentile(diff[resample].mean(axis=1), [2.5, 97.5])
print(f'{name:>3} n={len(diff):>2} B-A MRR {diff.mean():+.2f} '
f'95% CI [{low:+.2f}, {high:+.2f}] B better {wins}, A better {losses}, '
f'ties {len(diff) - wins - losses}')all n=20 B-A MRR +0.09 95% CI [-0.13, +0.33] B better 5, A better 6, ties 9
en n=14 B-A MRR -0.19 95% CI [-0.33, -0.06] B better 0, A better 6, ties 8
vi n= 6 B-A MRR +0.75 95% CI [+0.42, +1.00] B better 5, A better 0, ties 1Overall, e5 is ahead by 0.09 MRR, but the interval runs from −0.13 to +0.33 and each model wins about as many queries as the other: on this set the overall comparison is a draw. The slices are not. In English, MiniLM wins six queries and loses none; in Vietnamese, e5 wins five of six, some by 20 places or more. Even with six queries, an effect that size is not noise.
Treat the bootstrap as a rough guide: with 6 or 14 queries the interval itself is unstable, and it says nothing about query types you left out. If a decision hangs on a small gap, add queries first; the interval narrows roughly with the square root of the number of queries.
This is also why a public leaderboard such as MTEB gives you a shortlist, not an answer. Its scores average many tasks and datasets whose domains, languages and text lengths may look nothing like your documents and your users' questions, and some public datasets may have been part of the models' training data. Pick candidates there, then run this lab on your own data.
08. Step 7: Write down the decision
A decision you can defend later names the evidence, the trade-off and the conditions that would change it. Save it next to the results, for example as results/decision.json:
{
"date": "2026-10-18",
"use_case": "help-centre RAG, top 3 chunks to the LLM, 1/3 of users write Vietnamese",
"query_set": "eval_data.py: 30 documents, 20 queries (14 en, 6 vi), one label each",
"results": {
"sentence-transformers/all-MiniLM-L6-v2@1110a24": {
"recall@3": {"en": 1.0, "vi": 0.33},
"mrr@10": {"en": 0.85, "vi": 0.25},
"seconds_per_1k_docs": 11.2,
"median_query_ms": 21.8
},
"intfloat/multilingual-e5-small@614241f": {
"recall@3": {"en": 1.0, "vi": 1.0},
"mrr@10": {"en": 0.65, "vi": 1.0},
"seconds_per_1k_docs": 24.8,
"median_query_ms": 51.1
}
},
"choice": "intfloat/multilingual-e5-small@614241f",
"because": "the only candidate with every answer in the top 3, in both languages",
"accepted_costs": "English recall@1 0.43 instead of 0.71; 2x the embedding time",
"noise": "overall MRR +0.09, 95% CI [-0.13, +0.33]; vi +0.75, 95% CI [+0.42, +1.00]",
"revisit_when": "at 60 labelled queries, or after testing a larger model"
}The choice follows from the product and the traffic, not from the overall average. The English recall@1 loss and the slower embedding are recorded as accepted costs, with a condition for revisiting them.
09. Troubleshooting
10. Check your understanding
11. Apply it (stretch)
Now do the practice project of this skill on your own data:
- Replace
eval_data.pywith your 500 documents and 20 labelled queries, loaded fromdocs.jsonland a queries file rather than typed in. - Set
OPENAI_EMBED_MODEL(for exampletext-embedding-3-small) and the price, runquality.py,failures.py,speed_cost.pyandpaired.pywithBset to the hosted model, and report how often each model ranks the labelled document first, with cost and latency per 1,000 documents. - Add a third candidate, such as
intfloat/multilingual-e5-base, or the hosted model withdimensions=256passed toembeddings.create, and check whether it changes the decision. - Write 20 more queries and rerun
paired.py. Did the intervals narrow as expected?
12. Review prompt
Without looking back, describe the four kinds of evidence this lab collected and the script that produced each. Explain why the per-language rows told a different story from the overall row, why a paired comparison suits two models scored on the same queries, and three facts your decision record must contain so that someone can challenge it in six months.
References
- MTEB leaderboard
- MTEB: Massive Text Embedding Benchmark (Muennighoff et al.)
- Sentence Transformers documentation
- Sentence Transformers: Semantic search
- Model card: intfloat/multilingual-e5-small
- Multilingual E5 Text Embeddings: A Technical Report
- OpenAI docs: Embeddings
- OpenAI API pricing
- NumPy: Random Generator
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.