Lexical, dense and hybrid retrieval
Implement BM25 from scratch with an inverted index, encode the corpus using a local GPU embedding model, construct an HNSW index and compare it with exact search, and combine both approaches with reciprocal rank fusion. Measure all variants with recall@k and nDCG@10 on the development set.
After this lesson you can
- Implement BM25 with an inverted index and verify it against a reference implementation.
- Encode the corpus with a local embedding model and search by cosine similarity.
- Build an HNSW index and measure recall against exact search and latency.
- Implement reciprocal rank fusion and compare the four variants.
Before you start
Finding evidence without knowing the answer
One query looks for a function with an exact name; another asks about a concept using different words from the paper. A lexical index can exploit the identifier in the first, while a dense representation can bring different expressions in the second closer. Neither intuition proves which method wins on your collection: you need independent queries and judgments and must compare the same document versions.
The previous lesson prepared ingestion and chunking and the protocol for manually reviewing and freezing a custom development set. Here we build four retrievers (BM25, exact dense, HNSW, and their fusion) and a reproducible comparison protocol. To have human judgments from the start, the lab measures everything on SciFact, a public dataset whose evidence was annotated by experts; at the end you will see which pieces change to repeat the table on your frozen set. Candidate questions you have not reviewed are useful for debugging, never as ground truth.
Search is a chain of decisions: extracted text, chunks, normalization, index, candidates, scoring, and selection. Results depend on each one. Two overlapping chunks can contain the same evidence and occupy two positions; a high similarity score is not a probability of relevance. Before studying implementation, distinguish evidence retrieval, neighbor approximation, and generated-answer quality.
BM25: from terms to probabilities and saturation
The probabilistic motivation begins with a question: how much do the relative odds of relevance change when we observe a term? Let be the presence of term in a document, the relevance event, and . Assume conditional independence of term indicators given or , and . The indicator vector’s likelihood ratio is a product; taking logarithms, the contribution dependent on is
To see this, the complete term is . Grouping the part independent of leaves the formula above. Prior relevance probability and absence contributions are constant across documents under these assumptions; ranking by the sum is equivalent to ranking by posterior odds. One more assumption is needed for the sum to visit only the query: each term appears equally in relevant and nonrelevant documents, , so its weight disappears. This is a simplified binary model, not proof that real words are independent or every rare term is relevant.
Without relevance judgments, one approximation uses document frequencies. With half-count smoothing and the simplifying assumption , , where is document count and the number containing , the weight above reduces to
It can be negative for very common terms. This explains the connection to TF-IDF rarity; sign and smoothing depend on the variant. Extensions using within-document frequency and length are additional modeling, not a mandatory algebraic consequence of binary independence. Robertson and Zaragoza develop the probabilistic framework and its extensions.
For the interactive and exercise we fix a nonnegative IDF variant and a query represented as a term list. If is the frequency of in , its length, the average length, and , define
Repeated query terms are counted repeatedly in this definition. By convention, an absent term contributes zero without evaluating the fraction: this avoids when and the document is empty. For positive frequency and fixed length, the factor increases with and approaches as grows. As length grows with everything else fixed and , the denominator increases and weight falls. With this normalization disappears; with it fully uses the length ratio. Zero length is allowed for empty documents if collection mean is positive. If the whole collection is empty, define or reject that case before division.
Normalization aims to prevent long documents winning solely because they have more opportunities to contain words, but does not make long text irrelevant. Tokenization, lowercasing, punctuation, lemmatization, and identifier handling matter as much as and . A string like load_model can be lost if index and query are normalized differently. An inverted index does not avoid concept collisions: identical words can have different meanings.
Incompatible variants share the same name. The lab uses BM25Okapi from rank_bm25: it first computes and replaces strictly negative values by epsilon times the mean of those initial vocabulary IDFs; zero values are not replaced. If the mean is negative, the replacement can also be negative. As in our formula, a query represented as a list counts repeated terms again. The lab variant and positive IDF of the interactive and exercise are not equivalent; parity is claimed only when the custom implementation and BM25Okapi explicitly share this rule. To check against a library, align formula, tokenization, parameters, average length, and tie policy; comparing numbers without aligned conventions does not demonstrate a bug. Retain hand tests and an independent reference with the same formula.
Two encoders and a geometry
Dense retrieval encodes the corpus once per version and saves each vector with its chunk identity. Every query is encoded at search time. A bi-encoder compares precomputed vectors without running the model on every query-passage pair; this efficiency has a potential cost: there is no detailed interaction between the two texts during encoding. Pair reranking comes later.
DPR uses a two-encoder framework trained for questions and passages. For the open-question datasets studied, the abstract reports a 9 to 19 percentage-point absolute improvement in top-20 passage retrieval accuracy over its Lucene-BM25. This is a specific comparison of systems and data, not a guarantee for personal notes, Spanish, or identifiers. Training, question set, segmentation, and domain may change the result.
Some models require different instructions or prefixes for queries and passages. The BGE card documents retrieval usage and distinguishes query instructions from passage text; follow the exact model and version card. Do not add the prefix to both sides for symmetry or remove it without measurement. A different version, truncation, normalization, or prefix requires rebuilding or versioning embeddings: mixing vectors generated under different contracts invalidates the comparison.
Exact nearest-neighbor search computes the query product with every normalized vector and sorts or selects the largest. It is the reference for measuring approximation, not a human relevance label. Define a deterministic tie rule and identify repeated vectors; ties at the boundary can make the result depend on that rule. Quantize or change precision only when the reference and test query record it, because it can also alter order.
HNSW: trading work for approximate neighbors
This is hierarchical navigable graph structure applied to our vectors. In Malkov and Yashunin, each node’s maximum height is randomly chosen with decreasing probability; upper layers have fewer nodes and serve broader-scale movement. When inserting a vector, neighbors are searched and connections selected per layer using a heuristic that tries to preserve diversity. Search starts at an upper-layer entry, advances to closer neighbors, and descends; at the base it explores a broader candidate set. The neighbor-selection heuristic is distinct from scale separation: the paper attributes a specific improvement on clustered data at high recall to it.
In a particular implementation, M controls the connection budget and ef_construction exploration width during construction; ef controls the candidate set during querying. Their exact meanings and limits depend on the library. The hnswlib documentation says ef must be at least the requested neighbor count. Increasing ef normally increases work and can improve recall, but does not guarantee strict improvement for every query or stable latency across machines. Changing M requires rebuilding the index: it is not merely a slider on an already built search.
In the figure’s model nodes form a grid and a fixed rule selects the upper layer. At each layer each point proposes its nearest neighbors and connections are symmetrized; degree can therefore exceed . Real HNSW construction selects heights randomly and uses a search and heuristic for links. The figure isolates navigation and search-width effects without attributing its results to that implementation. Replay the steps to observe which nodes are evaluated while descending. Initially, with and ef , search evaluates 4 of 20 nodes and stops at 12, while the exact neighbor is 17; with ef it evaluates 10 and finds it. If the graph is disconnected, increasing ef cannot reach a component inaccessible from the entry: with , each grid row is isolated at the base layer, entry 12 is in the row of nodes 10 to 14, and no ef reaches 17, which is in the row above.
If is the set of exact-search neighbors and the HNSW set, both with elements, approximate-neighbor recall is
Average per query and compare with measured latency for the same , index, threads, and ef configuration. This recall uses no relevance judgments: an ANN can exactly reproduce a dense ranking that is bad for the task. For the application use another recall over relevant documents. Measure the ef tradeoff under the intended serving configuration, with warmup and a latency distribution. Selecting enormous ef to exceed a threshold and then using another in production invalidates the conclusion.
Reciprocal rank fusion
The formula uses positions, not score magnitudes. This avoids adding a BM25 score to a cosine without common calibration, but also discards distance and confidence information. smooths differences between nearby positions: as it increases, contributions of different positions converge, and appearing in multiple lists weighs relatively more. List depths affect who can receive contributions. In Cormack, Clarke, and Büttcher’s original paper, was fixed in preliminary research; it is not a universally optimal constant. Tune that value and depth on development, never by repeatedly looking at the reserved test.
Fusion can improve when lists supply complementary evidence, but does not guarantee beating each component for every query. It can promote a mediocre document present in both lists above an excellent one present in only one; it can also propagate duplicates from overlapping chunks. Inspect ranks by question type, identify documents retrieved by only one branch, and decide whether to deduplicate by chunk or source before calculating metrics. These policies answer different questions.
Metrics and comparison design
For a query with nonempty relevant-evidence set , define retrieval recall as , where contains the first results. If multiple references are equivalent and one suffices to answer, the alternative hit metric, indicating a nonempty intersection, answers another question. Define handling of queries without evidence rather than dividing by zero. If annotations are incomplete, an unlabeled passage is not necessarily irrelevant: inspect new results and version any expanded judgments.
nDCG accounts for position and relevance grades. For binary relevance at rank ,
where is the same calculation under ideal ordering of judged documents. If , an explicit convention is needed; here we exclude those queries from mean nDCG and report them separately. Graded relevance has different gain functions, so state which you use. Compute per-query averages and break down types, question counts, ties, and queries without evidence; a single mean can hide a regression on rare identifiers.
import math
def rrf(rankings, K=60):
totals = {}
for ranking in rankings:
for r, doc in enumerate(ranking, 1):
totals[doc] = totals.get(doc, 0) + 1 / (K + r)
return [doc for doc, _ in sorted(totals.items(), key=lambda x: (-x[1], x[0]))]
def ndcg(order, relevant, k):
# IDCG usa todos los pertinentes juzgados, no solo los que aparecen en la lista.
dcg = sum(1 / math.log2(i + 2) for i, d in enumerate(order[:k]) if d in relevant)
idcg = sum(1 / math.log2(i + 2) for i in range(min(k, len(relevant))))
return dcg / idcg
lexica = ['d4', 'd1', 'd7', 'd2']
densa = ['d1', 'd9', 'd4', 'd3']
relevant = {'d1', 'd9'}
fusion = rrf([lexica, densa])
print('RRF:', fusion[:4])
for name, order in [('léxica', lexica), ('densa', densa), ('RRF', fusion)]:
print(f'nDCG@4 {name}: {ndcg(order, relevant, 4):.4f}')Document d4, first in the lexical list, falls behind d1, which has better combined ranks. Fusion does not beat the dense branch here: d9 appears only there and fusion pushes it down, precisely the risk described above.
The final table should compare BM25, exact dense, HNSW, and fusion on the same verified development questions, with recall@10 and nDCG@10. Also report ANN recall@10 against exact search, separately from relevance judgments, and per-query latency with measurement conditions. Fix a threshold for HNSW recall against exact beforehand, for example 0.98, and claim it reached only with measured results of that same configuration. A synthetic battery or unreviewed candidate questions verify code and debug the protocol; they do not replace frozen human evaluation.
Lab: build, compare, and measure
The lab implements the lexical variant and its inverted index, builds embeddings with a local model, compares HNSW against exact search, and combines ranks with RRF. It must pin seeds where randomness occurs, versions, corpus, normalization, device, and parameters. Approximate and exact search use the same normalized vectors; a comparison with different models would measure more than the index. Measure construction and queries separately. Absolute timings depend on the machine and concurrent activity: compare configurations measured in the same session and do not transfer latencies between machines.
As a human-judged benchmark we use SciFact train (Wadden et al., 2020), an external English dataset of scientific claims and paper abstracts. It does not replace your development set or establish generalization: this is the training split and parameters (, , ef, ) are fixed by looking at it. The cell downloads BEIR SciFact and original SciFact, without opening test labels. It saves results, fingerprints, and versions in a new ejecucion-* subdirectory within $ATLAS_LAB_DIR/p05-l03; if environment variable ATLAS_LAB_DIR is unset, the base folder is ~/atlas-lab.
The BEIR training file contains 919 positive pairs; intersecting them with original SciFact’s evidence field leaves 564 human-annotated pairs across 505 queries. The other 355 appear as cited documents but not in that evidence field. We consider evidence both supporting and contradicting a claim relevant. We exclude 304 queries without an evidence positive from relevance metrics and use all 809 for ANN recall, which needs no judgments. Annotation may be incomplete: an unlabeled document is not proven irrelevant.
The lab needs Python with requests, numpy, PyTorch with CUDA, sentence-transformers, rank-bm25, and faiss-cpu (pip install requests sentence-transformers rank-bm25 faiss-cpu, with CUDA PyTorch already installed). The reference run used PyTorch 2.11, transformers 5.20, sentence-transformers 5.1.2, faiss-cpu 1.15.1, and rank-bm25 0.2.2; the cell records your environment versions with results. It uses the GPU for encoding, batch 8, and CPU with one thread for search. multilingual-e5-small is downloaded from Hugging Face at a pinned revision and uses query: and passage: prefixes as its card requires. Its limit is 512 tokens: 731 of 5183 abstracts exceed it and are truncated; no query does. BM25 uses full text, so branches do not always see the same effective text and evidence may fall outside the embedding. Counting annotated evidence sentences in the truncated part is a useful lab extension. Lexical tokenization splits hyphens, so this test does not demonstrate literal identifier preservation.
For HNSW we use FAISS CPU IndexHNSWFlat, which implements Malkov and Yashunin’s algorithm with the same parameters (M, efConstruction, efSearch) and installs as a prebuilt package. hnswlib, the authors’ implementation, exposes the same controls (M, ef_construction, and set_ef), but pip may need to compile its C++ extension; on Windows that requires Visual Studio build tools. If you use it, replace the index and repeat measurement: figures below are from FAISS. Custom BM25 and rank_bm25 share parameters and variant, and their scores are compared for every query. The lab ranks every lexical document, including those with zero or negative scores, and gives the first 100 to RRF. If there are no known terms, the lexical branch contributes documents chosen by ID tie-breaking, a limitation of this policy; the educational interactive omits zero scores and uses another candidate selection.
"""Experimento reproducible sobre BEIR SciFact train, separado de p05-l02.
No abre qrels/test.tsv. Del fichero compartido queries.jsonl solo conserva IDs
presentes en qrels/train.tsv. Los juicios son de SciFact, no de p05-l02.
Dependencias: torch con CUDA, requests, numpy, sentence-transformers,
transformers, huggingface_hub, rank-bm25 y faiss-cpu. Instálalas en tu
entorno; el modelo se descarga a la caché común de Hugging Face.
Los resultados se guardan en $ATLAS_LAB_DIR/p05-l03 (por defecto ~/atlas-lab).
"""
import csv
import hashlib
import importlib.metadata
import io
import json
import os
from pathlib import Path
import platform
import re
import sys
import time
import traceback
import zipfile
import tempfile
import gc
import tarfile
from collections import Counter, defaultdict
BASE = Path(os.environ.get('ATLAS_LAB_DIR', Path.home() / 'atlas-lab')).expanduser() / 'p05-l03'
BASE.mkdir(parents=True, exist_ok=True)
HERE = Path(tempfile.mkdtemp(prefix='ejecucion-', dir=str(BASE)))
print('Directorio de esta ejecución:', HERE, flush=True)
os.environ.setdefault('TOKENIZERS_PARALLELISM', 'false')
URL = 'https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/scifact.zip'
ORIGINAL_URL = 'https://scifact.s3-us-west-2.amazonaws.com/release/latest/data.tar.gz'
MODEL = 'intfloat/multilingual-e5-small'
REVISION = '614241f622f53c4eeff9890bdc4f31cfecc418b3'
def digest(b):
return hashlib.sha256(b).hexdigest()
def tokenize(text):
return re.findall(r'\w+', text.casefold(), flags=re.UNICODE)
class InvertedBM25:
def __init__(self, documents, k1=1.5, b=0.75, epsilon=0.25):
import math
self.k1, self.b = k1, b
self.lengths = [len(doc) for doc in documents]
self.avgdl = sum(self.lengths) / len(documents)
self.postings = defaultdict(list)
for i, document in enumerate(documents):
for term, count in Counter(document).items():
self.postings[term].append((i, count))
n = len(documents)
raw = {term: math.log(n - len(posts) + 0.5) - math.log(len(posts) + 0.5)
for term, posts in self.postings.items()}
avg = sum(raw.values()) / len(raw)
self.idf = {term: value if value >= 0 else epsilon * avg for term, value in raw.items()}
def scores(self, query):
import numpy as np
scores = np.zeros(len(self.lengths), dtype=np.float64)
for term in query:
for i, count in self.postings.get(term, ()):
denom = count + self.k1 * (1 - self.b + self.b * self.lengths[i] / self.avgdl)
scores[i] += self.idf[term] * count * (self.k1 + 1) / denom
return scores
def ranked(scores, ids):
import numpy as np
return [ids[i] for i in np.lexsort((np.asarray(ids), -scores))]
def rrf(lists, depth=100, offset=60):
totals = defaultdict(float)
for ranking in lists:
for i, doc in enumerate(ranking[:depth], 1):
totals[doc] += 1 / (offset + i)
return sorted(totals, key=lambda d: (-totals[d], d))
def metrics(order, labels, k=10):
import math
relevant = {doc for doc, grade in labels.items() if grade > 0}
hits = [1 if d in relevant else 0 for d in order[:k]]
recall = sum(hits) / len(relevant)
dcg = sum(hit / math.log2(i + 2) for i, hit in enumerate(hits))
ideal = sum(1 / math.log2(i + 2) for i in range(min(k, len(relevant))))
return recall, dcg / ideal
def main():
import requests
import numpy as np
import torch
import faiss
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer
from huggingface_hub import hf_hub_download
faiss.omp_set_num_threads(1)
torch.set_num_threads(1)
if not torch.cuda.is_available():
raise RuntimeError('CUDA no disponible: no se puede verificar el laboratorio solicitado')
response = requests.get(URL, timeout=120)
response.raise_for_status()
body = response.content
data_sha = digest(body)
original = requests.get(ORIGINAL_URL, timeout=120)
original.raise_for_status()
original_sha = digest(original.content)
with tarfile.open(fileobj=io.BytesIO(original.content), mode='r:gz') as original_tar:
train_members = [x for x in original_tar.getmembers() if x.name.endswith('/claims_train.jsonl')]
if len(train_members) != 1:
raise ValueError('No se encontró el fichero de afirmaciones train original')
original_train = original_tar.extractfile(train_members[0]).read()
original_train_sha = digest(original_train)
claims = {str(x['id']): x for x in (json.loads(line) for line in original_train.splitlines())}
del original, original_train
qrels_all = defaultdict(dict)
with zipfile.ZipFile(io.BytesIO(body)) as z:
names = set(z.namelist())
def read(name):
match = [n for n in names if n.endswith('/' + name) or n == name]
if len(match) != 1:
raise ValueError('Miembro ausente o ambiguo: ' + name)
return z.read(match[0])
train_bytes = read('qrels/train.tsv')
for row in csv.DictReader(io.StringIO(train_bytes.decode('utf-8')), delimiter='\t'):
qrels_all[row['query-id']][row['corpus-id']] = int(row['score'])
if not set(qrels_all).issubset(claims):
raise ValueError('No todas las consultas BEIR figuran en SciFact train original')
qrels = defaultdict(dict)
audit = []
for qid in sorted(qrels_all):
claim = claims[qid]
for docid, score in sorted(qrels_all[qid].items()):
annotations = claim['evidence'].get(docid, [])
is_evidence = score > 0 and bool(annotations)
if is_evidence:
qrels[qid][docid] = score
audit.append({'query_id': qid, 'document_id': docid, 'beir_score': score,
'human_evidence': is_evidence,
'labels': sorted(set(x['label'] for x in annotations)),
'cited_by_source': int(docid) in claim['cited_doc_ids']})
human_original = {(qid, docid) for qid, claim in claims.items()
for docid in claim['evidence'] if qid in qrels_all}
selected = {(qid, docid) for qid, docs in qrels.items() for docid in docs}
missing_human = len(human_original - selected)
with (HERE / 'contraste-qrels-train.jsonl').open('w', encoding='utf-8', newline='\n') as f:
for item in audit:
f.write(json.dumps(item, ensure_ascii=False) + '\n')
excluded_queries = len(set(qrels_all) - set(qrels))
corpus_bytes = read('corpus.jsonl')
corpus = [json.loads(line) for line in corpus_bytes.splitlines()]
queries_bytes = read('queries.jsonl')
queries = {}
for line in queries_bytes.splitlines():
obj = json.loads(line)
if obj['_id'] in qrels_all:
queries[obj['_id']] = obj['text']
del body, corpus_bytes, queries_bytes
qids = sorted(qrels_all)
if set(qids) != set(queries):
raise ValueError('Faltan consultas train')
evaluation_ids = sorted(qrels)
without_positive = sum(not any(score > 0 for score in qrels[qid].values()) for qid in evaluation_ids)
if without_positive:
raise ValueError('Consultas sin juicios positivos: ' + str(without_positive))
corpus.sort(key=lambda x: x['_id'])
ids = [x['_id'] for x in corpus]
if any(not set(docs).issubset(ids) for docs in qrels.values()):
raise ValueError('Algún documento de qrels falta del corpus')
texts = [(d.get('title', '') + '\n' + d.get('text', '')).strip() for d in corpus]
tokens = [tokenize(text) for text in texts]
own = InvertedBM25(tokens)
reference = BM25Okapi(tokens)
lexical = {}
max_diff = 0.0
for qid in qids:
terms = tokenize(queries[qid])
scores = own.scores(terms)
max_diff = max(max_diff, float(np.max(np.abs(scores - reference.get_scores(terms)))))
lexical[qid] = ranked(scores, ids)
if max_diff > 1e-9:
raise AssertionError('BM25 no coincide con rank_bm25: ' + str(max_diff))
print('Corpus', len(ids), 'consultas ANN', len(qids), 'consultas con evidencia humana', len(evaluation_ids),
'excluidas sin positivo', excluded_queries, 'BM25 max diferencia', max_diff, flush=True)
torch.cuda.reset_peak_memory_stats()
model = SentenceTransformer(MODEL, revision=REVISION, device='cuda')
max_length = model.max_seq_length
counts = [len(model.tokenizer('passage: ' + text, truncation=False)['input_ids']) for text in texts]
query_counts = [len(model.tokenizer('query: ' + queries[qid], truncation=False)['input_ids']) for qid in qids]
print('Modelo en CUDA', 'limite', max_length, 'truncados', sum(x > max_length for x in counts), flush=True)
start = time.perf_counter()
embeddings = model.encode(['passage: ' + x for x in texts], batch_size=8, show_progress_bar=False,
normalize_embeddings=True, convert_to_numpy=True)
encode_s = time.perf_counter() - start
qembeddings = model.encode(['query: ' + queries[qid] for qid in qids], batch_size=8,
show_progress_bar=False, normalize_embeddings=True, convert_to_numpy=True)
embeddings = np.ascontiguousarray(embeddings, dtype='float32')
qembeddings = np.ascontiguousarray(qembeddings, dtype='float32')
peak = torch.cuda.max_memory_allocated()
print('Corpus codificado en', round(encode_s, 1), 's; pico de memoria', round(peak / 2**20), 'MiB', flush=True)
del model
gc.collect()
torch.cuda.empty_cache()
flat = faiss.IndexFlatIP(embeddings.shape[1])
flat.add(embeddings)
print('Índices exacto y HNSW FAISS, CPU con un hilo', flush=True)
graph = faiss.IndexHNSWFlat(embeddings.shape[1], 32, faiss.METRIC_INNER_PRODUCT)
graph.hnsw.efConstruction = 200
graph.add(embeddings)
index_sha = digest(faiss.serialize_index(graph).tobytes())
vector_sha = digest(embeddings.tobytes())
model_sha = digest(Path(hf_hub_download(MODEL, 'model.safetensors', revision=REVISION, local_files_only=True)).read_bytes())
tokenizer_sha = digest(Path(hf_hub_download(MODEL, 'tokenizer.json', revision=REVISION, local_files_only=True)).read_bytes())
depth = 100
def searches(index):
rankings = []
durations = []
index.search(qembeddings[:1], depth)
for vector in qembeddings:
start = time.perf_counter_ns()
_, neighbors = index.search(vector.reshape(1, -1), depth)
durations.append((time.perf_counter_ns() - start) / 1e6)
rankings.append([ids[i] for i in neighbors[0] if i >= 0])
return rankings, durations
exact, exact_ms = searches(flat)
distances11, _ = flat.search(qembeddings, 11)
ties_at_10 = int(np.count_nonzero(distances11[:, 9] == distances11[:, 10]))
variants = {}
for ef in (100, 128, 256):
graph.hnsw.efSearch = ef
ann, elapsed = searches(graph)
recall = float(np.mean([len(set(a[:10]) & set(e[:10])) / 10 for a, e in zip(ann, exact)]))
variants[str(ef)] = {'ann_recall_at_10': recall, 'median_ms': float(np.median(elapsed)),
'p95_ms': float(np.percentile(elapsed, 95))}
if ef == 256:
chosen = ann
print('HNSW', variants, flush=True)
rows = []
for qid, dense, ann in zip(qids, exact, chosen):
if qid not in qrels:
continue
lex = lexical[qid]
rankings = {'bm25': lex, 'dense': dense, 'hnsw': ann, 'hybrid': rrf([lex, dense])}
row = {'query_id': qid, 'judged_relevant': len([x for x in qrels[qid].values() if x > 0])}
for name, order in rankings.items():
recall, ndcg = metrics(order, qrels[qid])
row[name + '_recall10'] = recall
row[name + '_ndcg10'] = ndcg
row[name + '_first_judged_rank'] = next((i for i, d in enumerate(order, 1)
if qrels[qid].get(d, 0) > 0), None)
rows.append(row)
aggregates = {name: {metric: float(np.mean([r[name + '_' + metric] for r in rows]))
for metric in ('recall10', 'ndcg10')}
for name in ('bm25', 'dense', 'hnsw', 'hybrid')}
versions = {}
for dist in ['numpy', 'torch', 'transformers', 'sentence-transformers', 'faiss-cpu', 'rank-bm25']:
try:
versions[dist] = importlib.metadata.version(dist)
except importlib.metadata.PackageNotFoundError:
versions[dist] = 'desconocida'
summary = {'dataset': 'BEIR SciFact train', 'data_url': URL, 'archive_sha256': data_sha,
'train_qrels_sha256': digest(train_bytes), 'documents': len(ids),
'queries_ann': len(qids), 'queries_relevance': len(evaluation_ids),
'scifact_original_url': ORIGINAL_URL, 'scifact_original_archive_sha256': original_sha,
'claims_train_sha256': original_train_sha,
'beir_queries_before_filter': len(qrels_all), 'beir_qrels_before_filter': len(audit),
'human_evidence_pairs': sum(x['human_evidence'] for x in audit),
'non_evidence_pairs': sum(not x['human_evidence'] for x in audit),
'human_evidence_pairs_missing_from_beir': missing_human,
'queries_excluded_without_human_positive': excluded_queries,
'model': MODEL, 'model_revision': REVISION, 'model_license': 'MIT',
'model_safetensors_sha256': model_sha, 'tokenizer_json_sha256': tokenizer_sha,
'passage_vectors_sha256': vector_sha, 'hnsw_index_sha256': index_sha,
'device': torch.cuda.get_device_name(), 'peak_torch_bytes': peak,
'versions': versions, 'python': platform.python_version(), 'max_seq_length': max_length,
'documents_truncated': sum(x > max_length for x in counts),
'queries_truncated': sum(x > max_length for x in query_counts),
'queries_without_positive': without_positive,
'bm25_reference_max_abs_diff': max_diff, 'hnsw_implementation': 'FAISS IndexHNSWFlat CPU',
'hnsw_m': 32, 'ef_construction': 200, 'ef_chosen': 256,
'faiss_equal_score_ties_at_10': ties_at_10,
'tie_policy': 'BM25 empata por ID ascendente; FAISS devuelve su propio orden para empates de puntuación',
'bm25_tokenization': 'regex Unicode \\w+ sobre casefold; guiones separan identificadores como CVE',
'ann_variants': variants, 'exact_median_ms': float(np.median(exact_ms)),
'exact_p95_ms': float(np.percentile(exact_ms, 95)), 'aggregate': aggregates,
'rrf_offset': 60, 'rrf_depth': depth, 'corpus_encode_seconds': encode_s,
'timing_note': 'CPU con un hilo; una consulta por llamada; sin codificación; varía entre máquinas y ejecuciones',
'evaluation_note': 'Solo qrels BEIR train presentes en evidence humana original; se excluyen consultas sin positivo; no es evaluación p05-l02 ni resultado independiente.'}
(HERE / 'resultados-scifact-train.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding='utf-8')
with (HERE / 'consultas-scifact-train.jsonl').open('w', encoding='utf-8', newline='\n') as f:
for row in rows:
f.write(json.dumps(row, ensure_ascii=False) + '\n')
print(json.dumps(summary, ensure_ascii=False, indent=2), flush=True)
if __name__ == '__main__':
try:
main()
except BaseException:
(HERE / 'error-scifact.txt').write_text(traceback.format_exc(), encoding='utf-8')
raisenpm run lab and open the connection link.Here is what you should obtain. In this lesson’s reference run (an RTX 4060 Laptop for encoding and one CPU thread for search), averages over the 505 queries with evidence were as follows; three runs with the same configuration gave exactly the same quality figures. Each RRF list depth is 100 and its constant is 60; HNSW uses M=32, efConstruction=200, and efSearch=256.
| Retriever | Recall@10 | nDCG@10 |
|---|---|---|
| BM25 | 0.926733 | 0.825150 |
| Exact dense | 0.941254 | 0.840876 |
| HNSW | 0.941254 | 0.840876 |
| RRF of BM25 and exact dense | 0.944554 | 0.863801 |
The bars count queries whose first document with annotated evidence appears in the top ten: this is a hit rate, not recall of all evidence when several exist. Annotations are not necessarily exhaustive, and absence of an annotated positive from a truncated list does not prove results lack other evidence.
Across 809 queries, ANN recall@10 against exact was 0.993943 with ef=100, 0.996539 with ef=128, and 0.999876 with ef=256. Thus this particular run exceeds 0.98; it does not show the custom corpus will. There was an exact tie at the top-ten boundary and FAISS decides tie order. Maximum differences between custom and reference BM25 scores were 5.73 × 10⁻¹². The cell also reports per-query latencies with one CPU thread, excluding encoding. In those three runs, median exact-index latency ranged from 0.39 to 1.15 ms and HNSW with ef=256 from 0.54 to 0.74 ms: with 5183 vectors of 384 dimensions, exact search is already cheap and HNSW offers no speed benefit. Its advantage appears as the collection grows, because exact search cost is linear in vector count. Your times will differ; what should reproduce is quality and ANN recall. With another GPU or library version, small embedding numerical differences can move near-tied documents, so expect agreement in the first decimal places, not all of them.
To repeat the table on your frozen development set from the previous lesson, change only data loading: your chunks instead of the corpus, verified questions instead of claims, and judgments, already mapped from document to chunk as the warning explains, instead of qrels. tokenize, InvertedBM25, ranked, rrf, metrics, and index construction are reused unchanged. With Spanish questions multilingual-e5-small still applies; also check that BM25 tokenization does not break document identifiers, and add question type to each row to break down metrics, where the winning branch for each case is often visible.
Exercises
def bm25_scores(query_terms, index, k1, b):
passBM25 exploits term matches; embeddings seek proximity in a learned geometry; HNSW approximates that search and RRF combines rankings. Evaluate each stage against the appropriate reference and keep the test reserved.