Course contents 28 / 28

28 / 28 · Modern LLM Systems

Embeddings and semantic search

Build and evaluate a document retriever on an original fictional support corpus. A reproducible BM25 baseline exposes vocabulary mismatch; a hand-calculated vector example explains the idea of semantic retrieval.

On this page 6

A search system receives a question and returns documents that could answer it. Before adding a language model to write an answer, check this smaller task: did the search return the document containing the needed information?

We will use BIASED Retrieval Lab, a new exercise with 14 fictional support documents and 10 queries in English and Russian. The texts, queries and relevance labels were prepared for this exercise with AI assistance. They describe an invented learning workspace; its rules are not the terms or features of BIASED School.

The corpus and the relevance labels#

Every document has a stable ID. Every query lists the IDs considered relevant. For example:

IDText or task
d14Error R17 means that the output directory is read-only. Save the result in a personal folder and rerun the command.
q01R17 error output directory; relevant document: d14.
d05Download a lesson before travelling. Its text remains readable without a network connection; sending answers needs reconnection.
q08study aboard an airplane; relevant document: d05.

The first query shares distinctive words with its answer. The second expresses a need without repeating the document’s wording. Both are deliberately authored teaching cases, not a sample of real user requests.

Download the dataset, provenance and method, and rights statement. The source files contain the complete bilingual texts and labels.

A lexical baseline we can reproduce#

BM25 ranks documents by matching query terms. A term appearing in fewer documents contributes more; repeated occurrences have diminishing returns; document length adjusts the score. For a query qq and document dd, our implementation uses

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

Here NN is the number of documents, ntn_t counts documents containing term tt, ft,df_{t,d} counts occurrences in dd, and L‾\overline L is mean document length. We set k1=1.2k_1=1.2 and b=0.75b=0.75. This scoring family is described by Robertson and Zaragoza.

The script splits lowercase text into Unicode word tokens, with no stemming or stopword removal. It scores all documents, returns only positive scores, and breaks ties by document ID. These choices are part of the experiment: a zero-score document cannot appear simply because we increase the requested result count.

Measure the returned IDs#

Let rir_i be the rank of the first relevant document for query ii. If no relevant document is returned, that query contributes zero. With QQ queries,

Hit@⁡k=1Q∑i=1Q1[ri≤k],MRR⁡=1Q∑i=1Q1ri.\operatorname{Hit@}k=\frac{1}{Q}\sum_{i=1}^{Q}\mathbf{1}[r_i\leq k], \qquad \operatorname{MRR}=\frac{1}{Q}\sum_{i=1}^{Q}\frac{1}{r_i}.

In the second sum, an absent relevant result has reciprocal rank zero. Relevance is checked by exact document ID. The evaluator does not guess relevance by comparing snippets.

The saved run gives the same aggregate result in both languages:

CasesQueriesFirst relevant rank
Exact terms and the designed distractor caseq01–q06, q09, q101
Vocabulary mismatchq07, q08Not returned
AggregateAll 10Hit@1 = Hit@3 = MRR = 0.8

The English airplane query has no matching terms and returns no candidates. Its Russian counterpart returns some irrelevant documents sharing a common preposition, but still misses d05. Inspecting the failed cases tells us more than the aggregate: the relevant text receives no lexical evidence under this tokenizer.

The saved results contain query-level ranks, top-three scores, the method settings and a hash of the dataset bytes.

Why embeddings might help#

A learned encoder maps a text to a vector. Training can make related meanings nearby even when their words differ. A dual-encoder retriever computes document vectors beforehand and compares a query vector to them; Sentence-BERT and DPR describe related approaches.

For an arithmetic illustration only, choose a query vector q=(1,0)q=(1,0), an offline-reading document vector u=(0.8,0.6)u=(0.8,0.6) and an upload-limit document vector v=(0,1)v=(0,1). All three have length one, so cosine similarity equals their dot product:

cos⁡(q,u)=0.8,cos⁡(q,v)=0.\cos(q,u)=0.8,\qquad\cos(q,v)=0.

These coordinates are hand-chosen, not outputs of a model. They explain how a vector ranking could put offline reading first; they do not demonstrate that a trained model will do so. No dense retriever was run for this lesson.

A fair next experiment keeps the same document IDs and relevance labels, runs a named encoder, and compares every changed ranking against the lexical baseline. For a larger corpus, retrieve candidates first and use a more expensive joint query-document scorer only on those candidates. Neither step is a guarantee of improvement.

Run and change the experiment#

Save the script beside dataset.json, then run:

python3 retrieval-example.py --dataset dataset.json --output results.json

Python’s standard library is sufficient. No external dataset, model download or paid service is required. A self-contained notebook with the data and saved outputs runs the same experiment.

Start by changing one query while keeping its relevant ID fixed. Predict which terms will match, run the script, and inspect that query’s rank. Then add an irrelevant document that repeats a query term: a higher lexical score is not proof that a document answers the question.

Limits#

The ten queries were written together with the corpus to illustrate specific failures. This is not a held-out benchmark, and 0.8 is not an estimate of production quality. One query changes Hit@k by 0.1. The two locales have separate token matches; equal aggregate metrics do not mean identical rankings. Dense retrieval, reranking and generated answers remain unmeasured here.

To inspect the arithmetic further, review vectors and linear maps. To extend the script, use Python functions. The useful habit is to keep documents, relevance labels, ranking settings and observed results together.

References#