4Retrieval: dense, lexical, and RRF-fused — does fusion help?
Verbs:encode_query + search(embedding_table=…) · build_lexical_index + lexical_search · search(filter=…) · rrf_fuse · assemble_context(hybrid=True) · Background: dense vs sparse retrieval, reciprocal rank fusion (Cormack, Clarke, and Büttcher 2009), the BM25 probabilistic-relevance baseline (Robertson and Zaragoza 2009) · Checked: measurement (per-method precision@10 / nDCG@10 and the honest fusion delta).
Retrieval quality is usually reported as one number per embedding table. This chapter asks the question a practitioner asks: given dense embeddings, a lexical scorer, and a graph-propagated variant, which retriever — and which fusion — should I reach for? The task is fixed (same-subject retrieval over the papers, asked by title, scored against an embedding-independent same-subject golden) and the retriever varies.
import mathimport tempfilefrom collections import defaultdictimport jammiimport numpy as npfrom jammi_cookbook import datasets, encoders, keystone, scalefrom jammi_cookbook.claims import claimSCALE = scale.current()MODEL = encoders.text(SCALE)DEPTH =100# candidates per ranked list before fusiondb = jammi.connect(f"file://{tempfile.mkdtemp()}")arxiv = datasets.arxiv(db, SCALE)raw = keystone.embed(db, arxiv, SCALE)propagated = keystone.propagate(db, arxiv, raw)golden = keystone.subject_golden(db, arxiv)relevant: dict[str, set[str]] = defaultdict(set)query_text: dict[str, str] = {}for g in db.sql(f"SELECT query_id, query_text, relevant_id FROM {golden}").to_pylist(): relevant[g["query_id"]].add(g["relevant_id"]) query_text[g["query_id"]] = g["query_text"]queries =sorted(relevant)print(f"{len(queries)} queries, each asked by its title")
2026-10-03T07:45:16.141972Z WARN jammi_kernels::admission: fused-kernel domain check failed; falling back to the eager composition op="attention_block_fused" predicate="head_dim_is_attention_block_fixed_head_dim"
200 queries, each asked by its title
4.1 Dense retrieval: one search per table
A source can carry several embedding tables — here the raw embeddings and the graph-propagated ones. search takes the query vector and, with embedding_table=, the table to search; without it, the source’s current default. The query is encoded once, by the model that produced both tables’ space (propagation keeps it).
query_vectors = {q: db.encode_query(model=MODEL, query=query_text[q]) for q in queries}def dense(table: str):def rank(q: str) ->list[str]: hits = db.search(arxiv.papers, query=query_vectors[q], k=DEPTH, embedding_table=table)return hits.column("_row_id").to_pylist()return rankdef per_query(ranked: dict[str, list[str]]) -> np.ndarray:"""Each query's precision@10 and nDCG@10 against the same-subject golden, one row per query in ``queries`` order.""" rows = []for q in queries: hits = [1.0if r in relevant[q] else0.0for r in ranked[q][:10]] ideal =sum(1/ math.log2(i +2) for i inrange(min(10, len(relevant[q])))) rows.append((sum(hits) /10, sum(h / math.log2(i +2) for i, h inenumerate(hits)) / ideal))return np.array(rows)rankers = {"dense_raw": dense(raw), "dense_prop": dense(propagated)}
4.2 Lexical BM25 — the sparse arm
BM25 (Robertson and Zaragoza 2009) is the probabilistic-relevance lexical score — term frequency saturated and length-normalized, weighted by inverse document frequency. It scores the same papers against the same relevance target, from the query’s words alone. build_lexical_index materialises the papers’ text as a lexical table — one row per paper, its title and abstract joined — and lexical_search ranks it against the query’s words, hydrating the papers the way search does, each hit carrying its bm25_score and bm25_rank.
The analyzer stems English ("raw" would not), and the query’s words are terms, not syntax: a title’s colon or quote is text.
4.3 RRF fusion — the engine’s rrf_fuse
Reciprocal rank fusion (Cormack, Clarke, and Büttcher 2009) combines ranked lists by summing 1 / (k_rrf + rank) across rankers — rank-only, so it needs no score calibration. We fuse the two dense arms, and the hybrid dense + lexical.
ranked = {name: {q: rank(q) for q in queries} for name, rank in rankers.items()}ranked["rrf_raw_prop"] = { q: [doc for doc, _ in db.rrf_fuse([ranked["dense_raw"][q], ranked["dense_prop"][q]])]for q in queries}ranked["rrf_raw_bm25"] = { q: [doc for doc, _ in db.rrf_fuse([ranked["dense_raw"][q], ranked["bm25"][q]])]for q in queries}by_query = {name: per_query(r) for name, r in ranked.items()}metrics = {name: tuple(float(m) for m in rows.mean(axis=0)) for name, rows in by_query.items()}print(f"{'method':<14}{'precision@10':>14}{'nDCG@10':>10}")for name, (p, n) in metrics.items():print(f"{name:<14}{p:>14.3f}{n:>10.3f}")
claim("propagating the embeddings over citations ranks better than the raw embeddings", metrics["dense_prop"][0] > metrics["dense_raw"][0]and metrics["dense_prop"][1] > metrics["dense_raw"][1],f"precision@10 {metrics['dense_prop'][0]:.3f} against {metrics['dense_raw'][0]:.3f}")
✓ propagating the embeddings over citations ranks better than the raw embeddings (precision@10 0.427 against 0.399)
4.4 The honest fusion finding
This is the part a benchmark table would quietly drop. A fused list “helps” only if it beats the best single arm by more than the queries’ own noise, so the comparison is paired: the same 200 queries, each scored under both lists, and the mean per-query difference set against its standard error.
single =max(("dense_raw", "dense_prop", "bm25"), key=lambda m: metrics[m][0])fused =max(("rrf_raw_prop", "rrf_raw_bm25"), key=lambda m: metrics[m][0])diff = by_query[fused] - by_query[single]gain, se = diff.mean(axis=0), diff.std(axis=0, ddof=1) / np.sqrt(len(diff))print(f"best single arm: {single} best fusion: {fused}")for i, metric inenumerate(("precision@10", "nDCG@10")):print(f"{metric:<13} fused − single: {gain[i]:+.3f} (standard error {se[i]:.3f})")
best single arm: bm25 best fusion: rrf_raw_bm25
precision@10 fused − single: -0.048 (standard error 0.014)
nDCG@10 fused − single: +0.005 (standard error 0.013)
if SCALE is scale.Scale.FULL: claim("the best fusion is the two dense arms, and the best single arm the propagated one", fused =="rrf_raw_prop"and single =="dense_prop") claim("fusion is a wash: neither metric moves by two standard errors",all(abs(g) <2* e for g, e inzip(gain, se)),f"precision@10 {gain[0]:+.3f} ± {se[0]:.3f}, nDCG@10 {gain[1]:+.3f} ± {se[1]:.3f}") claim("the hybrid dense + lexical list lands below the propagated arm", metrics["rrf_raw_bm25"][0] < metrics["dense_prop"][0])
At full scale fusion is a wash. RRF of the two dense arms lands next to the propagated arm it contains — a hair ahead on one metric, a hair behind on the other, neither by two standard errors — and the hybrid dense + lexical list lands on its raw dense arm, well below the propagated one. Rank fusion adds something only when a weaker arm reliably surfaces relevant papers the stronger one misses; on this target neither the raw dense arm nor BM25 does it often enough to show. The large lever is graph propagation (the propagation chapter), which moves precision@10 by several points, where fusion moves it by less than its noise. Measure each arm first; fuse only when the paired difference says the fused list beats the best single arm.
4.5 Filtered retrieval — ranking only the rows a predicate admits
A filter is a SQL predicate over the source’s columns, and both searches rank only the rows it admits: the predicate is evaluated once, and the index is searched within that set — each segment scores a small admitted set exactly, or walks its graph admitting only those rows when the set is large. A selective filter therefore costs work in proportion to the rows it admits, and returns the exact filtered answer however far those rows sit from the query.
The filter here is deliberately selective: the papers of the sparsest publication year. The truth for each search is computed independently — the admitted keys from SQL, the full unfiltered ranking (an exact dense search, a BM25 search over every row), and its first k admitted rows.
PAPERS =f"{arxiv.papers}.public.{arxiv.papers}"sparse = db.sql(f"SELECT year, COUNT(*) AS n FROM {PAPERS} GROUP BY year ORDER BY n, year LIMIT 1").to_pylist()[0]predicate =f"year = {sparse['year']}"admitted =set(db.sql(f"SELECT paper_id FROM {PAPERS} WHERE {predicate}").column(0).to_pylist())n_papers = db.sql(f"SELECT COUNT(*) AS n FROM {PAPERS}").column(0)[0].as_py()K =5q = queries[0]def first_admitted(ranking: list[str]) ->list[str]:return [r for r in ranking if r in admitted][:K]everything = db.search( arxiv.papers, query=query_vectors[q], k=n_papers, embedding_table=raw, exact=True).column("_row_id").to_pylist()dense_filtered = db.search( arxiv.papers, query=query_vectors[q], k=K, embedding_table=raw, filter=predicate).column("_row_id").to_pylist()lexical_all = db.lexical_search( arxiv.papers, text=query_text[q], k=n_papers, lexical_table=lexical).column("_row_id").to_pylist()lexical_filtered = db.lexical_search( arxiv.papers, text=query_text[q], k=K, lexical_table=lexical, filter=predicate).column("_row_id").to_pylist()reach =min(everything.index(r) for r in admitted) +1print(f"filter: {predicate} admits {len(admitted)} of {n_papers} papers")print(f"nearest admitted paper sits at rank {reach} of the unfiltered ranking")print(f"dense filtered top-{K}: {dense_filtered}")print(f"lexical filtered top-{K}: {lexical_filtered}")
filter: year = 2014 admits 2 of 400 papers
nearest admitted paper sits at rank 111 of the unfiltered ranking
dense filtered top-5: ['1522301498', '1583912456']
lexical filtered top-5: ['1522301498', '1583912456']
claim("the filter is selective", len(admitted) < n_papers, f"{len(admitted)} of {n_papers} papers")claim("a filtered dense search returns exactly the first admitted rows of the full ranking", dense_filtered == first_admitted(everything))claim("so does a filtered lexical search", lexical_filtered == first_admitted(lexical_all))claim("and neither returns a row the predicate refuses",set(dense_filtered) <= admitted andset(lexical_filtered) <= admitted)
✓ the filter is selective (2 of 400 papers)
✓ a filtered dense search returns exactly the first admitted rows of the full ranking
✓ so does a filtered lexical search
✓ and neither returns a row the predicate refuses
A search that ranked first and filtered after would have had to rank the reach nearest rows to find even the first admitted one; ranking within the admitted set gets the same answer without that breadth.
4.6assemble_context(hybrid=True) — a context from similarity and citations
Retrieval also feeds prediction. assemble_context retrieves a target’s context set and pools it into one vector; hybrid=True takes the union of its embedding-similarity neighbours and a declared-edge walk (here, the citations), and reports how the set was assembled.
claim("a hybrid context is assembled from both sources and holds at least k members", context["source"] =="hybrid"and context["context_size"] >=5,f"{context['context_size']} members")
✓ a hybrid context is assembled from both sources and holds at least k members (6 members)
db.close()
4.7 Bridge note
Retrieval is one primitive at three resolutions. A dense kNN, a lexical BM25 scan, and a graph-propagated kNN all rank documents by a relevance signal; RRF (Cormack, Clarke, and Büttcher 2009) is a rank-only combiner over those lists. The measured spread says the signal — dense-semantic vs lexical vs graph-propagated — is the large lever and the combiner the small one.
Cormack, Gordon V., Charles L. A. Clarke, and Stefan Büttcher. 2009. “Reciprocal Rank Fusion Outperforms Condorcet and Individual Rank Learning Methods.” In Proceedings of the 32nd International ACM SIGIR Conference on Research and Development in Information Retrieval, 758–59.
Robertson, Stephen, and Hugo Zaragoza. 2009. “The Probabilistic Relevance Framework: BM25 and Beyond.”Foundations and Trends in Information Retrieval 3 (4): 333–89.