AlgoViz

Lexical, semantic and hybrid retrieval

medium 6 min

Lexical retrieval and dense retrieval can disagree productively.

Video lesson · Chapter 1 of 4

One fault has two names

0:00 / 3:54

Theory

Read or listen first. About 2 min.

What it is

Lexical retrieval and dense retrieval can disagree productively. The former can preserve an exact error code; the latter can recover paraphrases. Fusion combines evidence from both rankings after each has searched the eligible corpus.

Why it exists

Track result identity across both lists. Measure performance separately on identifiers and paraphrases, then inspect whether fusion helps one population at the expense of the other. Rank fusion is a reasonable baseline when raw score scales differ.

Find both a fault code and its paraphrase

Term matches → Combined order (send lexical ranks). Dense neighbors → Combined order (send semantic ranks)
Term matches → Combined order (send lexical ranks). Dense neighbors → Combined order (send semantic ranks)

Inside this chapter

Chapter sources
Query Embedding
Encode a query with the representation and preprocessing expected by the index. A change in language, casing policy or model-specific prefix can shift its neighbors. Test with known query–passage pairs and inspect nearest results before changing the generator or adding more retrieved text.

The query must go through the same pipeline the encoder expects: the same model version, any query-side instruction or prefix, and the same text clean-up. Small mismatches do not raise errors; they just move the query vector a little, and neighbours shift. Keep a handful of known question and answer pairs as a smoke test and check their ranks after any change.

Example. For a model with query and passage prefixes, encode a known question both ways. Check how the rank of its answer passage changes.

A query on its way to the index
  1. 1Raw questionhow do I reset my PIN
  2. 2Same clean-up as docscasing, whitespace, codes kept
  3. 3Add query prefixquery: how do I reset my PIN
  4. 4Same encoder versionone vector, same space
  5. 5Nearest neighboursanswer passage at rank 1

Skip the prefix or change the model and the answer passage quietly slides down the list.

Similarity Search Mechanics
Similarity search scores or ranks candidates using the index metric. Some APIs return distances where smaller is closer; others return similarities where larger is better. Verify the contract with a point identical to the query and an orthogonal point before implementing a score threshold.

Different engines report different things: cosine similarity, cosine distance (one minus similarity), squared Euclidean distance or raw inner product. A threshold written for one is inverted for another. Querying with a vector already in the index tells you instantly which direction is better, and an orthogonal vector tells you what "unrelated" looks like.

Example. Search an index with one of its stored vectors. Determine whether the expected best result has the smallest distance or the largest score.

Learn the score contract before setting a threshold

Top-K Retrieval
Top-k caps how many candidates survive retrieval. A larger k may recover additional evidence but increases reranking cost and can exhaust context. Measure recall at several values and distinguish the number retrieved from the smaller number of passages ultimately sent to the generator.

There are really two k values: how many candidates the first stage retrieves, and how many passages reach the generator. Retrieving more raises recall but costs rerank time and offers more chances for distractors. Plot recall against k on a labelled set, choose the retrieval k where the curve flattens, then choose the final k from the token budget.

Example. Compare recall at k = 3 and k = 10, then count how many of the ten candidates can actually fit in the final prompt.

Recall rises with k, but the prompt is fixed

kRecall@kRerank costFit in prompt
30.603 pairs3 of 3
100.8510 pairs4 of 10
500.9550 pairs4 of 50
Illustrative numbers. Retrieve wide for recall, rerank, then send only what fits.
Result Ranking & Scoring
Scores from different retrievers can use incompatible scales. Normalize with a justified method or combine ranks, then measure relevance on labeled queries. Keep each original score and rank in traces. Otherwise a ranking regression can be impossible to attribute to the lexical or dense stage.

Lexical scores are unbounded and depend on document length and term rarity; cosines sit roughly between minus one and one and cluster differently per encoder. Adding them directly lets one scale dominate. Either normalise each list with a method you have tested (for example min-max per query) or combine ranks, and log every original score and rank so you can tell which side caused a change.

Example. One system scores a document 12 and another scores it 0.8. Inspect the ranks within each list before treating the numbers as comparable.

Raw scores are not comparable; ranks are

DocLexical scoreLexical rankCosineDense rank
P412.010.783
P96.540.841
P5absentabsent0.802
Illustrative. A BM25 score of 12 and a cosine of 0.84 live on unrelated scales.
BM25 lexical scoring
The standard lexical ranking function. A document scores higher when it contains rare query terms, contains them more often (with diminishing returns), and is not unusually long.

Three ideas are packed into the formula. IDF rewards rare terms. The fraction saturates, so the tenth occurrence of a word adds far less than the first. The length term penalises long documents that match only because they contain lots of words. BM25 knows nothing about synonyms, which is exactly why it complements dense retrieval rather than replacing it.

Example. In a support index, "E17" appears in two documents out of ten thousand, so it carries a large weight. "Card" appears in thousands and adds little.

BM25 for query terms q₁ … qₙ

score(D,Q)=∑i=1nIDF(qi)⋅f(qi,D) (k1+1)f(qi,D)+k1(1−b+b ∣D∣avgdl)\text{score}(D,Q)=\sum_{i=1}^{n}\text{IDF}(q_i)\cdot\frac{f(q_i,D)\,(k_1+1)}{f(q_i,D)+k_1\left(1-b+b\,\frac{|D|}{\text{avgdl}}\right)}
f is the term count in D, |D| the document length, avgdl the average length. k₁ controls saturation, b controls length normalisation; common defaults are around 1.2 and 0.75.

How it works

Step through the idea, or press Play.

Step 1 of 3

Term matches. P4 rank 1 · P9 rank 4

Understand it

Worked example

Find both a fault code and its paraphrase

  1. 1

    P4 rank 1 · P9 rank 4

    The rare code E17 is a strong lexical signal. This index supplies ranked IDs with its own score scale.

  2. 2

    P9 rank 1 · P4 rank 3

    “Charged twice” retrieves the useful P9 even without the error code. The dense score scale need not match the lexical scale.

  3. 3

    P4 narrowly outranks P9

    For equal weights and fusion constant 60, P4 receives 1/61 + 1/63. P9 receives 1/64 + 1/61. Keep upstream ranks to explain the difference.

Reciprocal rank fusion

RRF⁡(d)=∑j: d∈Lj1k+rj(d)\operatorname{RRF}(d)=\sum_{j:\,d\in L_j}\frac{1}{k+r_j(d)}
Ranks start at one; an absent document contributes zero for that list. With k = 60, ranks 1 and 3 yield about 0.03227. Ranks 4 and 1 yield about 0.03202.

Follow the handoffs

Track result identity across both lists. Measure performance separately on identifiers and paraphrases, then inspect whether fusion helps one population at the expense of the other. Rank fusion is a reasonable baseline when raw score scales differ.

Reciprocal rank fusion with k = 60

DocLexical rankDense rank1/(60+r) termsRRF
P4131/61 + 1/630.03227
P9411/64 + 1/610.03202
P4 wins narrowly. Neither raw score was used, only positions.

Two retrievers feed one fused list

Keep both upstream ranks in the trace so a change in the fused order can be explained.

Summary

The whole topic in one minute.

Raw scores need not have comparable meanings. Rank fusion combines ordering without assuming identical score units.

Track result identity across both lists. Measure performance separately on identifiers and paraphrases, then inspect whether fusion helps one population at the expense of the other. Rank fusion is a reasonable baseline when raw score scales differ.

Sources