bm25
A Rust crate for everything BM25. This crate provides utilities at three levels of abstraction:
- BM25 Embedder: Embeds text into a sparse vector space for information retrieval. You can use these embeddings with vector databases, e.g., Qdrant, Pinecone and Milvus, etc.
- BM25 Scorer: Efficiently scores the relevance of a query embedding to document embeddings.
- BM25 Search Engine: A fast, light-weight, in-memory keyword search engine built on top of the embedder and scorer.
See bm25-demo for a WebAssembly demo of the search engine.
Features
- Multilingual tokenizer with stemming, stop word removal and unicode normalization
- Language detection
- Full access to BM25 parameters
- Parallelism for fast batch-fitting
- Modular and customisable
- Configurable via compile-time features
The BM25 algorithm
BM25 is an algorithm for scoring the relevance of a query to documents in a corpus. You can make this scoring more efficient by pre-computing a 'sparse embedding' of each document. You can use these sparse embeddings directly, or upload them to a vector database and query them from there.
BM25 assumes that you know the average (meaningful) token count of your documents ahead of time. This crate provides utilities to compute this. If this assumption doesn't hold for your use-case, you have two options: (1) make a sensible guess (e.g. based on a sample); or (2) configure the algorithm to disregard document length. The former is recommended.
BM25 has three parameters: b, k1 and avgdl. These terms match the formula given on
Wikipedia. avgdl ('average document length') is the aforementioned average meaningful token count;
you should always provide a value for this and the crate can fit this for you. b controls
document length normalization; 0 means no normalisation (length will not affect score) while 1
means full normalisation. If you know avgdl, 0.75 is typically a good choice for b. If
you're guessing avgdl, you can use a slightly lower b to reduce the effect of document length
on score. If you have no idea what avgdl is, set b to 0. k1 controls how much weight is
given to recurring tokens. For almost all use-cases, a value of 1.2 is suitable.
Getting started
Add bm25 to your project with
Depending on your use-case, you may want to read more about the Embedder, Scorer or SearchEngine.
Embed
You can generate sparse embeddings from text using this crate. You can store and query these in most vector databases, or use them directly. The best way to embed some text is to fit an embedder to your corpus.
use ;
let corpus = ;
let embedder: Embedder = with_fit_to_corpus.build;
assert_eq!;
let embedding = embedder.embed;
assert_eq!
BM25 parameters
For cases where you don't have the full corpus ahead of time, but have an approximate idea of the
average meaningful word count you expect, you can construct an embedder with your avgdl guess.
use ;
let embedder: Embedder = with_avgdl
.build;
If you want to disregard document length altogether, set b to 0.
use ;
let embedder: Embedder = with_avgdl
.b // if b = 0, avgdl has no effect
.build;
Language
By default, the embedder uses an English DefaultTokenizer. If you are working with a different
language, you can configure the embedder to tokenize accordingly.
use ;
let embedder: Embedder = with_avgdl
.language_mode
.build;
If your corpus is multilingual, or you don't know the language ahead of time, you can enable the
language_detection feature.
This unlocks the LanguageMode::Detect enum value. In this mode, the tokenizer will try to detect
the language of each piece of input text before tokenizing. Note that there is a small performance
overhead when embedding in this mode.
use ;
let embedder: Embedder = with_avgdl
.language_mode
.build;
Tokenizer
The embedder uses a tokenizer to convert text into a sequence of tokens to embed. The default tokenizer detects language, normalizes unicode, splits on unicode word boundaries, removes stop words and stems the remaining words. You can customise its behaviour by using the builder.
use ;
let tokenizer = builder
.language_mode
.normalization // Normalize unicode (e.g., 'é' -> 'e', '🍕' -> 'pizza', etc.)
.stopwords // Remove common words with little meaning (e.g., 'the', 'and', 'of', etc.)
.stemming // Reduce words to their root form (e.g., 'running' -> 'run')
.build;
let text = "Slices of 🍕";
let tokens = tokenizer.tokenize;
// 'slices' is stemmed to 'slice', 'of' is a stopword, and '🍕' is normalized to 'pizza'
assert_eq!;
While this works well for most languages and use-cases, this crate makes it easy for you to provide
your own tokenizer. All you have to do is implement the Tokenizer trait.
use ;
;
// Tokenize on occurrences of "T"
let embedder = with_avgdl.build;
let embedding = embedder.embed;
assert_eq!;
If you're not using the DefaultTokenizer at all, you can disable the default_tokenizer feature
to remove some dependencies from your project.
Embedding space
You can customise the dimensionality of your sparse vector via the generic parameter. Supported
values are usize, u32 and u64. You can also use your own type (and inject your own embedding
function) by implementing the TokenEmbedder trait.
use ;
let text = "cup of tea";
// Embed into a u32-dimensional space
let embedder = with_avgdl.build;
let embedding = embedder.embed;
assert_eq!;
// Embed into a u64-dimensional space
let embedder = with_avgdl.build;
let embedding = embedder.embed;
assert_eq!;
;
// Embed into a MyType-dimensional space
let embedder = with_avgdl.build;
let embedding = embedder.embed;
assert_eq!;
Score
This crate provides a BM25 scorer that can efficiently score the relevance of a query embedding to document embeddings. The scorer manages the complexity of maintaining token frequencies and indexes, as well as the actual scoring. Use this if you need BM25 scoring, but want to manage the lifecycle of raw documents yourself.
use ;
let corpus = ;
let query = "pink";
let mut scorer = new;
let embedder: Embedder =
with_fit_to_corpus.build;
for in corpus.iter.enumerate
let query_embedding = embedder.embed;
let score = scorer.score;
assert_eq!;
let matches = scorer.matches;
assert_eq!;
Search
This crate includes a light-weight, in-memory keyword search engine built on top of the embedder and scorer. See bm25-demo for a WebAssembly demo.
use ;
let corpus = ;
let search_engine = with_corpus.build;
let limit = 3;
let search_results = search_engine.search;
assert_eq!;
You can construct a search engine with documents (allowing you to customise the id type and value), or with an average document length.
use ;
// Build a search engine from documents
let search_engine = with_documents
.build;
// Build a search engine from avgdl
let search_engine = with_avgdl
.build;
You can upsert or remove documents from the search engine. Note that mutating the search corpus
by upserting or removing documents will change the true value of avgdl. The more avgdl drifts
from its true value, the less accurate the BM25 scores will be.
use ;
let mut search_engine = with_avgdl
.build;
let document_id = 42;
let document = Document ;
search_engine.upsert;
assert_eq!;
search_engine.remove;
assert_eq!;
Working with a large corpus
If your corpus is large, fitting an embedder can be slow. Fortunately, you can trivially
parallelise this via the parallelism feature, which implements data parallelism using
Rayon.