Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Extract MMR diversity re-ranking into a standalone MMRRanker

Daoud Clarkef222d72537ef
diff --git a/mwmbl/rankeval/evaluation/evaluate_remote.py b/mwmbl/rankeval/evaluation/evaluate_remote.py
index d74111f..20aa783 100644
--- a/mwmbl/rankeval/evaluation/evaluate_remote.py
+++ b/mwmbl/rankeval/evaluation/evaluate_remote.py
@@ -13,6 +13,7 @@ from mwmbl.rankeval.paths import MODEL_PATH, RUST_MODEL_PATH
from mwmbl.tinysearchengine.indexer import TinyIndex, Document
from mwmbl.tinysearchengine.ltr import RustXGBPipeline
from mwmbl.tinysearchengine.ltr_rank import LTRRanker
+from mwmbl.tinysearchengine.mmr_rank import MMRRanker
from mwmbl.tinysearchengine.rank import Ranker, HeuristicRanker, HeuristicAndWikiRanker
from mwmbl.rankeval.evaluation.evaluate import RankingModel, evaluate
@@ -32,7 +33,8 @@ def run():
# model = pickle.load(open(MODEL_PATH, 'rb'))
model = RustXGBPipeline.from_model_path(str(RUST_MODEL_PATH))
- ranker = LTRRanker(RemoteIndex(), DummyCompleter(), model, True, 3)
+ ranker = MMRRanker(LTRRanker(RemoteIndex(), DummyCompleter(), model, True, 3))
+ # ranker = LTRRanker(RemoteIndex(), DummyCompleter(), model, True, 3) # MMR off
# ranker = HeuristicRanker(RemoteIndex(), DummyCompleter())
# ranker = HeuristicAndWikiRanker(RemoteIndex(), DummyCompleter(), max_wiki_results=3)
model = MwmblRankingModel(ranker)
diff --git a/mwmbl/search_setup.py b/mwmbl/search_setup.py
index 0a5f409..7a6786c 100644
--- a/mwmbl/search_setup.py
+++ b/mwmbl/search_setup.py
@@ -12,6 +12,7 @@ from mwmbl.tinysearchengine.completer import Completer
from mwmbl.tinysearchengine.indexer import TinyIndex, Document
from mwmbl.tinysearchengine.ltr import RustXGBPipeline
from mwmbl.tinysearchengine.ltr_rank import LTRRanker
+from mwmbl.tinysearchengine.mmr_rank import MMRRanker
from mwmbl.tinysearchengine.rank import HeuristicAndWikiRanker
CURATED_DOMAINS_CACHE_KEY = "curated-domains"
@@ -34,8 +35,8 @@ tiny_index = TinyIndex(item_factory=Document, index_path=index_path)
tiny_index.__enter__()
ltr_model = RustXGBPipeline.from_model_path(str(settings.RUST_MODEL_PATH))
-# Diversity (one-time-only-per-domain) is handled inside LTRRanker via MMR re-ranking,
-# which demotes rather than drops same-domain results.
-ranker = LTRRanker(tiny_index, completer, ltr_model, include_wiki=True, num_wiki_results=3)
+# Diversity is applied by the wrapping MMRRanker, which demotes (rather than drops)
+# same-domain / near-duplicate results. Unwrap to disable diversity.
+ranker = MMRRanker(LTRRanker(tiny_index, completer, ltr_model, include_wiki=True, num_wiki_results=3))
batch_cache = BatchCache(Path(settings.DATA_PATH) / settings.BATCH_DIR_NAME)
diff --git a/mwmbl/tinysearchengine/ltr_rank.py b/mwmbl/tinysearchengine/ltr_rank.py
index a19cfc8..cca1bc0 100644
--- a/mwmbl/tinysearchengine/ltr_rank.py
+++ b/mwmbl/tinysearchengine/ltr_rank.py
@@ -4,10 +4,6 @@ LTR (Learning-to-Rank) ranker that uses the Rust XGBoost pipeline for scoring.
LTRRanker accepts any model with a sklearn-compatible predict(DataFrame) interface,
including both the Python sklearn pipeline and the Rust RustXGBPipeline.
"""
-import math
-from collections import Counter
-from urllib.parse import urlparse
-
import numpy as np
from pandas import DataFrame
from sklearn.base import BaseEstimator
@@ -15,73 +11,6 @@ from sklearn.base import BaseEstimator
from mwmbl.tinysearchengine.completer import Completer
from mwmbl.tinysearchengine.indexer import Document, TinyIndex
from mwmbl.tinysearchengine.rank import Ranker, get_wiki_results
-from mwmbl.tokenizer import tokenize
-
-
-# Maximal Marginal Relevance (MMR) diversity parameters, applied in order_results.
-# MMR re-orders the relevance-sorted candidates so near-duplicate / same-domain
-# results are demoted rather than dropped (the big search engines diversify the
-# list instead of hard-capping one result per domain).
-MMR_LAMBDA = 0.7 # weight on relevance vs. diversity (1.0 = pure relevance, 0.0 = max diversity)
-DOMAIN_SIMILARITY_WEIGHT = 0.8 # within the kernel: weight on same-domain vs. text overlap
-MMR_WINDOW = 50 # only diversify the top candidates; the long tail keeps relevance order
-
-
-def _normalized_bow(doc: Document) -> dict[str, float]:
- """L2-normalised bag-of-words over title + extract, so cosine is a plain dot product."""
- counts = Counter(tokenize(f"{doc.title or ''} {doc.extract or ''}"))
- if not counts:
- return {}
- norm = math.sqrt(sum(c * c for c in counts.values()))
- return {token: count / norm for token, count in counts.items()}
-
-
-def _text_cosine(a: dict[str, float], b: dict[str, float]) -> float:
- # a and b are already L2-normalised, so the sparse dot product is the cosine.
- if len(a) > len(b):
- a, b = b, a
- return sum(weight * b[token] for token, weight in a.items() if token in b)
-
-
-def mmr_rerank(ranked_pages: list[Document]) -> list[Document]:
- """Re-order a relevance-sorted list to demote near-duplicate / same-domain results.
-
- Greedy Maximal Marginal Relevance with a domain-dominant kernel
- (sim = w_domain * same_domain + (1 - w_domain) * bag-of-words cosine). Relevance is
- rank-based (scale-invariant): the i-th most relevant page has relevance
- (window - i) / window, so it does not depend on the model's compressed score
- magnitudes. Each candidate is discounted by its greatest similarity to an
- already-selected page, so e.g. the second result from a domain sinks below fresher
- domains but is never dropped.
-
- Only the top MMR_WINDOW candidates are diversified (O(window^2)); the long tail,
- which is rarely seen, keeps plain relevance order so the cost stays bounded.
- """
- n = len(ranked_pages)
- if n <= 2:
- return ranked_pages
-
- window = min(n, MMR_WINDOW)
- head, tail = ranked_pages[:window], ranked_pages[window:]
-
- relevance = [(window - i) / window for i in range(window)]
- bows = [_normalized_bow(p) for p in head]
- netlocs = [urlparse(p.url).netloc for p in head]
-
- remaining = set(range(window))
- max_sim = [0.0] * window
- selected: list[int] = []
- while remaining:
- best = max(remaining, key=lambda i: MMR_LAMBDA * relevance[i] - (1 - MMR_LAMBDA) * max_sim[i])
- selected.append(best)
- remaining.discard(best)
- best_bow, best_netloc = bows[best], netlocs[best]
- for j in remaining:
- domain_sim = DOMAIN_SIMILARITY_WEIGHT if best_netloc and best_netloc == netlocs[j] else 0.0
- sim = domain_sim + (1 - DOMAIN_SIMILARITY_WEIGHT) * _text_cosine(best_bow, bows[j])
- if sim > max_sim[j]:
- max_sim[j] = sim
- return [head[i] for i in selected] + tail
class LTRRanker(Ranker):
@@ -145,11 +74,9 @@ class LTRRanker(Ranker):
if len(filtered_pages) == 0:
return []
- # Sort by model relevance, then re-order with MMR to diversify the list
- # (demotes same-domain / near-duplicate results instead of dropping them).
+ # Sort by model relevance (descending).
indices = np.argsort(filtered_predictions)[::-1]
- ranked_pages = filtered_pages[indices].tolist()
- return mmr_rerank(ranked_pages)
+ return filtered_pages[indices].tolist()
def external_search(self, query: str) -> list[Document]:
if self.include_wiki:
diff --git a/mwmbl/tinysearchengine/mmr_rank.py b/mwmbl/tinysearchengine/mmr_rank.py
new file mode 100644
index 0000000..3659980
--- /dev/null
+++ b/mwmbl/tinysearchengine/mmr_rank.py
@@ -0,0 +1,99 @@
+"""
+Maximal Marginal Relevance (MMR) diversity re-ranking.
+
+MMRRanker is a decorator that wraps any Ranker and re-orders its relevance-sorted
+search() output so near-duplicate / same-domain results are demoted rather than dropped
+(the big search engines diversify the list instead of hard-capping one result per domain).
+It can wrap any ranker (LTRRanker, HeuristicRanker, ...), which also makes it easy to
+evaluate a ranker with and without diversity.
+"""
+import math
+from collections import Counter
+from urllib.parse import urlparse
+
+from mwmbl.tinysearchengine.indexer import Document
+from mwmbl.tinysearchengine.rank import Ranker
+from mwmbl.tokenizer import tokenize
+
+
+# MMR tuning parameters.
+MMR_LAMBDA = 0.7 # weight on relevance vs. diversity (1.0 = pure relevance, 0.0 = max diversity)
+DOMAIN_SIMILARITY_WEIGHT = 0.8 # within the kernel: weight on same-domain vs. text overlap
+MMR_WINDOW = 50 # only diversify the top candidates; the long tail keeps relevance order
+
+
+def _normalized_bow(doc: Document) -> dict[str, float]:
+ """L2-normalised bag-of-words over title + extract, so cosine is a plain dot product."""
+ counts = Counter(tokenize(f"{doc.title or ''} {doc.extract or ''}"))
+ if not counts:
+ return {}
+ norm = math.sqrt(sum(c * c for c in counts.values()))
+ return {token: count / norm for token, count in counts.items()}
+
+
+def _text_cosine(a: dict[str, float], b: dict[str, float]) -> float:
+ # a and b are already L2-normalised, so the sparse dot product is the cosine.
+ if len(a) > len(b):
+ a, b = b, a
+ return sum(weight * b[token] for token, weight in a.items() if token in b)
+
+
+def mmr_rerank(ranked_pages: list[Document]) -> list[Document]:
+ """Re-order a relevance-sorted list to demote near-duplicate / same-domain results.
+
+ Greedy Maximal Marginal Relevance with a domain-dominant kernel
+ (sim = w_domain * same_domain + (1 - w_domain) * bag-of-words cosine). Relevance is
+ rank-based (scale-invariant): the i-th most relevant page has relevance
+ (window - i) / window, so it does not depend on the model's compressed score
+ magnitudes. Each candidate is discounted by its greatest similarity to an
+ already-selected page, so e.g. the second result from a domain sinks below fresher
+ domains but is never dropped.
+
+ Only the top MMR_WINDOW candidates are diversified (O(window^2)); the long tail,
+ which is rarely seen, keeps plain relevance order so the cost stays bounded.
+ """
+ n = len(ranked_pages)
+ if n <= 2:
+ return ranked_pages
+
+ window = min(n, MMR_WINDOW)
+ head, tail = ranked_pages[:window], ranked_pages[window:]
+
+ relevance = [(window - i) / window for i in range(window)]
+ bows = [_normalized_bow(p) for p in head]
+ netlocs = [urlparse(p.url).netloc for p in head]
+
+ remaining = set(range(window))
+ max_sim = [0.0] * window
+ selected: list[int] = []
+ while remaining:
+ best = max(remaining, key=lambda i: MMR_LAMBDA * relevance[i] - (1 - MMR_LAMBDA) * max_sim[i])
+ selected.append(best)
+ remaining.discard(best)
+ best_bow, best_netloc = bows[best], netlocs[best]
+ for j in remaining:
+ domain_sim = DOMAIN_SIMILARITY_WEIGHT if best_netloc and best_netloc == netlocs[j] else 0.0
+ sim = domain_sim + (1 - DOMAIN_SIMILARITY_WEIGHT) * _text_cosine(best_bow, bows[j])
+ if sim > max_sim[j]:
+ max_sim[j] = sim
+ return [head[i] for i in selected] + tail
+
+
+class MMRRanker:
+ """Decorator that applies MMR diversity re-ranking to a wrapped ranker's results.
+
+ Demotes (never drops) same-domain / near-duplicate results. Delegates completion and
+ raw retrieval unchanged.
+ """
+
+ def __init__(self, ranker: Ranker):
+ self.ranker = ranker
+
+ def search(self, s: str, additional_results: list[Document]) -> list[Document]:
+ return mmr_rerank(self.ranker.search(s, additional_results))
+
+ def complete(self, q: str):
+ return self.ranker.complete(q)
+
+ def get_raw_results(self, query: str):
+ return self.ranker.get_raw_results(query)
diff --git a/test/test_ltr_rank.py b/test/test_mmr_rank.py
similarity index 61%
rename from test/test_ltr_rank.py
rename to test/test_mmr_rank.py
index b6a6627..11befbc 100644
--- a/test/test_ltr_rank.py
+++ b/test/test_mmr_rank.py
@@ -1,5 +1,5 @@
from mwmbl.tinysearchengine.indexer import Document
-from mwmbl.tinysearchengine.ltr_rank import MMR_WINDOW, mmr_rerank
+from mwmbl.tinysearchengine.mmr_rank import MMR_WINDOW, MMRRanker, mmr_rerank
def _doc(title, url, extract=""):
@@ -54,3 +54,46 @@ def test_mmr_caps_work_to_window_and_keeps_tail():
assert {p.url for p in reranked} == {p.url for p in pages}
# The tail past the window is untouched.
assert reranked[MMR_WINDOW:] == pages[MMR_WINDOW:]
+
+
+class _FakeRanker:
+ """Minimal ranker stub exposing the methods MMRRanker delegates to."""
+
+ def __init__(self, results):
+ self._results = results
+ self.completed = None
+ self.raw_queried = None
+
+ def search(self, s, additional_results):
+ self.searched = (s, additional_results)
+ return self._results
+
+ def complete(self, q):
+ self.completed = q
+ return ["completion"]
+
+ def get_raw_results(self, query):
+ self.raw_queried = query
+ return ["raw"]
+
+
+def test_mmrranker_reranks_wrapped_search_output():
+ # The wrapped ranker returns results in relevance order: two same-domain then a
+ # fresh domain. MMRRanker should demote the second same-domain result below it.
+ a = _doc("Alpha repo", "https://github.com/x/alpha", "alpha project")
+ b = _doc("Beta repo", "https://github.com/x/beta", "beta project")
+ c = _doc("Gamma site", "https://example.org/gamma", "gamma encyclopedia entry")
+ ranker = MMRRanker(_FakeRanker([a, b, c]))
+
+ urls = [p.url for p in ranker.search("q", [])]
+ assert urls[0] == a.url
+ assert urls.index(c.url) < urls.index(b.url)
+
+
+def test_mmrranker_delegates_complete_and_raw_results():
+ fake = _FakeRanker([])
+ ranker = MMRRanker(fake)
+ assert ranker.complete("foo") == ["completion"]
+ assert fake.completed == "foo"
+ assert ranker.get_raw_results("bar") == ["raw"]
+ assert fake.raw_queried == "bar"