Module contents
Stage 3 of 9Advanced 110 min

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.

InteractiveLexical, dense, and fusion

Question: What does the key state store?

BM25

No positive scores.

Feature cosine
1. A (reference)1.000
RRF
1. A (reference)0.0164
lexical 0.0000 + vector 0.0164
  • BM25
  • Handcrafted feature cosine
  • Rank fusion
View corpus and model vocabulary

A. The KV cache stores the keys and values calculated for each token.
La caché KV conserva claves y valores calculados para cada token.

B. Prefill processes the prompt before producing the first token.
Prefill procesa el prompt antes de emitir el primer token.

C. CVE-2099-0002 is a different vulnerability that requires another patch.
CVE-2099-0002 es una vulnerabilidad diferente; requiere otro parche.

D. The patch fixes CVE-2099-0001 on the local server.
El parche corrige CVE-2099-0001 en el servidor local.

E. The initial delay includes processing the input before the first response.
La demora inicial incluye procesar la entrada antes de la primera respuesta.

F. An API key authenticates requests and authorizes access.
Una clave API autentica peticiones y autoriza el acceso.

KV state: cache, kv, conserva, claves, valores, almacenamiento, memoria, guardar.

input and first response: prefill, demora, latencia, primer, primera, respuesta, entrada, prompt.

vulnerability: cve-2099-0001, cve-2099-0002, parche, vulnerabilidad, vulnerable, corrige.

access: api, clave, autentica, acceso.

This instructional example uses a chosen reference for each question and preserves the original Spanish inputs for scoring. CVE-2099-0001 and CVE-2099-0002 are fictional. BM25 uses k1 = 1.2 and b = 0.75 with IDF log(1 + (N − df + 0.5)/(df + 0.5)). The four vector components count words in the displayed vocabulary, so the cosine uses handcrafted features. Both rankings omit zero scores and break ties by document letter.

RRF adds 1/(K + rank) from each list containing the document, with ranks starting at 1. The fusion considers only the selected candidates. Bar lengths use the scale of their own ranking.

Question type
2
60
Query used (Spanish corpus)almacenamiento memoria
Labeled referenceA
BM25 rankoutside candidates
Vector rank1
RRF rank1
This demonstration uses explicit educational documents and judgments. Semantic features are constructed by hand; these are not trained embeddings or development-set results. Change the query and compare ranks and fusion contributions.

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 Xt∈{0,1}X_t\in\{0,1\} be the presence of term tt in a document, RR the relevance event, pt=P(Xt=1∣R)p_t=\Pr(X_t=1\mid R) and ut=P(Xt=1∣¬R)u_t=\Pr(X_t=1\mid \neg R). Assume conditional independence of term indicators given RR or ¬R\neg R, and 0<pt,ut<10<p_t,u_t<1. The indicator vector’s likelihood ratio is a product; taking logarithms, the contribution dependent on XtX_t is

Xtlog⁡pt(1−ut)ut(1−pt).X_t\log\frac{p_t(1-u_t)}{u_t(1-p_t)}.

To see this, the complete term is Xtlog⁡(pt/ut)+(1−Xt)log⁡((1−pt)/(1−ut))X_t\log(p_t/u_t)+(1-X_t)\log((1-p_t)/(1-u_t)). Grouping the part independent of XtX_t 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 t∉qt\notin q appears equally in relevant and nonrelevant documents, pt=utp_t=u_t, so its weight log⁡1=0\log 1=0 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 pt=0.5p_t=0.5, ut=(nt+0.5)/(N+1)u_t=(n_t+0.5)/(N+1), where NN is document count and ntn_t the number containing tt, the weight above reduces to

log⁡N−nt+0.5nt+0.5.\log\frac{N-n_t+0.5}{n_t+0.5}.

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 ftdf_{td} is the frequency of tt in dd, ∣d∣|d| its length, L‾\overline{L} the average length, k1>0k_1>0 and 0≤b≤10\le b\le1, define

