perf(bm25): lower batch allocations -- 93.4% less peak memory (#4893)

## TL;DR

- Reduce peak memory in `BM25Scorer.score_batch` for 1,000 search
results.
- Keep corpus counts between two passes and reuse reason strings within
each batch.
- Peak allocation falls from 2,471,190 to 164,222 bytes, saving
2,306,968 bytes; runtime rises from 15.41 to 22.56 ms.
- `pytest tests/test_relevance.py tests/test_relevance_extra.py -k 'bm25
or BM25' -q`: 16 passed, 32 deselected.

## Description

The batch scorer kept every document's tokens until scoring finished. It
now keeps query-term document counts, then reads each document again for
scoring.

The score formula, document lengths, and query-term counts stay the
same. A small local dictionary also reuses equal result descriptions.

## Changes Made

- `headroom/relevance/bm25.py`: `BM25Scorer.score_batch` keeps only
query-term document counts in the first pass, then tokenizes each
document again in the scoring pass.
- `headroom/relevance/bm25.py`: a small per-batch dictionary reuses
equal reason strings.
- No public interface, setting, or test file changes.

## Validation

These results use the repository's search-result generator on Linux
x86_64 with Python 3.12.13 and `HEADROOM_OFFLINE=1`.
Memory means peak Python allocations during one batch, not process RSS.
Runtime rows show median times without allocation tracing.

| Situation | Before | After | Change |
|---|---|---|---|
| 1,000 search results, peak allocation | 2,471,190 bytes | 164,222
bytes | 93.4% less |
| 100 search results, runtime | 1.46824 ms | 2.28269 ms | 55.5% slower |
| 1,000 search results, runtime | 15.40643 ms | 22.55516 ms | 46.4%
slower |
| 100 results with empty query, runtime | 0.03821 ms | 0.03777 ms |
Unchanged path; no observed slowdown |
| Single result, runtime | 0.01296 ms | 0.01295 ms | Unchanged path; no
material difference |

Memory measurements across seven fixed inputs and three runs give:

| Statistic | Value |
|---|---|
| Old -> new (mean) | 2.4 MiB -> 160.4 KiB (93.4% less peak memory) |
| 95% CI of the new/old ratio (bootstrap, 10,000 resamples) |
0.066–0.067 (93.3–93.4% less peak memory) |
| Mean ± SD of the change per input | -2.2 MiB ± 1.7 KiB |
| 95% CI of the mean change (t-interval) | -2.2 MiB to -2.2 MiB |
| Number of fixed inputs (n) | 7 (3 runs) |

This is a memory-for-time tradeoff: repeated tokenization makes nonempty
batches slower.
The later pass releases each token list after scoring its document.

Run the repository benchmarks with:

```bash
HEADROOM_OFFLINE=1 python -m pytest benchmarks/bench_relevance.py::TestBM25Benchmarks -q
```

All seven benchmarks passed. An additional local comparison checked
8,568 combinations against the original implementation with exact
results.
Those combinations cover empty documents, repeated words, UUIDs,
Unicode, and different scoring settings.

## Why this is safe and easy to maintain

The change adds six net code lines and keeps one shared scoring formula.
Scores, result order, reasons, and matched terms remain unchanged for
the checked inputs.
Existing BM25 tests cover corpus IDF, matching, and normalization.

## Type of Change

- [x] Performance improvement

## Testing

- [x] Focused BM25 unit tests pass.
- [x] `ruff check headroom/relevance/bm25.py` passes.
- [x] `ruff format --check headroom/relevance/bm25.py` passes.
- [ ] Full unit suite passes.
- [ ] Type checking passes (`mypy headroom`).
- [ ] New repository tests added.

The broader relevance run reports 37 passed, eight skipped, and three
failed on both versions.
All three failures require the unavailable `headroom._core` extension in
SmartCrusher integration tests.
No new behavior or public interface is added; existing tests exercise
the changed path.

### Test Output

```text
$ HEADROOM_OFFLINE=1 pytest tests/test_relevance.py tests/test_relevance_extra.py -k 'bm25 or BM25' -q
====================== 16 passed, 32 deselected in 0.62s =======================

$ ruff check headroom/relevance/bm25.py && ruff format --check headroom/relevance/bm25.py
All checks passed!
1 file already formatted

$ HEADROOM_OFFLINE=1 python -m pytest benchmarks/bench_relevance.py::TestBM25Benchmarks -q
============================== 7 passed in 5.81s ===============================
```

## Real Behavior Proof

- Environment: Linux x86_64, Python 3.12.13, offline mode, no provider
or model needed.
- Exact command / steps: Run this direct scoring call after applying the
patch:

```bash
HEADROOM_OFFLINE=1 python -c 'from headroom.relevance.bm25 import BM25Scorer; s = BM25Scorer(); print([(r.score, r.matched_terms) for r in s.score_batch(["shared zeta", "shared alpha", "shared beta", "shared gamma"], "shared zeta")])'
```

- Observed result: The rare term ranks the first document higher:

```text
[(0.13093333199837626, ['shared', 'zeta']), (0.010536051565782637, ['shared']), (0.010536051565782637, ['shared']), (0.010536051565782637, ['shared'])]
```

- Not tested: Full application traffic, native-extension integration,
and other operating systems.

## Runtime Rollout Safety

- Rollout-managed feature(s): None; this is the pure Python BM25 scorer.
- Minimum rollout channel: Not applicable to this local scoring path.
- Stable/default behavior changed: Lower temporary memory use with
higher batch latency; scoring values are preserved.
- Kill switch / disable path: No new setting; use the previous
implementation if needed.
- Unsafe override required: No override is required.
- Qualification impact: No provider qualification changes.
- Rollback path: Revert this single-file change.

## Review Readiness

- [x] I have performed a self-review (automated source and result review
by a separate reviewer step; see AI assistance below).
- [x] Automated source and result checks completed.
- [x] This PR is ready for human review, with the latency tradeoff
stated above.

## Checklist

- [x] The modified file follows the project's style guidelines.
- [x] Source reviewed for duplicated scoring logic and unnecessary
complexity.
- [x] `CHANGELOG.md` was not edited.
- [ ] Full repository checks completed.

## AI assistance

This PR was prepared with AI assistance from Aiden. Candidates were
tracked with Weco Observe.

Weco share link:
https://dashboard.weco.ai/share/Y27llB_ia4h2OzafJay18VxKVJ0L4m8I

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4893"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

Co-authored-by: Aiden <aiden@weco.ai>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
Dex Hünter
2026-11-16 23:49:54 -06:00
committed by GitHub
co-authored by Aiden JD Davis
parent c8168a0aa0
commit cb8414cc73
+18 -12
View File
@@ -242,19 +242,23 @@ class BM25Scorer(RelevanceScorer):
# redo identical work per item.
context_freq = Counter(context_tokens)
# Compute average document length for normalization
all_tokens = [self._tokenize(item) for item in items]
avg_len = sum(len(t) for t in all_tokens) / max(len(items), 1)
# Retain corpus statistics, not the tokens for the entire batch.
total_len = 0
n_docs = 0
doc_freq_across: Counter[str] = Counter()
for item in items:
tokens = self._tokenize(item)
total_len += len(tokens)
n_docs += 1
doc_freq_across.update({token for token in tokens if token in context_freq})
del tokens
avg_len = total_len / max(len(items), 1)
# Compute corpus IDF per query term. Unlike single-item scoring,
# a batch is a real corpus, so document frequency is meaningful:
# terms that appear in many items are down-weighted while rare,
# discriminative terms (IDs, UUIDs) are boosted. This is what makes
# the ranking BM25 rather than plain term-frequency weighting.
n_docs = len(all_tokens)
doc_freq_across: Counter[str] = Counter()
for tokens in all_tokens:
doc_freq_across.update(set(tokens))
idf_map = {
term: self._compute_idf(term, n_docs, doc_freq_across[term])
for term in set(context_tokens)
@@ -262,7 +266,9 @@ class BM25Scorer(RelevanceScorer):
}
results = []
for item_tokens in all_tokens:
reasons = {0: "BM25: no matches"}
for item in items:
item_tokens = self._tokenize(item)
raw_score, matched = self._bm25_score(
item_tokens,
context_tokens,
@@ -270,6 +276,7 @@ class BM25Scorer(RelevanceScorer):
idf_map=idf_map,
query_freq=context_freq,
)
del item_tokens
# Normalize
if self.normalize_score:
@@ -283,10 +290,9 @@ class BM25Scorer(RelevanceScorer):
normalized = min(1.0, normalized + 0.3)
match_count = len(matched)
if match_count == 0:
reason = "BM25: no matches"
else:
reason = f"BM25: {match_count} terms"
if match_count not in reasons:
reasons[match_count] = f"BM25: {match_count} terms"
reason = reasons[match_count]
results.append(
RelevanceScore(