Ranking Documents with BM25

File: BM25.lean

BM25 scores how well a document matches a query. Search engines have used it for decades. A document scores higher when it contains a query term many times, when that term is rare in the other documents, and when the document is short.

For a query Code Test and a document Code Test, with Code Test the count of term Code Test in Code Test:

math
math

Code Test is the number of documents, Code Test is the number that contain Code Test, Code Test is the length of Code Test in words, and Code Test is the mean document length.

The Code

 1 -- lean --run BM25.lean   (Okapi BM25 document ranking)
 2 
 3 -- Lowercased runs of letters and digits. The fold carries the
 4 -- finished words and the characters of the word in progress,
 5 -- both in reverse order.
 6 def tokenize (text : String) : List String :=
 7   let init : List String × List Char := ([], [])
 8   let (words, acc) := text.toList.foldl (init := init)
 9     fun (words, acc) ch =>
10       if ch.isAlphanum then (words, ch.toLower :: acc)
11       else if acc.isEmpty then (words, acc)
12       else (String.ofList acc.reverse :: words, [])
13   let words :=
14     if acc.isEmpty then words else String.ofList acc.reverse :: words
15   words.reverse
16 
17 def fixed (x : Float) (d : Nat := 3) : String :=
18   let n := (x.abs * (10 ^ d).toFloat).round.toUInt64.toNat
19   let frac := toString (n % 10 ^ d)
20   let pad := "".pushn '0' (d - frac.length)
21   s!"{if x < 0 then "-" else ""}{n / 10 ^ d}.{pad}{frac}"
22 
23 -- Returns (score, document) pairs, best first.
24 def bm25Search (corpus : List String) (query : String)
25     (k1 : Float := 1.5) (b : Float := 0.75) : List (Float × String) :=
26   let docs := corpus.map tokenize
27   let n := corpus.length
28   let avgdl := (docs.map List.length).sum.toFloat / (max 1 n).toFloat
29   let qTerms := (tokenize query).eraseDups
30   let idf (term : String) : Float :=
31     let df := (docs.countP (·.contains term)).toFloat
32     Float.log (1.0 + (n.toFloat - df + 0.5) / (df + 0.5))
33   let scored := (docs.zip corpus).map fun (doc, raw) =>
34     let len := doc.length.toFloat
35     let score := qTerms.foldl (init := 0.0) fun acc term =>
36       let tf := (doc.count term).toFloat
37       if tf > 0 then
38         let norm := k1 * (1.0 - b + b * len / avgdl)
39         acc + idf term * (tf * (k1 + 1.0)) / (tf + norm)
40       else acc
41     (score, raw)
42   (scored.filter (·.1 > 0.0)).mergeSort (fun a b => a.1 ≥ b.1)
43 
44 def corpus : List String := [
45   "Common Lisp is a general-purpose programming language " ++
46   "with powerful macros.",
47   "Python is an interpreted language known for data science " ++
48   "and machine learning.",
49   "Deep learning models require automatic differentiation " ++
50   "and gradient optimization.",
51   "Macros in Common Lisp enable syntactic metaprogramming " ++
52   "and DSL design.",
53   "Okapi BM25 is an information retrieval ranking function " ++
54   "used in search engines."]
55 
56 def main : IO Unit := do
57   IO.println s!"Corpus size: {corpus.length} documents"
58   for query in ["Common Lisp macros", "search ranking", "learning"] do
59     IO.println s!"\nQuery: \"{query}\""
60     for (score, doc) in bm25Search corpus query do
61       IO.println s!"  [score: {fixed score}] {doc}"

How It Works

  • tokenize turns text into a list of lowercase words. It uses foldl with a pair as its state: the finished words and the letters of the current word. Both lists grow at the front, so the code reverses them at the end.
  • bm25Search has two parameters with default values, k1 and b. Callers can set them by name: bm25Search corpus query (b := 0.5).
  • idf is a local function. It uses docs and n from the lines above it.
  • docs.countP (·.contains term) counts the documents that contain the term. doc.count term counts how often the term appears in one document. eraseDups removes repeated query terms.
  • Nat and Float do not mix. The code converts each count with .toFloat before it divides.
  • mergeSort takes a function that says when a may come before b. fun a b => a.1 ≥ b.1 sorts by score, highest first.