BM25⁡(q,d)=∑t∈qlog⁡(1+N−nt+0.5nt+0.5)ftd(k1+1)ftd+k1(1−b+b∣d∣/L‾).\operatorname{BM25}(q,d)=\sum_{t\in q} \log\left(1+\frac{N-n_t+0.5}{n_t+0.5}\right) \frac{f_{td}(k_1+1)}{f_{td}+k_1(1-b+b|d|/\overline{L})}.

Repeated query terms are counted repeatedly in this definition. By convention, an absent term contributes zero without evaluating the fraction: this avoids 0/00/0 when b=1b=1 and the document is empty. For positive frequency and fixed length, the factor increases with ftdf_{td} and approaches k1+1k_1+1 as ftdf_{td} grows. As length grows with everything else fixed and b>0b>0, the denominator increases and weight falls. With b=0b=0 this normalization disappears; with b=1b=1 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 k1k_1 and bb. 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 log⁡((N−nt+0.5)/(nt+0.5))\log((N-n_t+0.5)/(n_t+0.5)) 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.

InteractiveDescending a navigable graph

Reproducible teaching model: 20 points in a 5 by 4 grid; indices divisible by 4 form the upper layer. In each layer, each node proposes its M nearest Euclidean neighbors and edges become bidirectional. This is not a library HNSW construction: M does not limit degree after symmetrization here, and heights are not random.

012345678910111213141516171819
  • Evaluated node in visible layer
  • Upper path and explored node ring
  • Exact neighbor at base
  • Query
Base layer · 6/6

In the upper layer search advances greedily from node 0, breaking ties by index. At the base it starts at the final upper node and explores nearby candidates, retaining up to ef best. “Evaluated” counts distinct nodes whose distances were calculated, including unexpanded ones, not total calculations; compare this with the 20 nodes in exhaustive search. The dashed green circle marks the exact neighbor; the approximate value comes from retained candidates.

2
2
0.55
0.90
Base entrynode 12
Nodes evaluated in visible layer4
Node explored at this stepnode 13
Approximate neighbor at finishnode 12
Exact neighbornode 17
Do they match?No
Replay the search and change the query, M, and ef. This educational graph is generated by an explicit deterministic rule; it is not a real HNSW index or a performance measurement. The exact neighbor is obtained by examining every point.

In the figure’s model nodes form a grid and a fixed rule selects the upper layer. At each layer each point proposes its MM nearest neighbors and connections are symmetrized; degree can therefore exceed MM. 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 M=2M=2 and ef =2=2, search evaluates 4 of 20 nodes and stops at 12, while the exact neighbor is 17; with ef =4=4 it evaluates 10 and finds it. If the graph is disconnected, increasing ef cannot reach a component inaccessible from the entry: with M=1M=1, 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 Ek(q)E_k(q) is the set of kk exact-search neighbors and Ak(q)A_k(q) the HNSW set, both with kk elements, approximate-neighbor recall is

ANNRecall@⁡k(q)=∣Ak(q)∩Ek(q)∣k.\operatorname{ANNRecall@}k(q)=\frac{|A_k(q)\cap E_k(q)|}{k}.

Average per query and compare with measured latency for the same kk, 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. KK 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, K=60K=60 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 GqG_q, define retrieval recall as ∣Gq∩Lk∣/∣Gq∣|G_q\cap L_k|/|G_q|, where LkL_k contains the first kk 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 reli∈{0,1}rel_i\in\{0,1\} at rank ii,

DCG@k=∑i=1krelilog⁡2(i+1),nDCG@k=DCG@kIDCG@k,DCG@k=\sum_{i=1}^{k}\frac{rel_i}{\log_2(i+1)},\qquad nDCG@k=\frac{DCG@k}{IDCG@k},

where IDCG@kIDCG@k is the same calculation under ideal ordering of judged documents. If IDCG=0IDCG=0, 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.

[ ]RRF and nDCG on two small listsBrowser
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 (k1k_1, bb, ef, KK) 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.

