bm25
A Rust crate that computes BM25 embeddings for information retrieval. You can use these embeddings in vector databases that support the storage of sparse vectors, e.g. Qdrant, Pinecone, Milvus, etc.
This crate also contains a light-weight, in-memory full-text search engine built on top of the embedder.
Features
- Fast
- Multilingual
- Language detection
- Stop word removal
- Parallelism for fast batch-embedding
- Customisable embedding space
- Full access to BM25 parameters
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) word 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 if most of your documents are around the same size.
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 word 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
Embed
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, this crate tokenizes text in English. If you are working with a different language, you can set the embedder language mode.
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 embedder 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 built-in tokenizer detects language, splits on whitespace and punctuation, removes stop words and stems the remaining words.
Stop words
By default, this crate removes stop words according to the NLTK stop words list for the given/detected language before embedding. This removes noise from insignificant words. If you do not want to remove stop words, disable default features.
If you would rather use the Stopwords ISO stop words collection:
Stop word lists are provided by the stop-words crate. For more information, see the documentation therein.
Custom tokenizer
While the built-in tokenizer works well for most languages and use-cases, you can still tokenize text yourself and use this crate only for embedding.
use ;
let tokens = ;
let embedder: Embedder = with_avgdl
.build;
let embedding = embedder.embed_tokens;
assert_eq!
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 EmbeddingDimension 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 usize-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!;
Search
This crate includes a light-weight, in-memory full-text search engine built on top of the embedder.
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 and generating embeddings can be slow. Fortunately,
these tasks can both be trivially parallelised via the parallelism feature, which implements
data parallelism using Rayon.