tokenize keeps letters and digits only. It drops apostrophes, splits hyphenated words such as general-purpose into two tokens, and does no stemming, so learning and learn are different terms. Those choices are fine for a demo but change rankings on real text. Add a stop-word filter and a simple suffix rule as an exercise, then compare the output.

Checking a Score

Take the query “Common Lisp macros” and the document “Macros in Common Lisp enable syntactic metaprogramming and DSL design.” The document has 10 tokens and the corpus mean is 10.8. Each query term appears once in the document and in two of the five documents, so df is 2 and idf is ln(1 + 3.5/2.5) = 0.8755. The length factor is 1.5 * (1 - 0.75 + 0.75 * 10/10.8) = 1.4167. Each term adds 0.8755 * 2.5 / (1 + 1.4167) = 0.9057, and three terms give 2.717.

b Common Lisp document Macros document
0 2.626 2.626
0.75 2.605 2.717
1 2.598 2.749

At b = 0 the length term disappears and the two documents tie, since each contains the three terms once. At b = 1 the shorter document gains most. k1 controls saturation: with k1 = 1.5, a term that appears ten times scores less than ten times as much as a term that appears once. Try this: run the first query with b := 1.0 and k1 := 0.5.

Lean 4 Notes

let and local functions. bm25Search is one expression made of a series of let lines. Each let names a value that the later lines can use. let idf (term : String) : Float := ... defines a local function with the same syntax as def. A local function can use every name defined above it, so idf reads docs and n without taking them as parameters.

Type ascriptions. In tokenize, the line let init : List String × List Char := ([], []) gives a type to the start value. [] alone could be a list of any type, and Lean needs to know which before it checks the fold.

Named arguments. foldl takes a function, a start value, and a list. text.toList.foldl (init := init) fun ... => ... passes the start value by name. That leaves the function as the last argument, where it can span several lines with no closing parenthesis.

if is an expression. An if returns a value, so both branches must have the same type. In tokenize the three branches each return a pair. There is no if without else outside a do block.

Strings and characters. A String is UTF-8 text. toList gives its characters as a List Char, and String.ofList builds a string from such a list. Char has test and conversion functions such as isAlphanum and toLower. A character literal uses single quotes and a string literal uses double quotes.

No mixed arithmetic. n is a Nat and df is a Float, so n - df does not compile. The code writes n.toFloat - df. In (max 1 n).toFloat the max runs on Nat values first, and the result becomes a Float.

Sorting. mergeSort belongs to List and keeps the order of elements that compare as equal. Its argument returns a Bool. a.1 ≥ b.1 is a statement about two floats, and Lean turns it into a Bool by computing it.

for in IO. The two nested for loops in main run IO actions for each element. for (score, doc) in ... takes each pair apart.

Running It

 1 $ lean --run BM25.lean
 2 Corpus size: 5 documents
 3 
 4 Query: "Common Lisp macros"
 5   [score: 2.717] Macros in Common Lisp enable syntactic metaprogramming and DSL design.
 6   [score: 2.605] Common Lisp is a general-purpose programming language with powerful macros.
 7 
 8 Query: "search ranking"
 9   [score: 2.641] Okapi BM25 is an information retrieval ranking function used in search engines.
10 
11 Query: "learning"
12   [score: 0.946] Deep learning models require automatic differentiation and gradient optimization.
13   [score: 0.834] Python is an interpreted language known for data science and machine learning.

For the first query both documents contain all three terms. The shorter document ranks first.

Using It

Replace corpus with your own documents. To read them from files, change main to call IO.FS.readFile for each path. bm25Search tokenizes the corpus on every call. For many queries against one corpus, split it into a function that builds the token lists once and a function that scores a query against them. Five documents make the IDF values small and close; with a real corpus the gap between rare and common terms widens.