[ ]BM25, embeddings, HNSW, and RRF on SciFact trainLocal GPU
"""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')
        raise
This cell needs the local lab (PyTorch with your GPU). Start it with npm 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.

RetrieverRecall@10nDCG@10
BM250.9267330.825150
Exact dense0.9412540.840876
HNSW0.9412540.840876
RRF of BM25 and exact dense0.9445540.863801
InteractiveExplore evaluated claims

External SciFact training split with the original human judgments matched to BEIR. The ranks come from the lab's reference run on this split.

Claim 1000: text appears after loading the verified original file

358 of 505
BM25rank 3
Exact denserank 1
RRFrank 2
  • BM25
  • Exact dense
  • RRF
First annotated positive in the top 10 among matching claims
BM25472/505 (93.5 %)
Exact dense480/505 (95.0 %)
RRF481/505 (95.2 %)

Load claims_train.jsonl to read the claims.

Download the official SciFact archive, extract claims_train.jsonl, and select it above. The browser reads the training claims and keeps them locally. The expected hash is f4c8fa82d8bd0653a9cc8d61a6ea48c25eacea64e90af5dbf390ebb1b74372f0. Claims and annotations from Wadden et al., SciFact, CC BY 4.0.

BM25 ranks all 5183 documents. Dense retrieval returns its top 100. RRF combines the top 100 from each method with K = 60. Other relevant evidence may still appear when there is no annotated positive. The first positive's rank describes the first hit only.

BM25 and RRF break ties by ascending lexicographic ID. Dense retrieval uses the order returned by FAISS. Among the 809 ANN queries, one had a score tie at the top-10 cutoff.

Rank provenance

The 505 records come from consultas-scifact-train.jsonl in the lesson run, SHA-256 641b41808bf5afe9a0e2978760e75a7c60d958ecf28f3e840a762fbe97be8ed5. Summary SHA-256 2a1a39b52e804bf9c5758470af167257dca066debf2bb4bb131c1dc5c739b98a. Original SciFact archive SHA-256 11c621288d41ac144d29b13b0f8503b3820b7d6e8b1f6ff24dff335c196d76be. BEIR SciFact archive SHA-256 536e14446a0ba56ed1398ab1055f39fe852686ecad24a6306c80c490fa8e0165. Training qrels SHA-256 a53f2114831916c096b6c37d9e54da68cef4efdcdbd5ed46533601af972acf1d.

Documents with annotated evidence
Claims matching the filter505 of 505
Documents with evidence1
First annotated positive: BM25rank 3
First annotated positive: Exact denserank 1
First annotated positive: RRFrank 2
Ranks from the recorded run on external SciFact train. Filter by number of documents with evidence and compare where the first appears in each list. To view each claim's text, load the official file identified in the figure; its fingerprint is checked in the browser.

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

NumericTwo lists
A document occupies ranks 3 and 7 in two lists. With K = 60 and this lesson's RRF definition, what is its score?
NumericThe order of evidence
There are exactly three relevant documents. A five-item ranking has binary relevance [1, 0, 1, 0, 1]. Calculate nDCG@5 with discount 1 / log₂(i + 1) and binary gain.
NumericOne term by hand
A collection has N = 1000 documents and term t appears in n_t = 10. In a document of length 150, with average length 100, t appears 3 times. With k1 = 1.2, b = 0.75, and this lesson's positive-IDF BM25 formula (natural logarithm), how much does t contribute to the score?
QuizOne list versus two
Document A ranks 1 in BM25 and is absent from the dense top 100. Document B ranks 2 in both lists. With RRF and constant K > 0, what happens?
QuizWhere is the bottleneck?
Your HNSW index achieves ANN recall@10 of 0.9999 against exact search, but dense-ranking relevance recall@10 is 0.80. Which conclusion is correct?
QuizA query with an identifier
A query contains a rare function identifier that must appear literally. Which design is the most defensible starting point?
CodeSumming inverted lists
Implement bm25_scores(query_terms, index, k1, b). index contains N, avgdl, lengths (a list of lengths), and postings: a dictionary mapping terms to lists of pairs (zero-based integer ID, positive frequency). Use the lesson’s positive-IDF formula; the term’s document count is the length of its list. Return a list of N scores. The query may repeat terms; count them repeatedly. Assume N > 0, avgdl > 0, k1 > 0, 0 ≤ b ≤ 1, and postings without repeated documents.
def bm25_scores(query_terms, index, k1, b):
  pass
Shift+Enter to run
Key idea

BM25 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.