Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Wire per-source reward EMA into the contribution_ema feature

Daoud Clarke6c090c235301
diff --git a/mwmbl/tinysearchengine/super_search.py b/mwmbl/tinysearchengine/super_search.py
index 6b7a40a..423f20d 100644
--- a/mwmbl/tinysearchengine/super_search.py
+++ b/mwmbl/tinysearchengine/super_search.py
@@ -49,6 +49,7 @@ from mwmbl.tinysearchengine.mmr_rank import mmr_rerank
from mwmbl.tinysearchengine.rank import score_result_whole
from mwmbl.tinysearchengine.super_search_sources import SOURCES
from mwmbl.tinysearchengine.super_search_select import bandit as ss_bandit
+from mwmbl.tinysearchengine.super_search_select import rstats as ss_rstats
from mwmbl.tinysearchengine.super_search_select import judge as ss_judge
from mwmbl.tinysearchengine.super_search_select import profiles as ss_profiles
from mwmbl.tinysearchengine.super_search_select.policy import select_sources
@@ -552,6 +553,12 @@ async def _record_rewards(ctx: SelectionContext, last_results_key: list) -> None
await asyncio.to_thread(log_impression, ctx, rewards)
except Exception:
logger.exception("super-search failed to record rewards")
+ try:
+ # Per-source reward EMA: the online stat behind the contribution_ema
+ # feature (aggregate per source, nothing query-derived).
+ await asyncio.to_thread(ss_rstats.update, rewards)
+ except Exception:
+ logger.exception("super-search failed to update reward stats")
try:
await asyncio.to_thread(record_source_provenance, ctx)
except Exception:
diff --git a/mwmbl/tinysearchengine/super_search_select/evaluation.py b/mwmbl/tinysearchengine/super_search_select/evaluation.py
index bdc4388..7993475 100644
--- a/mwmbl/tinysearchengine/super_search_select/evaluation.py
+++ b/mwmbl/tinysearchengine/super_search_select/evaluation.py
@@ -235,20 +235,34 @@ def simulate_xgb(matrix: RewardMatrix, k: int, epsilon: float,
(source, reward) pairs have accumulated, selection uses the cosine
baseline (matching how real impression logs bootstrap), after which the
model is fit and refit every ``refit_every`` queries.
+
+ The per-source reward EMA (the online stat behind ``contribution_ema``,
+ kept in Redis in production) is recomputed along the replay and injected
+ into that feature slot at decision time, exactly as serving would see it.
"""
from mwmbl.tinysearchengine.super_search_select import xgb_model
+ from mwmbl.tinysearchengine.super_search_select.rstats import DECAY
rng = np.random.default_rng(seed)
- Q = matrix.X.shape[0]
+ Q, S, _ = matrix.X.shape
vocab = xgb_model.build_vocab(matrix.sources)
vocab_index = {name: i for i, name in enumerate(vocab)}
cos_i = matrix.feature_names.index("cos_bow")
+ ema_i = matrix.feature_names.index("contribution_ema")
+ ema = np.zeros(S)
+ ema_seen = np.zeros(S, dtype=bool)
model = None
xs: list[np.ndarray] = []
ys: list[float] = []
captured = 0.0
since_fit = 0
+
+ def encode(q: int, s: int) -> np.ndarray:
+ x = matrix.X[q, s].copy()
+ x[ema_i] = ema[s]
+ return xgb_model.encode(x, matrix.sources[s], vocab_index)
+
for q in rng.permutation(Q):
avail = np.where(matrix.mask[q])[0]
if avail.size == 0:
@@ -257,8 +271,7 @@ def simulate_xgb(matrix: RewardMatrix, k: int, epsilon: float,
if model is None:
chosen = avail[np.argsort(matrix.X[q, avail, cos_i])[::-1][:k_q]]
else:
- enc = np.stack([xgb_model.encode(matrix.X[q, s], matrix.sources[s], vocab_index)
- for s in avail])
+ enc = np.stack([encode(q, s) for s in avail])
ranked = avail[np.argsort(model.predict(enc))[::-1]]
n_explore = int(rng.binomial(k_q, epsilon))
chosen = list(ranked[:k_q - n_explore])
@@ -267,9 +280,13 @@ def simulate_xgb(matrix: RewardMatrix, k: int, epsilon: float,
chosen += list(rng.choice(rest, size=min(n_explore, rest.size), replace=False))
chosen = np.asarray(chosen)
for s in chosen:
- xs.append(xgb_model.encode(matrix.X[q, s], matrix.sources[s], vocab_index))
+ xs.append(encode(q, s))
ys.append(float(matrix.R[q, s]))
captured += matrix.R[q, s]
+ for s in chosen:
+ r = float(matrix.R[q, s])
+ ema[s] = r if not ema_seen[s] else (1.0 - DECAY) * ema[s] + DECAY * r
+ ema_seen[s] = True
since_fit += 1
if len(ys) >= min_rows and (model is None or since_fit >= refit_every):
model = xgb_model.train(np.stack(xs), np.asarray(ys), params=params)
@@ -378,11 +395,25 @@ def evaluate_holdout(matrix: RewardMatrix, k: int = 10, test_frac: float = 0.2,
vocab = xgb_model.build_vocab(matrix.sources)
vocab_index = {name: i for i, name in enumerate(vocab)}
+ # Serve-time analog of the per-source reward EMA (rstats): each source's
+ # mean train-split reward, injected into the contribution_ema slot for
+ # both splits so the model can use the online stat it will see live.
+ ema_i = matrix.feature_names.index("contribution_ema")
+ train_mask = np.zeros(len(matrix.queries), dtype=bool)
+ train_mask[train_idx] = True
+ seen = matrix.mask & train_mask[:, None]
+ with np.errstate(invalid="ignore"):
+ source_mean = np.where(seen.sum(axis=0) > 0,
+ (matrix.R * seen).sum(axis=0) / np.maximum(seen.sum(axis=0), 1),
+ 0.0)
+
def rows_for(idx: np.ndarray):
xs, ys, cells = [], [], []
for q in idx:
for s in np.where(matrix.mask[q])[0]:
- xs.append(xgb_model.encode(matrix.X[q, s], matrix.sources[s], vocab_index))
+ x = matrix.X[q, s].copy()
+ x[ema_i] = source_mean[s]
+ xs.append(xgb_model.encode(x, matrix.sources[s], vocab_index))
ys.append(float(matrix.R[q, s]))
cells.append((q, s))
return np.stack(xs), np.asarray(ys), cells
diff --git a/mwmbl/tinysearchengine/super_search_select/features.py b/mwmbl/tinysearchengine/super_search_select/features.py
index e4d0243..95f3905 100644
--- a/mwmbl/tinysearchengine/super_search_select/features.py
+++ b/mwmbl/tinysearchengine/super_search_select/features.py
@@ -130,8 +130,9 @@ class QueryContext:
@dataclass
class SiteStats:
- """Online per-site stats used as features (read from Redis; defaults for cold sites)."""
- contribution_ema: float = 0.0 # mean fraction of results surviving into top-K
+ """Online per-site stats used as features (read from Redis via ``rstats``;
+ defaults for cold sites)."""
+ contribution_ema: float = 0.0 # EMA of the source's per-request reward (judge score)
latency_ema: float = 0.0 # mean response time, seconds
failure_rate: float = 0.0 # fraction of recent queries that errored/timed out
diff --git a/mwmbl/tinysearchengine/super_search_select/policy.py b/mwmbl/tinysearchengine/super_search_select/policy.py
index 52d2e83..3a8973d 100644
--- a/mwmbl/tinysearchengine/super_search_select/policy.py
+++ b/mwmbl/tinysearchengine/super_search_select/policy.py
@@ -23,10 +23,9 @@ import random
import numpy as np
from django.conf import settings
-from mwmbl.tinysearchengine.super_search_select import bandit, profiles, xgb_model
+from mwmbl.tinysearchengine.super_search_select import bandit, profiles, rstats, xgb_model
from mwmbl.tinysearchengine.super_search_select.features import (
QueryContext,
- SiteStats,
cosine_relevance,
feature_vector,
)
@@ -69,7 +68,8 @@ def select_sources(
bow, cng = profiles.get_query_vectors(query)
qctx = QueryContext.build(query, bow, cng)
profs = profiles.get_profiles(selectable)
- feats = {n: feature_vector(qctx, get_meta(n), profs[n]) for n in selectable}
+ stats = rstats.get_stats(selectable)
+ feats = {n: feature_vector(qctx, get_meta(n), profs[n], stats[n]) for n in selectable}
mode = settings.SUPER_SEARCH_SELECTION_MODE
if mode == "xgb":
@@ -82,13 +82,15 @@ def select_sources(
raise ValueError(f"unknown SUPER_SEARCH_SELECTION_MODE {mode!r}")
if ctx is not None:
+ pinned_stats = rstats.get_stats([n for n in pinned if n not in feats])
for name in pinned + chosen:
if name in feats:
ctx.features[name] = feats[name].tolist()
elif name not in ctx.features:
# pinned sources weren't scored; compute their features too.
ctx.features[name] = feature_vector(
- qctx, get_meta(name), profs.get(name, (None, None))
+ qctx, get_meta(name), profs.get(name, (None, None)),
+ pinned_stats.get(name),
).tolist()
return pinned + chosen
@@ -143,7 +145,8 @@ def _record_features(ctx: SelectionContext, query: str, names: list[str]) -> Non
bow, cng = profiles.get_query_vectors(query)
qctx = QueryContext.build(query, bow, cng)
profs = profiles.get_profiles(names)
+ stats = rstats.get_stats(names)
for name in names:
ctx.features[name] = feature_vector(
- qctx, get_meta(name), profs.get(name, (None, None)), SiteStats()
+ qctx, get_meta(name), profs.get(name, (None, None)), stats.get(name)
).tolist()
diff --git a/mwmbl/tinysearchengine/super_search_select/rstats.py b/mwmbl/tinysearchengine/super_search_select/rstats.py
new file mode 100644
index 0000000..370f223
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_select/rstats.py
@@ -0,0 +1,57 @@
+"""Online per-source reward statistics in Redis.
+
+Keeps a decaying mean (EMA) of each source's per-request reward — the judge
+score its results earn — and serves it back as the ``contribution_ema``
+feature. This is the per-arm running mean that a per-request-updated bandit
+(LinTS) learns through its intercept; exposing it as a *feature* gives the
+batch-trained xgb model the same online signal without per-request model
+updates, and lets its trees interact it with the rest of the context.
+
+Aggregate per-source statistics only — nothing query-derived is stored here.
+"""
+from __future__ import annotations
+
+import redis
+from django.conf import settings
+
+from mwmbl.tinysearchengine.super_search_select.features import SiteStats
+
+_REWARD_EMA = "ss:rstat:reward:{site}"
+
+# Weight of the newest observation. Matches the content-profile decay ethos:
+# slow enough to be stable, fast enough to track a source going stale.
+DECAY = 0.1
+
+_redis: redis.Redis | None = None
+
+
+def _get_redis() -> redis.Redis:
+ global _redis
+ if _redis is None:
+ _redis = redis.from_url(settings.REDIS_URL)
+ return _redis
+
+
+def get_stats(sites: list[str]) -> dict[str, SiteStats]:
+ """Per-source online stats; zeros for sources never rewarded (cold)."""
+ r = _get_redis()
+ pipe = r.pipeline()
+ for site in sites:
+ pipe.get(_REWARD_EMA.format(site=site))
+ values = pipe.execute()
+ return {
+ site: SiteStats(contribution_ema=float(v) if v is not None else 0.0)
+ for site, v in zip(sites, values)
+ }
+
+
+def update(rewards: dict[str, float]) -> None:
+ """Fold one request's per-source rewards into the EMAs."""
+ r = _get_redis()
+ pipe = r.pipeline()
+ keys = [_REWARD_EMA.format(site=site) for site in rewards]
+ old = r.mget(keys) if keys else []
+ for (site, reward), prev in zip(rewards.items(), old):
+ ema = reward if prev is None else (1.0 - DECAY) * float(prev) + DECAY * float(reward)
+ pipe.set(_REWARD_EMA.format(site=site), repr(float(ema)))
+ pipe.execute()
diff --git a/test/test_super_search_bandit.py b/test/test_super_search_bandit.py
index 1b1a28a..dc59114 100644
--- a/test/test_super_search_bandit.py
+++ b/test/test_super_search_bandit.py
@@ -3,7 +3,7 @@ import fakeredis
import numpy as np
import pytest
-from mwmbl.tinysearchengine.super_search_select import bandit, policy, profiles
+from mwmbl.tinysearchengine.super_search_select import bandit, policy, profiles, rstats
from mwmbl.tinysearchengine.super_search_select.features import NUM_FEATURES
from mwmbl.tinysearchengine.super_search_select.rewards import SelectionContext
@@ -110,6 +110,7 @@ def test_policy_bandit_branch_selects_and_records_features(monkeypatch):
r = fakeredis.FakeRedis()
monkeypatch.setattr(bandit, "_redis", r)
monkeypatch.setattr(profiles, "_redis", r)
+ monkeypatch.setattr(rstats, "_redis", r)
monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_SELECTION_MODE", "lints")
names = ["mwmbl", "hn"] + [f"site{i}" for i in range(20)]
diff --git a/test/test_super_search_xgb.py b/test/test_super_search_xgb.py
index f9fb64f..b0ade4e 100644
--- a/test/test_super_search_xgb.py
+++ b/test/test_super_search_xgb.py
@@ -5,7 +5,7 @@ import fakeredis
import numpy as np
import pytest
-from mwmbl.tinysearchengine.super_search_select import policy, profiles, xgb_model
+from mwmbl.tinysearchengine.super_search_select import policy, profiles, rstats, xgb_model
from mwmbl.tinysearchengine.super_search_select.evaluation import RewardMatrix
from mwmbl.tinysearchengine.super_search_select.features import (
FEATURE_NAMES,
@@ -210,7 +210,9 @@ def test_get_model_hot_reloads_after_retrain(tmp_path, monkeypatch):
@pytest.fixture
def xgb_policy_env(tmp_path, monkeypatch):
"""xgb selection mode with a toy artifact trained over the policy's sources."""
- monkeypatch.setattr(profiles, "_redis", fakeredis.FakeRedis())
+ r = fakeredis.FakeRedis()
+ monkeypatch.setattr(profiles, "_redis", r)
+ monkeypatch.setattr(rstats, "_redis", r)
monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_SELECTION_MODE", "xgb")
monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_XGB_MODEL_DIR", str(tmp_path))
names = ["mwmbl", "hn"] + [f"site{i}" for i in range(20)]
@@ -248,7 +250,9 @@ def test_policy_xgb_full_explore_still_valid(xgb_policy_env, monkeypatch):
def test_policy_xgb_missing_artifact_raises(monkeypatch, tmp_path):
- monkeypatch.setattr(profiles, "_redis", fakeredis.FakeRedis())
+ r = fakeredis.FakeRedis()
+ monkeypatch.setattr(profiles, "_redis", r)
+ monkeypatch.setattr(rstats, "_redis", r)
monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_SELECTION_MODE", "xgb")
monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_XGB_MODEL_DIR",
str(tmp_path / "empty"))
@@ -259,13 +263,50 @@ def test_policy_xgb_missing_artifact_raises(monkeypatch, tmp_path):
def test_policy_unknown_mode_raises(monkeypatch):
- monkeypatch.setattr(profiles, "_redis", fakeredis.FakeRedis())
+ r = fakeredis.FakeRedis()
+ monkeypatch.setattr(profiles, "_redis", r)
+ monkeypatch.setattr(rstats, "_redis", r)
monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_SELECTION_MODE", "bogus")
names = ["mwmbl", "hn"] + [f"site{i}" for i in range(20)]
with pytest.raises(ValueError, match="SUPER_SEARCH_SELECTION_MODE"):
policy.select_sources("some query", names, k=5)
+# ---------------------------------------------------------------------------
+# Online per-source reward EMA (rstats -> contribution_ema feature)
+# ---------------------------------------------------------------------------
+
+def fake_rstats_redis(monkeypatch):
+ r = fakeredis.FakeRedis()
+ monkeypatch.setattr(rstats, "_redis", r)
+ return r
+
+
+def test_rstats_cold_source_is_zero(fake_rstats_redis):
+ assert rstats.get_stats(["never_seen"])["never_seen"].contribution_ema == 0.0
+
+
+def test_rstats_ema_tracks_rewards(fake_rstats_redis):
+ rstats.update({"a": 1.0, "b": 0.0})
+ assert rstats.get_stats(["a"])["a"].contribution_ema == pytest.approx(1.0)
+ rstats.update({"a": 0.0})
+ ema = rstats.get_stats(["a", "b"])
+ assert ema["a"].contribution_ema == pytest.approx(1.0 - rstats.DECAY)
+ assert ema["b"].contribution_ema == pytest.approx(0.0)
+
+
+def test_rstats_feeds_selection_features(fake_rstats_redis, monkeypatch):
+ monkeypatch.setattr(profiles, "_redis", fake_rstats_redis)
+ rstats.update({"site0": 0.8})
+ ema_i = FEATURE_NAMES.index("contribution_ema")
+ ctx = SelectionContext()
+ names = ["mwmbl", "hn"] + [f"site{i}" for i in range(20)]
+ policy.select_sources("some query", names, k=len(names), ctx=ctx) # small-fanout path
+ assert ctx.features["site0"][ema_i] == pytest.approx(0.8)
+ assert ctx.features["site1"][ema_i] == 0.0
+
+
# ---------------------------------------------------------------------------
# Online retrain from the impression log
# ---------------------------------------------------------------------------