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:
| ID | Text or task |
|---|---|
d14 | Error R17 means that the output directory is read-only. Save the result in a personal folder and rerun the command. |
q01 | R17 error output directory; relevant document: d14. |
d05 | Download a lesson before travelling. Its text remains readable without a network connection; sending answers needs reconnection. |
q08 | study 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 and document , our implementation uses
Here is the number of documents, counts documents containing term , counts occurrences in , and is mean document length. We set and . 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 be the rank of the first relevant document for query . If no relevant document is returned, that query contributes zero. With queries,
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:
| Cases | Queries | First relevant rank |
|---|---|---|
| Exact terms and the designed distractor case | q01–q06, q09, q10 | 1 |
| Vocabulary mismatch | q07, q08 | Not returned |
| Aggregate | All 10 | Hit@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 , an offline-reading document vector and an upload-limit document vector . All three have length one, so cosine similarity equals their dot product:
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#
- S. Robertson, H. Zaragoza. The Probabilistic Relevance Framework: BM25 and Beyond. Foundations and Trends in Information Retrieval, 2009. Conceptual reference for lexical scoring; no source text or implementation is reproduced.
- N. Reimers, I. Gurevych. Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks. EMNLP-IJCNLP, 2019. Sentence embeddings compared by cosine similarity.
- V. Karpukhin et al. Dense Passage Retrieval for Open-Domain Question Answering. EMNLP, 2020. Dual-encoder retrieval.