bm25-mojo 0.2.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bm25_mojo/__init__.py ADDED
@@ -0,0 +1,28 @@
1
+ """bm25-mojo: a drop-in faster replacement for the `rank_bm25` package.
2
+
3
+ Same classes, same call shapes, same scores — powered by a Mojo kernel where
4
+ the platform supports it (macOS arm64, Linux x86_64), with a vendored
5
+ pure-Python fallback everywhere else (including Windows).
6
+
7
+ from bm25_mojo import BM25Okapi
8
+
9
+ bm25 = BM25Okapi(tokenized_corpus) # same as rank_bm25.BM25Okapi
10
+ scores = bm25.get_scores(tokenized_query) # np.ndarray of float64
11
+ top = bm25.get_top_n(tokenized_query, documents, n=5)
12
+
13
+ Set BM25_MOJO_DISABLE_NATIVE=1 to force the pure-Python fallback.
14
+ """
15
+
16
+ from bm25_mojo._native import backend_info, native_available
17
+ from bm25_mojo.core import BM25, BM25L, BM25Okapi, BM25Plus
18
+
19
+ __version__ = "0.2.5" # x-release-please-version
20
+ __all__ = [
21
+ "BM25",
22
+ "BM25Okapi",
23
+ "BM25L",
24
+ "BM25Plus",
25
+ "backend_info",
26
+ "native_available",
27
+ "__version__",
28
+ ]
bm25_mojo/_native.py ADDED
@@ -0,0 +1,602 @@
1
+ """ctypes loader for the bm25mojo native kernel, with an ABI-version handshake.
2
+
3
+ Resolution order:
4
+
5
+ 1. ``$BM25_MOJO_NATIVE_LIB`` (explicit path override, for development)
6
+ 2. the shared library bundled in this wheel under ``bm25_mojo/_native/``
7
+ 3. the repository development build output ``kernels/bm25/build/``
8
+
9
+ If the library cannot be found, fails to load, or reports an ABI version this
10
+ package does not understand, :class:`NativeUnavailable` is raised and the
11
+ caller falls back to the vendored pure-Python reference implementation.
12
+ Set ``BM25_MOJO_DISABLE_NATIVE=1`` to force that fallback (used by the
13
+ differential test suite).
14
+
15
+ Stable C ABI::
16
+
17
+ int32_t bm25mojo_abi_version(void) -> 4
18
+ void* bm25mojo_build_index_corpus(...)
19
+ void bm25mojo_build_result_free(result)
20
+ void* bm25mojo_index_create(...)
21
+ int32_t bm25mojo_vocab_attach(handle, ...)
22
+ int32_t bm25mojo_score(handle, ...)
23
+ int32_t bm25mojo_score_batch(handle, ...)
24
+ int32_t bm25mojo_score_batch_str(handle, ...)
25
+ void bm25mojo_index_destroy(handle)
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import ctypes
31
+ import os
32
+ import sys
33
+ import threading
34
+
35
+ import numpy as np
36
+
37
+ # Must equal ABI_VERSION in kernels/bm25/src/bm25mojo.mojo. A mismatch means
38
+ # the installed wheel and the resolved shared library disagree; fall back.
39
+ ABI_VERSION = 4
40
+ # Older libraries back to ABI v3 are still usable for scoring and for the
41
+ # Python-side build path, so the handshake accepts [ABI_VERSION_MIN, ABI_VERSION].
42
+ ABI_VERSION_MIN = 3
43
+
44
+ # Score-formula variants, mirrored from the kernel.
45
+ VARIANT_OKAPI = 0
46
+ VARIANT_L = 1
47
+ VARIANT_PLUS = 2
48
+
49
+ _ENV_LIB = "BM25_MOJO_NATIVE_LIB"
50
+ _ENV_DISABLE = "BM25_MOJO_DISABLE_NATIVE"
51
+
52
+ # Widest fixed-width token slot the kernel accepts (MAX_TOKEN_WIDTH there).
53
+ MAX_TOKEN_WIDTH = 4096
54
+
55
+
56
+ class NativeUnavailable(RuntimeError): # noqa: N818
57
+ """The native bm25mojo kernel could not be found, loaded, or verified."""
58
+
59
+
60
+ class UnsafeTokenError(ValueError):
61
+ """A token the native string path cannot take (non-`str`, embedded NUL,
62
+ or over-wide slot); the caller falls back to id-mapping for that batch."""
63
+
64
+
65
+ def _lib_basename() -> str:
66
+ if sys.platform == "darwin":
67
+ return "libbm25mojo.dylib"
68
+ if sys.platform.startswith("linux"):
69
+ return "libbm25mojo.so"
70
+ if sys.platform.startswith("win"):
71
+ return "bm25mojo.dll" # no Mojo toolchain builds this today
72
+ return "libbm25mojo.so"
73
+
74
+
75
+ def _candidate_paths() -> list[tuple[str, str]]:
76
+ """(source_label, path) candidates, in resolver order."""
77
+ out: list[tuple[str, str]] = []
78
+ override = os.environ.get(_ENV_LIB)
79
+ if override:
80
+ out.append((f"env {_ENV_LIB}", override))
81
+ here = os.path.dirname(__file__)
82
+ out.append(("bundled in wheel", os.path.join(here, "_native", _lib_basename())))
83
+ out.append(
84
+ (
85
+ "repo-dev build output",
86
+ os.path.abspath(
87
+ os.path.join(here, "..", "..", "..", "kernels", "bm25", "build", _lib_basename())
88
+ ),
89
+ )
90
+ )
91
+ return out
92
+
93
+
94
+ def _bind_abi(lib: ctypes.CDLL, abi: int) -> None:
95
+ # Every pointer argument is declared c_void_p and fed a plain integer
96
+ # address (numpy's `arr.ctypes.data`) at call time: ctypes converts a
97
+ # Python int to void* without constructing any per-call pointer object,
98
+ # the cheapest marshal path there is. The C side sees the same ABI.
99
+ vp = ctypes.c_void_p
100
+ lib.bm25mojo_abi_version.argtypes = []
101
+ lib.bm25mojo_abi_version.restype = ctypes.c_int32
102
+ # ABI v2+: the kernel builds the CSR postings and bakes idf-weighted
103
+ # scores from doc-major term-frequency streams.
104
+ lib.bm25mojo_index_create.argtypes = [
105
+ ctypes.c_int64, # n_docs
106
+ vp, # doc_len[n_docs]
107
+ ctypes.c_double, # avgdl
108
+ ctypes.c_double, # k1
109
+ ctypes.c_double, # b
110
+ ctypes.c_double, # delta
111
+ ctypes.c_int32, # variant
112
+ ctypes.c_int64, # n_terms
113
+ vp, # doc_offsets[n_docs+1]
114
+ vp, # doc_tids[ntok]
115
+ vp, # doc_freqs[ntok]
116
+ vp, # idf[n_terms]
117
+ ]
118
+ lib.bm25mojo_index_create.restype = ctypes.c_void_p
119
+ lib.bm25mojo_vocab_attach.argtypes = [vp, vp, ctypes.c_int64, ctypes.c_int64]
120
+ lib.bm25mojo_vocab_attach.restype = ctypes.c_int32
121
+ lib.bm25mojo_score.argtypes = [vp, vp, ctypes.c_int64, vp]
122
+ lib.bm25mojo_score.restype = ctypes.c_int32
123
+ lib.bm25mojo_score_batch.argtypes = [vp, vp, vp, ctypes.c_int64, vp]
124
+ lib.bm25mojo_score_batch.restype = ctypes.c_int32
125
+ lib.bm25mojo_score_batch_str.argtypes = [
126
+ vp,
127
+ vp,
128
+ ctypes.c_int64,
129
+ vp,
130
+ ctypes.c_int64,
131
+ vp,
132
+ ]
133
+ lib.bm25mojo_score_batch_str.restype = ctypes.c_int32
134
+ lib.bm25mojo_index_destroy.argtypes = [vp]
135
+ lib.bm25mojo_index_destroy.restype = None
136
+ if abi >= 4:
137
+ lib.bm25mojo_build_index_corpus.argtypes = [
138
+ ctypes.c_int64, # n_docs
139
+ vp, # tokens[total_bytes]
140
+ vp, # doc_offsets[n_docs + 1]
141
+ ctypes.c_int32, # variant
142
+ ctypes.c_double, # k1
143
+ ctypes.c_double, # b
144
+ ctypes.c_double, # delta
145
+ ctypes.c_double, # epsilon
146
+ ]
147
+ lib.bm25mojo_build_index_corpus.restype = ctypes.c_void_p
148
+ lib.bm25mojo_build_index_tids.argtypes = [
149
+ ctypes.c_int64, # n_docs
150
+ vp, # token_tids[total_tokens]
151
+ vp, # doc_offsets[n_docs + 1]
152
+ ctypes.c_int32, # variant
153
+ ctypes.c_double, # k1
154
+ ctypes.c_double, # b
155
+ ctypes.c_double, # delta
156
+ ctypes.c_double, # epsilon
157
+ ]
158
+ lib.bm25mojo_build_index_tids.restype = ctypes.c_void_p
159
+ lib.bm25mojo_build_result_free.argtypes = [vp]
160
+ lib.bm25mojo_build_result_free.restype = None
161
+
162
+
163
+ _LOCK = threading.Lock()
164
+ _LIB: ctypes.CDLL | None = None
165
+ _LIB_ABI: int | None = None
166
+ _LIB_SOURCE: str | None = None
167
+ _LOAD_ERROR: str | None = None
168
+
169
+
170
+ def _load() -> ctypes.CDLL:
171
+ """Resolve, dlopen, and ABI-handshake the native kernel. Never caches failure."""
172
+ global _LIB, _LIB_ABI, _LIB_SOURCE, _LOAD_ERROR
173
+ if os.environ.get(_ENV_DISABLE) == "1":
174
+ raise NativeUnavailable(f"native kernel disabled by {_ENV_DISABLE}=1")
175
+ if _LIB is not None:
176
+ return _LIB
177
+ with _LOCK:
178
+ if _LIB is not None:
179
+ return _LIB
180
+ errors: list[str] = []
181
+ for label, path in _candidate_paths():
182
+ try:
183
+ if not path or not os.path.exists(path):
184
+ continue
185
+ try:
186
+ lib = ctypes.CDLL(path)
187
+ except OSError as exc:
188
+ errors.append(f"{label} ({path}): {exc}")
189
+ continue
190
+ try:
191
+ lib.bm25mojo_abi_version.argtypes = []
192
+ lib.bm25mojo_abi_version.restype = ctypes.c_int32
193
+ abi = int(lib.bm25mojo_abi_version())
194
+ except Exception as exc: # missing/renamed symbol = wrong lib
195
+ errors.append(f"{label} ({path}): ABI not recognized: {exc}")
196
+ continue
197
+ if abi < ABI_VERSION_MIN or abi > ABI_VERSION:
198
+ errors.append(
199
+ f"{label} ({path}): native ABI v{abi} not in supported range "
200
+ f"v{ABI_VERSION_MIN}..v{ABI_VERSION}"
201
+ )
202
+ continue
203
+ try:
204
+ _bind_abi(lib, abi)
205
+ except Exception as exc:
206
+ errors.append(f"{label} ({path}): ABI not recognized: {exc}")
207
+ continue
208
+ _LIB, _LIB_ABI, _LIB_SOURCE = lib, abi, f"{label} ({path})"
209
+ _LOAD_ERROR = None
210
+ return lib
211
+ except OSError as exc:
212
+ errors.append(f"{label}: {exc}")
213
+ _LOAD_ERROR = "; ".join(errors) or "no native kernel found on any resolver path"
214
+ raise NativeUnavailable(_LOAD_ERROR)
215
+
216
+
217
+ def native_available() -> bool:
218
+ """True if the native kernel can score right now. Never raises."""
219
+ try:
220
+ _load()
221
+ return True
222
+ except NativeUnavailable:
223
+ return False
224
+
225
+
226
+ def backend_info() -> dict:
227
+ """Diagnostics for the active backend. Never raises."""
228
+ info = {
229
+ "native_available": False,
230
+ "native_source": None,
231
+ "abi_version_expected": ABI_VERSION,
232
+ "abi_version_native": None,
233
+ "disabled_by_env": os.environ.get(_ENV_DISABLE) == "1",
234
+ "platform": sys.platform,
235
+ "error": None,
236
+ }
237
+ try:
238
+ lib = _load()
239
+ except NativeUnavailable as exc:
240
+ info["error"] = str(exc)
241
+ return info
242
+ info["native_available"] = True
243
+ info["native_source"] = _LIB_SOURCE
244
+ info["abi_version_native"] = int(lib.bm25mojo_abi_version())
245
+ return info
246
+
247
+
248
+ def native_build_available() -> bool:
249
+ """True if the loaded native library supports the ABI v4 corpus builder."""
250
+ try:
251
+ _load()
252
+ except NativeUnavailable:
253
+ return False
254
+ return _LIB_ABI is not None and _LIB_ABI >= 4
255
+
256
+
257
+ class _BuildResultC(ctypes.Structure):
258
+ """C layout of the Mojo BuildResult struct."""
259
+
260
+ _fields_ = [
261
+ ("status", ctypes.c_int32),
262
+ ("_pad", ctypes.c_int32),
263
+ ("n_docs", ctypes.c_int64),
264
+ ("n_terms", ctypes.c_int64),
265
+ ("nnz", ctypes.c_int64),
266
+ ("avgdl", ctypes.c_double),
267
+ ("doc_len", ctypes.c_void_p),
268
+ ("doc_offsets", ctypes.c_void_p),
269
+ ("doc_tids", ctypes.c_void_p),
270
+ ("doc_freqs", ctypes.c_void_p),
271
+ ("df", ctypes.c_void_p),
272
+ ("vocab_buf", ctypes.c_void_p),
273
+ ("vocab_lens", ctypes.c_void_p),
274
+ ]
275
+
276
+
277
+ _CTYPE_FOR_DTYPE = {
278
+ np.float64: ctypes.c_double,
279
+ np.int64: ctypes.c_int64,
280
+ np.int32: ctypes.c_int32,
281
+ np.uint8: ctypes.c_uint8,
282
+ }
283
+
284
+
285
+ def _array_from_ptr(ptr: int, dtype: np.dtype, shape: tuple[int, ...]) -> np.ndarray:
286
+ """Wrap a C pointer as a temporary numpy array (caller must copy to own)."""
287
+ c_type = _CTYPE_FOR_DTYPE[dtype]
288
+ c_ptr = ctypes.cast(ptr, ctypes.POINTER(c_type))
289
+ return np.ctypeslib.as_array(c_ptr, shape=shape)
290
+
291
+
292
+ def _build_result_to_dict(result_ptr: int) -> dict:
293
+ """Copy a native BuildResult into Python-owned numpy arrays and free it."""
294
+ lib = _load()
295
+ result = ctypes.cast(result_ptr, ctypes.POINTER(_BuildResultC)).contents
296
+ if result.status != 0:
297
+ lib.bm25mojo_build_result_free(result_ptr)
298
+ raise NativeUnavailable(f"native corpus build failed with status {result.status}")
299
+ n_terms = int(result.n_terms)
300
+ n_docs_out = int(result.n_docs)
301
+ nnz = int(result.nnz)
302
+ avgdl = float(result.avgdl)
303
+ try:
304
+ doc_len = _array_from_ptr(result.doc_len, np.float64, (n_docs_out,)).copy()
305
+ doc_offsets_out = _array_from_ptr(result.doc_offsets, np.int64, (n_docs_out + 1,)).copy()
306
+ doc_tids = _array_from_ptr(result.doc_tids, np.int32, (nnz,)).copy()
307
+ doc_freqs = _array_from_ptr(result.doc_freqs, np.float64, (nnz,)).copy()
308
+ df = _array_from_ptr(result.df, np.int64, (n_terms,)).copy()
309
+ vocab_lens = _array_from_ptr(result.vocab_lens, np.int32, (n_terms,)).copy()
310
+ vocab_buf_size = int(vocab_lens.sum())
311
+ vocab_buf = _array_from_ptr(result.vocab_buf, np.uint8, (vocab_buf_size,)).copy()
312
+ finally:
313
+ lib.bm25mojo_build_result_free(result_ptr)
314
+ return {
315
+ "n_docs": n_docs_out,
316
+ "n_terms": n_terms,
317
+ "nnz": nnz,
318
+ "avgdl": avgdl,
319
+ "doc_len": doc_len,
320
+ "doc_offsets": doc_offsets_out,
321
+ "doc_tids": doc_tids,
322
+ "doc_freqs": doc_freqs,
323
+ "df": df,
324
+ "vocab_buf": vocab_buf,
325
+ "vocab_lens": vocab_lens,
326
+ }
327
+
328
+
329
+ def build_index_corpus(
330
+ n_docs: int,
331
+ tokens: bytes,
332
+ doc_offsets: np.ndarray,
333
+ variant: int,
334
+ k1: float,
335
+ b: float,
336
+ delta: float,
337
+ epsilon: float,
338
+ ) -> dict:
339
+ """Native corpus ingestion: length-prefixed UTF-8 token stream -> index data.
340
+
341
+ The returned arrays are freshly allocated numpy copies; the Mojo-side
342
+ result object is freed before returning. Raises :class:`NativeUnavailable`
343
+ on any build error so the caller can fall back to the Python build path.
344
+ """
345
+ lib = _load()
346
+ if _LIB_ABI is None or _LIB_ABI < 4:
347
+ raise NativeUnavailable("native library does not expose ABI v4 corpus builder")
348
+ tokens_arr = np.frombuffer(tokens, dtype=np.uint8)
349
+ doc_offsets = np.ascontiguousarray(doc_offsets, dtype=np.int64)
350
+ result_ptr = lib.bm25mojo_build_index_corpus(
351
+ ctypes.c_int64(n_docs),
352
+ tokens_arr.ctypes.data,
353
+ doc_offsets.ctypes.data,
354
+ ctypes.c_int32(variant),
355
+ ctypes.c_double(k1),
356
+ ctypes.c_double(b),
357
+ ctypes.c_double(delta),
358
+ ctypes.c_double(epsilon),
359
+ )
360
+ if not result_ptr:
361
+ raise NativeUnavailable("native corpus build returned NULL")
362
+ return _build_result_to_dict(result_ptr)
363
+
364
+
365
+ def build_index_tids(
366
+ n_docs: int,
367
+ token_tids: np.ndarray,
368
+ doc_offsets: np.ndarray,
369
+ variant: int,
370
+ k1: float,
371
+ b: float,
372
+ delta: float,
373
+ epsilon: float,
374
+ ) -> dict:
375
+ """Native corpus ingestion: term-id stream -> index data.
376
+
377
+ `token_tids` must be a contiguous int32 array of all term ids in document
378
+ order; `doc_offsets` has n_docs + 1 token offsets. Term ids are assigned by
379
+ the caller in first-appearance order and must form a dense 0..n_terms-1
380
+ range. The returned arrays are freshly allocated numpy copies; the Mojo-side
381
+ result object is freed before returning. Raises :class:`NativeUnavailable`
382
+ on any build error so the caller can fall back to another build path.
383
+ """
384
+ lib = _load()
385
+ if _LIB_ABI is None or _LIB_ABI < 4:
386
+ raise NativeUnavailable("native library does not expose ABI v4 term-id builder")
387
+ token_tids = np.ascontiguousarray(token_tids, dtype=np.int32)
388
+ doc_offsets = np.ascontiguousarray(doc_offsets, dtype=np.int64)
389
+ result_ptr = lib.bm25mojo_build_index_tids(
390
+ ctypes.c_int64(n_docs),
391
+ token_tids.ctypes.data,
392
+ doc_offsets.ctypes.data,
393
+ ctypes.c_int32(variant),
394
+ ctypes.c_double(k1),
395
+ ctypes.c_double(b),
396
+ ctypes.c_double(delta),
397
+ ctypes.c_double(epsilon),
398
+ )
399
+ if not result_ptr:
400
+ raise NativeUnavailable("native term-id build returned NULL")
401
+ return _build_result_to_dict(result_ptr)
402
+
403
+
404
+ class NativeIndex:
405
+ """Owned handle to a native corpus index. Not thread-safe to close twice."""
406
+
407
+ def __init__(
408
+ self,
409
+ doc_len: np.ndarray,
410
+ avgdl: float,
411
+ k1: float,
412
+ b: float,
413
+ delta: float,
414
+ variant: int,
415
+ doc_offsets: np.ndarray,
416
+ doc_tids: np.ndarray,
417
+ doc_freqs: np.ndarray,
418
+ idf: np.ndarray,
419
+ vocab_terms: np.ndarray | None = None,
420
+ ) -> None:
421
+ lib = _load() # raises NativeUnavailable
422
+ doc_len = np.ascontiguousarray(doc_len, dtype=np.float64)
423
+ doc_offsets = np.ascontiguousarray(doc_offsets, dtype=np.int64)
424
+ doc_tids = np.ascontiguousarray(doc_tids, dtype=np.int32)
425
+ doc_freqs = np.ascontiguousarray(doc_freqs, dtype=np.float64)
426
+ idf = np.ascontiguousarray(idf, dtype=np.float64)
427
+ n_docs = np.int64(doc_len.shape[0])
428
+ n_terms = np.int64(idf.shape[0])
429
+ handle = lib.bm25mojo_index_create(
430
+ n_docs,
431
+ doc_len.ctypes.data,
432
+ ctypes.c_double(avgdl),
433
+ ctypes.c_double(k1),
434
+ ctypes.c_double(b),
435
+ ctypes.c_double(delta),
436
+ ctypes.c_int32(variant),
437
+ n_terms,
438
+ doc_offsets.ctypes.data,
439
+ doc_tids.ctypes.data,
440
+ doc_freqs.ctypes.data,
441
+ idf.ctypes.data,
442
+ )
443
+ if not handle:
444
+ raise NativeUnavailable(
445
+ "native kernel rejected the index (invalid sizes, streams, or "
446
+ "variant); falling back to the pure-Python reference"
447
+ )
448
+ # The kernel copies every buffer; these arrays may be freed by the GC.
449
+ self._lib = lib
450
+ self._handle = handle
451
+ self._n_docs = int(n_docs)
452
+ # Hot-path caches: avoid per-call ctypes constructor overhead.
453
+ self._score_fn = lib.bm25mojo_score
454
+ self._batch_fn = lib.bm25mojo_score_batch
455
+ self._batch_str_fn = lib.bm25mojo_score_batch_str
456
+ # Attach the vocabulary for the native string-token batch path. On any
457
+ # refusal (mismatched sizes, embedded-NUL term) the index simply keeps
458
+ # using the id-mapping path — results are identical, mapping is slower.
459
+ self._str_ok = False
460
+ if vocab_terms is not None:
461
+ vocab_terms = np.ascontiguousarray(vocab_terms)
462
+ if (
463
+ vocab_terms.dtype.kind == "S"
464
+ and vocab_terms.shape[0] == int(n_terms)
465
+ and 0 < vocab_terms.dtype.itemsize <= MAX_TOKEN_WIDTH
466
+ ):
467
+ rc = lib.bm25mojo_vocab_attach(
468
+ handle,
469
+ vocab_terms.ctypes.data,
470
+ vocab_terms.dtype.itemsize,
471
+ int(n_terms),
472
+ )
473
+ self._str_ok = rc == 0
474
+
475
+ @property
476
+ def n_docs(self) -> int:
477
+ return self._n_docs
478
+
479
+ @property
480
+ def str_ok(self) -> bool:
481
+ """Whether the native string-token batch path is armed for this index."""
482
+ return self._str_ok
483
+
484
+ def score(self, query_term_ids: np.ndarray) -> np.ndarray:
485
+ """Score one token-id query against every document. Returns float64[n_docs].
486
+
487
+ The output buffer comes from np.zeros (calloc): the kernel accumulates
488
+ without zeroing, so per-query cost is O(postings), not O(n_docs).
489
+ """
490
+ if self._handle is None:
491
+ raise NativeUnavailable("native index is closed")
492
+ if query_term_ids.dtype != np.int32 or not query_term_ids.flags.c_contiguous:
493
+ query_term_ids = np.ascontiguousarray(query_term_ids, dtype=np.int32)
494
+ out = np.zeros(self._n_docs, dtype=np.float64)
495
+ rc = self._score_fn(
496
+ self._handle,
497
+ query_term_ids.ctypes.data,
498
+ len(query_term_ids),
499
+ out.ctypes.data,
500
+ )
501
+ if rc != 0:
502
+ raise NativeUnavailable(f"native scoring failed with status {rc}")
503
+ return out
504
+
505
+ def score_batch_flat(
506
+ self, qids_flat: np.ndarray, offsets: np.ndarray, n_queries: int
507
+ ) -> np.ndarray:
508
+ """Score a pre-packed batch of queries in one FFI call.
509
+
510
+ `qids_flat`/`offsets` are the concatenated int32 term ids and their
511
+ int64 per-query offsets (n_queries + 1 entries) — the exact C ABI
512
+ layout, so callers that pack once pay no per-query marshalling.
513
+ Returns a float64 (n_queries, n_docs) panel whose row i is
514
+ bit-identical to scoring query i alone.
515
+ """
516
+ if self._handle is None:
517
+ raise NativeUnavailable("native index is closed")
518
+ if n_queries == 0:
519
+ return np.zeros((0, self._n_docs), dtype=np.float64)
520
+ if qids_flat.dtype != np.int32 or not qids_flat.flags.c_contiguous:
521
+ qids_flat = np.ascontiguousarray(qids_flat, dtype=np.int32)
522
+ if offsets.dtype != np.int64 or not offsets.flags.c_contiguous:
523
+ offsets = np.ascontiguousarray(offsets, dtype=np.int64)
524
+ panel = np.zeros((n_queries, self._n_docs), dtype=np.float64)
525
+ rc = self._batch_fn(
526
+ self._handle,
527
+ qids_flat.ctypes.data,
528
+ offsets.ctypes.data,
529
+ n_queries,
530
+ panel.ctypes.data,
531
+ )
532
+ if rc != 0:
533
+ raise NativeUnavailable(f"native batch scoring failed with status {rc}")
534
+ return panel
535
+
536
+ def score_batch_str(
537
+ self, tokens: np.ndarray, counts: np.ndarray, n_queries: int
538
+ ) -> np.ndarray:
539
+ """Score a batch of string-token queries in one FFI call.
540
+
541
+ `tokens` is the concatenated batch as a fixed-width ``'S'`` array
542
+ (NUL-padded slots); `counts[q]` is query q's token count. Mapping,
543
+ offset accumulation and scoring all run natively; each row of the
544
+ returned float64 (n_queries, n_docs) panel is bit-identical to
545
+ `score_batch_flat` over the mapped ids. Raises UnsafeTokenError when a
546
+ slot cannot be a NUL-padded string (embedded NUL) or is over-wide —
547
+ the caller then falls back to id-mapping for that batch.
548
+ """
549
+ if self._handle is None:
550
+ raise NativeUnavailable("native index is closed")
551
+ if n_queries == 0:
552
+ return np.zeros((0, self._n_docs), dtype=np.float64)
553
+ if not self._str_ok:
554
+ raise NativeUnavailable("native string path is not armed (no vocab map)")
555
+ tokens = np.ascontiguousarray(tokens)
556
+ counts = np.ascontiguousarray(counts, dtype=np.int32)
557
+ width = tokens.dtype.itemsize
558
+ if tokens.dtype.kind != "S" or width <= 0 or width > MAX_TOKEN_WIDTH:
559
+ raise UnsafeTokenError(f"unsupported token slot width {width!r}")
560
+ panel = np.zeros((n_queries, self._n_docs), dtype=np.float64)
561
+ rc = self._batch_str_fn(
562
+ self._handle,
563
+ tokens.ctypes.data,
564
+ width,
565
+ counts.ctypes.data,
566
+ n_queries,
567
+ panel.ctypes.data,
568
+ )
569
+ if rc == 3:
570
+ raise UnsafeTokenError("query token with an embedded NUL byte")
571
+ if rc != 0:
572
+ raise NativeUnavailable(f"native string batch scoring failed with status {rc}")
573
+ return panel
574
+
575
+ def score_batch(self, query_term_ids_list: list[np.ndarray]) -> np.ndarray:
576
+ """Score a batch of token-id queries in one FFI call.
577
+
578
+ Returns a float64 (n_queries, n_docs) panel whose row i is
579
+ bit-identical to `score(query_term_ids_list[i])`.
580
+ """
581
+ n_queries = len(query_term_ids_list)
582
+ if n_queries == 0:
583
+ return np.zeros((0, self._n_docs), dtype=np.float64)
584
+ counts = np.fromiter((len(q) for q in query_term_ids_list), dtype=np.int64,
585
+ count=n_queries)
586
+ qids_flat = np.concatenate(
587
+ [np.ascontiguousarray(q, dtype=np.int32) for q in query_term_ids_list]
588
+ )
589
+ offsets = np.zeros(n_queries + 1, dtype=np.int64)
590
+ np.cumsum(counts, out=offsets[1:])
591
+ return self.score_batch_flat(qids_flat, offsets, n_queries)
592
+
593
+ def close(self) -> None:
594
+ handle, self._handle = self._handle, None
595
+ if handle and self._lib is not None:
596
+ self._lib.bm25mojo_index_destroy(handle)
597
+
598
+ def __del__(self) -> None: # best-effort; never raise during GC
599
+ try:
600
+ self.close()
601
+ except Exception: # noqa: BLE001, S110
602
+ pass
@@ -0,0 +1,88 @@
1
+ """Vendored pure-Python reference scorers for the BM25 family.
2
+
3
+ This is the fallback path used when the native Mojo kernel is unavailable
4
+ (unsupported platform, missing shared library, ABI mismatch, or
5
+ ``BM25_MOJO_DISABLE_NATIVE=1``). It is a clean-room implementation of the
6
+ textbook formulas (Trotman et al., "Improvements to BM25 and Language Models
7
+ Examined") written to be observably identical to the widely used `rank_bm25`
8
+ package: same parameter defaults, same NumPy operation order, same dtypes, so
9
+ scores agree bit-for-bit (both paths are IEEE-754 float64 element-wise).
10
+
11
+ Only scoring lives here; index construction and idf calculation are shared
12
+ with the native path in `bm25_mojo.core`, so the two backends can never
13
+ disagree about the index itself.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import numpy as np
19
+
20
+
21
+ def okapi_scores(
22
+ doc_freqs: list[dict],
23
+ idf: dict,
24
+ doc_len: list[int],
25
+ avgdl: float,
26
+ query: list[str],
27
+ k1: float,
28
+ b: float,
29
+ ) -> np.ndarray:
30
+ """BM25Okapi: idf * (qf * (k1 + 1) / (qf + k1 * (1 - b + b * dl / avgdl)))."""
31
+ score = np.zeros(len(doc_freqs))
32
+ doc_len_arr = np.array(doc_len)
33
+ for q in query:
34
+ q_freq = np.array([(doc.get(q) or 0) for doc in doc_freqs])
35
+ score += (idf.get(q) or 0) * (
36
+ q_freq * (k1 + 1) / (q_freq + k1 * (1 - b + b * doc_len_arr / avgdl))
37
+ )
38
+ return score
39
+
40
+
41
+ def l_scores(
42
+ doc_freqs: list[dict],
43
+ idf: dict,
44
+ doc_len: list[int],
45
+ avgdl: float,
46
+ query: list[str],
47
+ k1: float,
48
+ b: float,
49
+ delta: float,
50
+ ) -> np.ndarray:
51
+ """BM25L as published on PyPI (rank_bm25 0.2.2):
52
+ idf * qf * (k1 + 1) * (ctd + delta) / (k1 + ctd + delta).
53
+
54
+ Note: rank_bm25's GitHub master dropped the leading qf factor after the
55
+ 0.2.2 release; this package matches the published PyPI package, which is
56
+ what `pip install rank_bm25` users run.
57
+ """
58
+ score = np.zeros(len(doc_freqs))
59
+ doc_len_arr = np.array(doc_len)
60
+ for q in query:
61
+ q_freq = np.array([(doc.get(q) or 0) for doc in doc_freqs])
62
+ ctd = q_freq / (1 - b + b * doc_len_arr / avgdl)
63
+ score += (
64
+ (idf.get(q) or 0) * q_freq * (k1 + 1) * (ctd + delta) / (k1 + ctd + delta)
65
+ )
66
+ return score
67
+
68
+
69
+ def plus_scores(
70
+ doc_freqs: list[dict],
71
+ idf: dict,
72
+ doc_len: list[int],
73
+ avgdl: float,
74
+ query: list[str],
75
+ k1: float,
76
+ b: float,
77
+ delta: float,
78
+ ) -> np.ndarray:
79
+ """BM25Plus: idf * (delta + qf * (k1 + 1) / (k1 * (1 - b + b * dl / avgdl) + qf))."""
80
+ score = np.zeros(len(doc_freqs))
81
+ doc_len_arr = np.array(doc_len)
82
+ for q in query:
83
+ q_freq = np.array([(doc.get(q) or 0) for doc in doc_freqs])
84
+ score += (idf.get(q) or 0) * (
85
+ delta
86
+ + (q_freq * (k1 + 1)) / (k1 * (1 - b + b * doc_len_arr / avgdl) + q_freq)
87
+ )
88
+ return score
bm25_mojo/core.py ADDED
@@ -0,0 +1,553 @@
1
+ """Drop-in BM25 ranking, API-compatible with the `rank_bm25` package.
2
+
3
+ `BM25Okapi`, `BM25L`, and `BM25Plus` accept the same constructor arguments,
4
+ expose the same index attributes (`corpus_size`, `avgdl`, `doc_freqs`, `idf`,
5
+ `doc_len`, ...), and return the same types from `get_scores`, `get_batch_scores`,
6
+ and `get_top_n` as their `rank_bm25` counterparts.
7
+
8
+ Scoring runs on the native Mojo kernel when its shared library is available
9
+ (macOS arm64 / Linux x86_64 wheels) and transparently falls back to the
10
+ vendored pure-Python reference implementation otherwise. Both backends share
11
+ index construction and idf calculation in this module, so results are
12
+ identical either way; the differential test suite asserts element-wise
13
+ agreement with `rank_bm25` on both paths.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+
20
+ import numpy as np
21
+
22
+ from bm25_mojo import _reference
23
+ from bm25_mojo._native import (
24
+ VARIANT_L,
25
+ VARIANT_OKAPI,
26
+ VARIANT_PLUS,
27
+ NativeIndex,
28
+ NativeUnavailable,
29
+ UnsafeTokenError,
30
+ build_index_corpus,
31
+ build_index_tids,
32
+ native_build_available,
33
+ )
34
+
35
+ __all__ = ["BM25", "BM25Okapi", "BM25L", "BM25Plus"]
36
+
37
+
38
+ class BM25:
39
+ """Shared index construction and the `rank_bm25` query API surface."""
40
+
41
+ # Overridden by subclasses: kernel variant id and fallback scorer.
42
+ _variant: int = VARIANT_OKAPI
43
+ _delta: float = 0.0
44
+
45
+ def __init__(self, corpus, tokenizer=None):
46
+ self.corpus_size = 0
47
+ self.avgdl = 0
48
+ self._doc_freqs = None
49
+ self._doc_freqs_native_arrays = None
50
+ self.idf = {}
51
+ self.doc_len = []
52
+ self.tokenizer = tokenizer
53
+
54
+ if tokenizer:
55
+ corpus = self._tokenize_corpus(corpus)
56
+
57
+ if native_build_available():
58
+ try:
59
+ arrays = self._build_native(corpus)
60
+ if arrays is not None:
61
+ terms = self._load_from_native_arrays(arrays)
62
+ nd = {term: int(arrays["df"][tid]) for tid, term in enumerate(terms)}
63
+ self._calc_idf(nd)
64
+ self._backend = self._build_native_index(arrays=arrays)
65
+ return
66
+ except (NativeUnavailable, UnsafeTokenError):
67
+ pass
68
+
69
+ nd = self._initialize(corpus)
70
+ self._calc_idf(nd)
71
+ self._backend = self._build_native_index(nd=nd)
72
+
73
+ @property
74
+ def doc_freqs(self):
75
+ """Per-document term frequencies; built lazily on first access."""
76
+ if self._doc_freqs is None:
77
+ self._doc_freqs = self._build_doc_freqs_from_arrays()
78
+ return self._doc_freqs
79
+
80
+ @doc_freqs.setter
81
+ def doc_freqs(self, value):
82
+ self._doc_freqs = value
83
+ self._doc_freqs_native_arrays = None
84
+
85
+ def _tokenize_corpus(self, corpus):
86
+ # rank_bm25 maps the tokenizer with multiprocessing.Pool; a sequential
87
+ # map returns element-for-element identical results without spawning
88
+ # processes (deterministic, and safe in test/CI sandboxes).
89
+ return [self.tokenizer(document) for document in corpus]
90
+
91
+ def _build_doc_freqs_from_arrays(self):
92
+ """Reconstruct the rank_bm25-compatible doc_freqs list from native arrays."""
93
+ arrays = self._doc_freqs_native_arrays
94
+ if arrays is None:
95
+ return []
96
+ terms = self._vocab_terms
97
+ if terms is None:
98
+ return []
99
+ doc_offsets = arrays["doc_offsets"]
100
+ doc_tids = arrays["doc_tids"]
101
+ doc_freqs = arrays["doc_freqs"]
102
+ return [
103
+ {
104
+ terms[int(tid)]: float(freq)
105
+ for tid, freq in zip(
106
+ doc_tids[int(doc_offsets[d]) : int(doc_offsets[d + 1])],
107
+ doc_freqs[int(doc_offsets[d]) : int(doc_offsets[d + 1])],
108
+ strict=True,
109
+ )
110
+ }
111
+ for d in range(arrays["n_docs"])
112
+ ]
113
+
114
+ @staticmethod
115
+ def _pack_corpus(corpus):
116
+ """Flatten a tokenised corpus into a length-prefixed UTF-8 byte buffer.
117
+
118
+ Returns ``(tokens_bytes, doc_offsets)`` where ``doc_offsets`` are byte
119
+ offsets. Each token is encoded as a 4-byte little-endian length followed
120
+ by its UTF-8 bytes, so empty tokens and arbitrary UTF-8 content are
121
+ preserved without ambiguity. Raises ``UnsafeTokenError`` for non-``str``
122
+ tokens, signalling that the caller should fall back to the pure-Python
123
+ build path (which supports arbitrary hashable tokens).
124
+ """
125
+ buf = bytearray()
126
+ doc_offsets = [0]
127
+ for doc in corpus:
128
+ if not doc:
129
+ doc_offsets.append(len(buf))
130
+ continue
131
+ for tok in doc:
132
+ if type(tok) is not str:
133
+ raise UnsafeTokenError("native build requires str tokens")
134
+ b = tok.encode("utf-8")
135
+ buf.extend(len(b).to_bytes(4, "little"))
136
+ buf.extend(b)
137
+ doc_offsets.append(len(buf))
138
+ return bytes(buf), np.array(doc_offsets, dtype=np.int64)
139
+
140
+ @staticmethod
141
+ def _token_ids_for_corpus(corpus):
142
+ """Assign term ids in first-appearance order and return flat id streams.
143
+
144
+ Returns ``(token_tids, doc_offsets, terms, vocab)`` where ``terms`` is
145
+ the vocabulary in first-appearance order and ``vocab`` is the term ->
146
+ tid dict. Raises ``UnsafeTokenError`` for non-``str`` tokens.
147
+ """
148
+ vocab = {}
149
+ terms = []
150
+ flat_tids = []
151
+ add_tid = flat_tids.append
152
+ doc_offsets = [0]
153
+ for doc in corpus:
154
+ for tok in doc:
155
+ if type(tok) is not str:
156
+ raise UnsafeTokenError("native build requires str tokens")
157
+ tid = vocab.get(tok)
158
+ if tid is None:
159
+ tid = len(terms)
160
+ vocab[tok] = tid
161
+ terms.append(tok)
162
+ add_tid(tid)
163
+ doc_offsets.append(len(flat_tids))
164
+ return (
165
+ np.array(flat_tids, dtype=np.int32),
166
+ np.array(doc_offsets, dtype=np.int64),
167
+ terms,
168
+ vocab,
169
+ )
170
+
171
+ def _build_native(self, corpus):
172
+ """Try to build the index via the ABI v4 native corpus builder.
173
+
174
+ Prefers the term-id path (Python assigns ids, native counts) because it
175
+ avoids token encoding and byte parsing. Falls back to the UTF-8 corpus
176
+ path when the term-id builder is unavailable.
177
+ """
178
+ try:
179
+ token_tids, doc_offsets, terms, vocab = self._token_ids_for_corpus(corpus)
180
+ except UnsafeTokenError:
181
+ return self._build_native_corpus(corpus)
182
+ try:
183
+ arrays = build_index_tids(
184
+ n_docs=len(corpus),
185
+ token_tids=token_tids,
186
+ doc_offsets=doc_offsets,
187
+ variant=self._variant,
188
+ k1=float(self.k1),
189
+ b=float(self.b),
190
+ delta=float(self._delta),
191
+ epsilon=float(getattr(self, "epsilon", 0.0)),
192
+ )
193
+ except NativeUnavailable:
194
+ return self._build_native_corpus(corpus)
195
+ # Keep the Python-built vocabulary; the kernel returned a dummy vocab buffer.
196
+ arrays["terms"] = terms
197
+ arrays["vocab"] = vocab
198
+ return arrays
199
+
200
+ def _build_native_corpus(self, corpus):
201
+ """Try to build the index via the UTF-8 token-stream native builder."""
202
+ tokens, doc_offsets = self._pack_corpus(corpus)
203
+ return build_index_corpus(
204
+ n_docs=len(corpus),
205
+ tokens=tokens,
206
+ doc_offsets=doc_offsets,
207
+ variant=self._variant,
208
+ k1=float(self.k1),
209
+ b=float(self.b),
210
+ delta=float(self._delta),
211
+ epsilon=float(getattr(self, "epsilon", 0.0)),
212
+ )
213
+
214
+ def _load_from_native_arrays(self, arrays):
215
+ """Populate the rank_bm25-compatible index attributes from native outputs.
216
+
217
+ Returns the list of vocabulary terms in first-appearance (term-id) order
218
+ so the caller can build ``nd`` and evaluate idfs with Python's
219
+ ``math.log`` for bit-exact parity with rank_bm25.
220
+ """
221
+ self.corpus_size = arrays["n_docs"]
222
+ self.avgdl = arrays["avgdl"]
223
+ self.doc_len = [int(x) for x in arrays["doc_len"]]
224
+
225
+ terms = arrays.get("terms")
226
+ vocab = arrays.get("vocab")
227
+ if terms is None:
228
+ vocab_buf = arrays["vocab_buf"]
229
+ vocab_lens = arrays["vocab_lens"]
230
+ terms = []
231
+ off = 0
232
+ for length in vocab_lens:
233
+ length = int(length)
234
+ terms.append(vocab_buf[off : off + length].tobytes().decode("utf-8"))
235
+ off += length
236
+ vocab = {term: tid for tid, term in enumerate(terms)}
237
+ self._vocab = vocab
238
+ self._vocab_terms = terms
239
+
240
+ # Defer doc_freqs construction: it is only needed for the fallback
241
+ # reference scorer and for direct attribute inspection.
242
+ self._doc_freqs_native_arrays = arrays
243
+ self._doc_freqs = None
244
+ return terms
245
+
246
+ def _initialize(self, corpus):
247
+ nd = {} # word -> number of documents containing the word
248
+ num_doc = 0
249
+ for document in corpus:
250
+ self.doc_len.append(len(document))
251
+ num_doc += len(document)
252
+
253
+ frequencies = {}
254
+ for word in document:
255
+ if word not in frequencies:
256
+ frequencies[word] = 0
257
+ frequencies[word] += 1
258
+ if self._doc_freqs is None:
259
+ self._doc_freqs = []
260
+ self._doc_freqs.append(frequencies)
261
+
262
+ for word in frequencies:
263
+ try:
264
+ nd[word] += 1
265
+ except KeyError:
266
+ nd[word] = 1
267
+
268
+ self.corpus_size += 1
269
+
270
+ self.avgdl = num_doc / self.corpus_size
271
+ return nd
272
+
273
+ def _calc_idf(self, nd):
274
+ raise NotImplementedError()
275
+
276
+ def _build_native_index(self, nd=None, arrays=None) -> str:
277
+ """Hand the numeric index to the native kernel; return the backend name.
278
+
279
+ Falls back to the vendored reference scorer when the native library is
280
+ unavailable, and in the degenerate avgdl == 0 case (an entirely empty
281
+ corpus), where the reference's IEEE behaviour (NaN propagation) is the
282
+ contract we mirror.
283
+
284
+ The kernel builds the CSR postings and bakes the idf-weighted scores
285
+ itself; this method only assembles doc-major term streams.
286
+ """
287
+ if self.avgdl == 0:
288
+ self._native_index = None
289
+ return "fallback"
290
+ if arrays is not None:
291
+ self._vocab = arrays.get("vocab")
292
+ if self._vocab is None:
293
+ # Reconstruct the vocabulary mapping from the byte buffer if the
294
+ # caller did not pre-build it.
295
+ vocab_buf = arrays["vocab_buf"]
296
+ vocab_lens = arrays["vocab_lens"]
297
+ terms = []
298
+ off = 0
299
+ for length in vocab_lens:
300
+ length = int(length)
301
+ terms.append(vocab_buf[off : off + length].tobytes().decode("utf-8"))
302
+ off += length
303
+ self._vocab = {term: tid for tid, term in enumerate(terms)}
304
+ idf_values = arrays.get("idf")
305
+ if idf_values is None:
306
+ idf_values = np.array([self.idf[word] for word in self._vocab], dtype=np.float64)
307
+ doc_offsets = arrays["doc_offsets"]
308
+ doc_tids = arrays["doc_tids"]
309
+ doc_freqs = arrays["doc_freqs"]
310
+ vocab_terms = None
311
+ if all(type(t) is str for t in self._vocab):
312
+ try:
313
+ vocab_terms = np.asarray(list(self._vocab), dtype="S")
314
+ except (UnicodeEncodeError, TypeError, ValueError):
315
+ vocab_terms = None
316
+ else:
317
+ # Vocabulary in first-appearance order (same iteration order as `nd`).
318
+ self._vocab = {word: tid for tid, word in enumerate(nd)}
319
+ vocab_get = self._vocab.get
320
+ doc_offsets = [0]
321
+ tids: list[int] = []
322
+ freqs: list[float] = []
323
+ for frequencies in self.doc_freqs:
324
+ tids.extend(map(vocab_get, frequencies))
325
+ freqs.extend(frequencies.values())
326
+ doc_offsets.append(len(tids))
327
+ idf_values = np.array([self.idf[word] for word in self._vocab], dtype=np.float64)
328
+ doc_offsets = np.array(doc_offsets, dtype=np.int64)
329
+ doc_tids = np.array(tids, dtype=np.int32)
330
+ doc_freqs = np.array(freqs, dtype=np.float64)
331
+ # Vocabulary as fixed-width 'S' slots in id order (dict iteration
332
+ # order), for the kernel's native token->id map. The native map keys
333
+ # are byte strings, so it may only be used when every term is a `str`
334
+ # — numpy 'S' conversion would silently stringify non-str keys and
335
+ # could conflate distinct dict keys (e.g. int 1 with "1"). Non-ASCII
336
+ # terms cannot encode to 'S' either. Any refusal simply leaves the
337
+ # id-mapping path in charge (identical results, slower mapping).
338
+ vocab_terms = None
339
+ if all(map(str.__instancecheck__, self._vocab)):
340
+ try:
341
+ vocab_terms = np.asarray(list(self._vocab), dtype="S")
342
+ except (UnicodeEncodeError, TypeError, ValueError):
343
+ vocab_terms = None
344
+ try:
345
+ self._native_index = NativeIndex(
346
+ doc_len=np.array(self.doc_len, dtype=np.float64),
347
+ avgdl=float(self.avgdl),
348
+ k1=float(self.k1),
349
+ b=float(self.b),
350
+ delta=float(self._delta),
351
+ variant=self._variant,
352
+ doc_offsets=doc_offsets,
353
+ doc_tids=doc_tids,
354
+ doc_freqs=doc_freqs,
355
+ idf=idf_values,
356
+ vocab_terms=vocab_terms,
357
+ )
358
+ return "native"
359
+ except NativeUnavailable:
360
+ self._native_index = None
361
+ return "fallback"
362
+
363
+ @property
364
+ def backend(self) -> str:
365
+ """Which scorer serves this instance: "native" or "fallback"."""
366
+ return self._backend
367
+
368
+ def get_scores(self, query):
369
+ if self._native_index is not None:
370
+ # Unseen terms contribute exactly 0 (their idf lookup is 0 and the
371
+ # per-document factor is finite), so they are skipped — the same
372
+ # result the reference computes by adding 0. map/filter in C for
373
+ # speed: this is the per-query hot path.
374
+ vocab_get = self._vocab.get
375
+ qids = np.array(
376
+ [v for v in map(vocab_get, query) if v is not None], dtype=np.int32
377
+ )
378
+ return self._native_index.score(qids)
379
+ return self._reference_scores(query)
380
+
381
+ def get_scores_batch(self, queries):
382
+ """Score a batch of tokenized queries in one call.
383
+
384
+ Returns a float64 array of shape (len(queries), corpus_size); row i is
385
+ bit-identical to ``get_scores(queries[i])``. Batching amortizes FFI,
386
+ allocation, and token-mapping overhead across the batch. On the
387
+ fallback backend this simply loops the reference scorer.
388
+ """
389
+ if type(queries) is not list:
390
+ queries = list(queries)
391
+ if not queries:
392
+ return np.zeros((0, self.corpus_size), dtype=np.float64)
393
+ if self._native_index is not None:
394
+ ni = self._native_index
395
+ if ni.str_ok:
396
+ # Native string-token path: numpy encodes the batch into
397
+ # fixed-width byte slots in C, then one FFI call maps (in the
398
+ # kernel's vocab hash), packs and scores. In the arena's
399
+ # interleave pattern this avoids re-walking a megabyte-scale
400
+ # Python dict per call (the eviction tax dominates the M
401
+ # cell); the ~1us conversion premium is the tight-loop cost.
402
+ # Exactness guards: only `str` tokens may take this path —
403
+ # 'S' conversion would stringify anything else and could
404
+ # conflate distinct dict keys — and non-ASCII strings cannot
405
+ # encode to 'S'; both fall through (identical results).
406
+ try:
407
+ tokens_flat = [t for q in queries for t in q]
408
+ if not all(map(str.__instancecheck__, tokens_flat)):
409
+ raise UnsafeTokenError("non-str token in batch")
410
+ counts = np.array([len(q) for q in queries], dtype=np.int32)
411
+ tokens = (
412
+ np.asarray(tokens_flat, dtype="S")
413
+ if tokens_flat
414
+ else np.zeros((0,), dtype="S1")
415
+ )
416
+ return ni.score_batch_str(tokens, counts, len(queries))
417
+ except (UnsafeTokenError, UnicodeEncodeError):
418
+ pass # fall through to the id-mapping path for this batch
419
+ # Single pass: token ids and per-query offsets are accumulated
420
+ # into flat Python lists (list.extend over a map/filter runs at C
421
+ # speed), then converted with exactly two numpy calls — instead of
422
+ # building one small numpy array per query plus a concatenate and
423
+ # a cumsum, whose fixed dispatch costs dominate small batches.
424
+ # Unseen terms map to None and are skipped: they contribute
425
+ # exactly 0, the same result the reference computes by adding 0.
426
+ vocab_get = self._vocab.get
427
+ flat: list[int] = []
428
+ offsets = [0]
429
+ extend = flat.extend
430
+ add_offset = offsets.append
431
+ for query in queries:
432
+ extend(v for v in map(vocab_get, query) if v is not None)
433
+ add_offset(len(flat))
434
+ return ni.score_batch_flat(
435
+ np.array(flat, dtype=np.int32),
436
+ np.array(offsets, dtype=np.int64),
437
+ len(queries),
438
+ )
439
+ return np.array([self._reference_scores(query) for query in queries])
440
+
441
+ def _reference_scores(self, query):
442
+ raise NotImplementedError()
443
+
444
+ def get_batch_scores(self, query, doc_ids):
445
+ """Scores for a subset of documents. Per-document BM25 scores are
446
+ independent, so this is bit-identical to scoring everything and
447
+ selecting `doc_ids` (which also mirrors negative-index behaviour)."""
448
+ assert all(di < len(self.doc_freqs) for di in doc_ids)
449
+ return self.get_scores(query)[doc_ids].tolist()
450
+
451
+ def get_top_n(self, query, documents, n=5):
452
+ assert self.corpus_size == len(
453
+ documents
454
+ ), "The documents given don't match the index corpus!"
455
+ scores = self.get_scores(query)
456
+ top_n = np.argsort(scores)[::-1][:n]
457
+ return [documents[i] for i in top_n]
458
+
459
+
460
+ class BM25Okapi(BM25):
461
+ def __init__(self, corpus, tokenizer=None, k1=1.5, b=0.75, epsilon=0.25):
462
+ self.k1 = k1
463
+ self.b = b
464
+ self.epsilon = epsilon
465
+ super().__init__(corpus, tokenizer)
466
+
467
+ _variant = VARIANT_OKAPI
468
+
469
+ def _calc_idf(self, nd):
470
+ # Collect the idf sum for the average used by the epsilon floor, and
471
+ # the terms whose idf is negative (term in more than half the corpus).
472
+ idf_sum = 0
473
+ negative_idfs = []
474
+ for word, freq in nd.items():
475
+ idf = math.log(self.corpus_size - freq + 0.5) - math.log(freq + 0.5)
476
+ self.idf[word] = idf
477
+ idf_sum += idf
478
+ if idf < 0:
479
+ negative_idfs.append(word)
480
+ self.average_idf = idf_sum / len(self.idf)
481
+
482
+ eps = self.epsilon * self.average_idf
483
+ for word in negative_idfs:
484
+ self.idf[word] = eps
485
+
486
+ def _reference_scores(self, query):
487
+ return _reference.okapi_scores(
488
+ self.doc_freqs, self.idf, self.doc_len, self.avgdl, query, self.k1, self.b
489
+ )
490
+
491
+
492
+ class BM25L(BM25):
493
+ def __init__(self, corpus, tokenizer=None, k1=1.5, b=0.75, delta=0.5):
494
+ self.k1 = k1
495
+ self.b = b
496
+ self.delta = delta
497
+ super().__init__(corpus, tokenizer)
498
+
499
+ _variant = VARIANT_L
500
+
501
+ @property
502
+ def _delta(self):
503
+ return self.delta
504
+
505
+ def _calc_idf(self, nd):
506
+ for word, freq in nd.items():
507
+ idf = math.log(self.corpus_size + 1) - math.log(freq + 0.5)
508
+ self.idf[word] = idf
509
+
510
+ def _reference_scores(self, query):
511
+ return _reference.l_scores(
512
+ self.doc_freqs,
513
+ self.idf,
514
+ self.doc_len,
515
+ self.avgdl,
516
+ query,
517
+ self.k1,
518
+ self.b,
519
+ self.delta,
520
+ )
521
+
522
+
523
+ class BM25Plus(BM25):
524
+ def __init__(self, corpus, tokenizer=None, k1=1.5, b=0.75, delta=1):
525
+ self.k1 = k1
526
+ self.b = b
527
+ self.delta = delta
528
+ super().__init__(corpus, tokenizer)
529
+
530
+ _variant = VARIANT_PLUS
531
+
532
+ @property
533
+ def _delta(self):
534
+ return self.delta
535
+
536
+ def _calc_idf(self, nd):
537
+ for word, freq in nd.items():
538
+ # log of the quotient (not a difference of logs) — matches the
539
+ # reference's float result bit-for-bit.
540
+ idf = math.log((self.corpus_size + 1) / freq)
541
+ self.idf[word] = idf
542
+
543
+ def _reference_scores(self, query):
544
+ return _reference.plus_scores(
545
+ self.doc_freqs,
546
+ self.idf,
547
+ self.doc_len,
548
+ self.avgdl,
549
+ query,
550
+ self.k1,
551
+ self.b,
552
+ self.delta,
553
+ )
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.5
2
+ Name: bm25-mojo
3
+ Version: 0.2.5
4
+ Summary: Drop-in faster replacement for rank_bm25, powered by a Mojo kernel (pure-Python fallback included).
5
+ Project-URL: Repository, https://github.com/thyn-ai/mojo-kernels
6
+ Project-URL: Company, https://thyn.ai
7
+ Author: Thyn
8
+ Maintainer: Thyn
9
+ License-Expression: Apache-2.0
10
+ Keywords: bm25,information-retrieval,mojo,ranking,search
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Text Processing :: Indexing
15
+ Requires-Python: >=3.10
16
+ Requires-Dist: numpy>=1.21
17
+ Description-Content-Type: text/markdown
18
+
19
+ # bm25-mojo
20
+
21
+ A drop-in faster replacement for the [`rank_bm25`](https://pypi.org/project/rank_bm25/)
22
+ package, powered by a clean-room Mojo kernel — with a vendored pure-Python
23
+ fallback for platforms without a native build (including Windows — tested there in CI: [`windows-fallback`](https://github.com/thyn-ai/mojo-kernels/actions/workflows/windows-fallback.yml)).
24
+
25
+ ```python
26
+ from bm25_mojo import BM25Okapi # same API as rank_bm25.BM25Okapi
27
+
28
+ bm25 = BM25Okapi(tokenized_corpus)
29
+ scores = bm25.get_scores(tokenized_query) # np.ndarray, float64
30
+ top = bm25.get_top_n(tokenized_query, documents, n=5)
31
+ panel = bm25.get_scores_batch(list_of_queries) # batch API: bit-identical rows
32
+ ```
33
+
34
+ - **Same results**: scores match `rank_bm25` element-wise (last-ulp level;
35
+ the differential suite asserts agreement within 1e-8 on both the native and
36
+ fallback backends). `BM25Okapi`, `BM25L`, and `BM25Plus` are provided.
37
+ - **Much faster scoring**: the kernel walks postings lists with the
38
+ idf-weighted scores baked in at index time — 149x-13,137x faster
39
+ `get_scores` than rank_bm25, and **1.1x-1.95x faster than bm25s 0.3.11
40
+ (numba, its recommended config) across the whole 1k-100k doc grid** (Apple
41
+ M4 Max; full method and numbers in the repository README and
42
+ `benchmarks/AUTOPSY-bm25s.md`).
43
+ - **No toolchain needed**: per-platform wheels ship the compiled kernel.
44
+ Everywhere else the package transparently uses its pure-Python fallback.
45
+ - Force the fallback with `BM25_MOJO_DISABLE_NATIVE=1`; inspect the active
46
+ backend with `bm25_mojo.backend_info()`.
47
+
48
+ Source, benchmarks, and development: <https://github.com/thyn-ai/mojo-kernels>
49
+
50
+ License: Apache-2.0, © 2026 Algenta
@@ -0,0 +1,7 @@
1
+ bm25_mojo/__init__.py,sha256=fSvobRzd0oEEHWeANxr4Dh0bdcHKrprfawNnAMkaQ_A,905
2
+ bm25_mojo/_native.py,sha256=AjLQFAJ1a0JOss8JFbnU5W5PT5ZcPm_SYyZPtN4lT8k,22793
3
+ bm25_mojo/_reference.py,sha256=CsQMcJl50gHkadwC_RQ1cC-G12kLmpdo2mNTbsCTbYs,2854
4
+ bm25_mojo/core.py,sha256=Hl584zRVN43TU9nNCKgakOHa0qFAKo6unAUAVWnvuhE,21701
5
+ bm25_mojo-0.2.5.dist-info/METADATA,sha256=71_3-MHjahW4Atid9qJhNjRKwyDl5tTvhZDdjZlkAiM,2368
6
+ bm25_mojo-0.2.5.dist-info/WHEEL,sha256=THafob7ofN-NsuMN7Mg4qZyHaQI7KkD-QlcQatYhXPo,87
7
+ bm25_mojo-0.2.5.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.3
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any