Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Super Search: add query-intent one-hot features (offline-evaluated, not a win)

Daoud Clarke17fb2e095087
diff --git a/mwmbl/tinysearchengine/super_search_select/features.py b/mwmbl/tinysearchengine/super_search_select/features.py
index 995dbc3..37f4351 100644
--- a/mwmbl/tinysearchengine/super_search_select/features.py
+++ b/mwmbl/tinysearchengine/super_search_select/features.py
@@ -18,8 +18,69 @@ from django.conf import settings
from mwmbl.tinysearchengine.super_search_select import vectors
from mwmbl.tinysearchengine.super_search_select.registry import SiteMeta
+# Query-intent taxonomy. Each query is tagged with zero or more coarse intents by
+# cheap word-boundary lexicon rules; appended to the feature vector as a one-hot
+# block. Because the tags are constant across all sources of a given query, only
+# the *per-arm* bandit can exploit them — each arm's ``theta`` learns that source's
+# affinity for each intent from realized reward (the global XGBoost in ``select``,
+# which ranks sources within a query, is structurally blind to query-only features,
+# so judge intents via ``simulate``). Generalises ``has_code_token`` from one bit
+# to a vector; the dense (intent, source) co-occurrence is what makes this learnable
+# where raw per-term one-hot is ~93% singletons on the eval matrix.
+INTENT_NAMES = [
+ "code", # programming / software / dev tooling
+ "academic", # papers / research / formal study
+ "gaming", # video games, mods, speedruns
+ "music", # songs, lyrics, albums, instruments
+ "news", # current events / politics / recency
+ "howto", # questions / guides / instructional
+ "media", # books / film / art / reviews
+ "reference", # definitions / encyclopedic / "what is"
+]
+
+_INTENT_PATTERNS = {
+ "code": re.compile(
+ r"\b(python|javascript|typescript|rust|golang|c\+\+|api|sdk|cli|npm|pip|"
+ r"pypi|github|gitlab|git|docker|kubernetes|regex|compiler|runtime|library|"
+ r"framework|package|module|function|async|bug|error|exception|traceback|"
+ r"syntax|code|coding|programming|developer|debug|install)\b", re.I),
+ "academic": re.compile(
+ r"\b(paper|papers|study|studies|research|thesis|dissertation|theorem|proof|"
+ r"lemma|journal|arxiv|preprint|citation|hypothesis|equation|dataset|"
+ r"benchmark|algorithm|peer.?review)\b", re.I),
+ "gaming": re.compile(
+ r"\b(game|games|gaming|gamer|mod|mods|speedrun|playthrough|walkthrough|rpg|"
+ r"fps|mmo|roguelike|pokemon|pokémon|minecraft|factorio|steam|itch|"
+ r"console|xbox|playstation|nintendo)\b", re.I),
+ "music": re.compile(
+ r"\b(song|songs|lyric|lyrics|album|albums|band|bands|music|musician|guitar|"
+ r"piano|synth|chord|chords|melody|track|tracks|remix|vinyl|discography)\b", re.I),
+ "news": re.compile(
+ r"\b(news|election|elections|president|senate|congress|war|breaking|latest|"
+ r"today|recent|court|verdict|policy|sanctions|protest|economy|inflation|"
+ r"20\d\d)\b", re.I),
+ "howto": re.compile(
+ r"\b(how|what|why|who|when|where|guide|guides|tutorial|tutorials|tips|howto|"
+ r"learn|fix|setup|configure|versus|vs|difference)\b", re.I),
+ "media": re.compile(
+ r"\b(book|books|novel|novels|author|authors|film|films|movie|movies|cinema|"
+ r"series|art|artist|painting|paintings|museum|gallery|poem|poetry|story|"
+ r"stories|review|reviews)\b", re.I),
+ "reference": re.compile(
+ r"\b(define|definition|meaning|means|history|origin|encyclopedia|wiki|"
+ r"wikipedia|biography|facts|overview|explained|explain)\b", re.I),
+}
+
+
+def classify_intent(query: str) -> list[float]:
+ """One-hot the query over ``INTENT_NAMES`` via lexicon rules (multi-label)."""
+ return [1.0 if _INTENT_PATTERNS[name].search(query or "") else 0.0
+ for name in INTENT_NAMES]
+
+
# Stable feature order. ``bias`` is the per-arm intercept (lets the bandit learn
-# a site's base success rate even with all-zero context).
+# a site's base success rate even with all-zero context). The ``intent_*`` block is
+# appended last so existing feature indices are unchanged.
FEATURE_NAMES = [
"bias",
"cos_bow",
@@ -31,7 +92,7 @@ FEATURE_NAMES = [
"failure_rate",
"query_len",
"has_code_token",
-]
+] + [f"intent_{name}" for name in INTENT_NAMES]
NUM_FEATURES = len(FEATURE_NAMES)
# Tokens that look like code / identifiers — a cheap signal that programming
@@ -46,6 +107,7 @@ class QueryContext:
cng: np.ndarray
n_tokens: int
has_code_token: bool
+ intent: list[float] # one-hot over INTENT_NAMES
@classmethod
def build(cls, query: str, bow: np.ndarray, cng: np.ndarray) -> "QueryContext":
@@ -54,6 +116,7 @@ class QueryContext:
cng=cng,
n_tokens=len(query.split()),
has_code_token=bool(_CODE_RE.search(query)),
+ intent=classify_intent(query),
)
@@ -86,6 +149,7 @@ def feature_vector(
stats.failure_rate, # failure_rate
min(qctx.n_tokens, 10) / 10.0, # query_len (normalised)
1.0 if qctx.has_code_token else 0.0, # has_code_token
+ *qctx.intent, # intent_* one-hot block
], dtype=np.float64)
return x
diff --git a/scripts/augment_matrix_intent.py b/scripts/augment_matrix_intent.py
new file mode 100644
index 0000000..afac2d5
--- /dev/null
+++ b/scripts/augment_matrix_intent.py
@@ -0,0 +1,66 @@
+"""Offline shortcut: append the query-only intent one-hot columns to an existing
+Super Search reward matrix, with NO network rebuild.
+
+The intent features (``features.classify_intent``) depend only on the query text,
+which is already stored in the matrix's ``.json`` sidecar, so we recompute them for
+every stored query and broadcast across all sources. ``R``/``mask`` are untouched.
+This avoids re-running ``super_search_eval.py build-matrix`` (~20 min, networked)
+just to test a query-only feature.
+
+Usage:
+ DATABASE_URL=... DJANGO_SETTINGS_MODULE=mwmbl.settings_dev uv run python \
+ scripts/augment_matrix_intent.py --in devdata/ss_eval_matrix \
+ --out devdata/ss_eval_matrix_intent
+"""
+import argparse
+import os
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mwmbl.settings_dev")
+import django # noqa: E402
+django.setup()
+
+import numpy as np # noqa: E402
+from mwmbl.tinysearchengine.super_search_select.evaluation import RewardMatrix # noqa: E402
+from mwmbl.tinysearchengine.super_search_select.features import ( # noqa: E402
+ FEATURE_NAMES, INTENT_NAMES, classify_intent,
+)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--in", dest="inp", default="devdata/ss_eval_matrix")
+ ap.add_argument("--out", dest="out", default="devdata/ss_eval_matrix_intent")
+ args = ap.parse_args()
+
+ m = RewardMatrix.load(args.inp)
+ Q, S, F = m.X.shape
+ intent_names = [f"intent_{n}" for n in INTENT_NAMES]
+ assert m.feature_names == FEATURE_NAMES[:F], (
+ f"matrix feature_names {m.feature_names} are not the prefix of the current "
+ f"FEATURE_NAMES; refusing to append (rebuild via build-matrix instead).")
+ assert FEATURE_NAMES[F:] == intent_names, "intent block must be the appended tail"
+
+ # (Q, n_intents) one-hot, then broadcast across the S source axis.
+ per_query = np.array([classify_intent(q) for q in m.queries], dtype=m.X.dtype)
+ intent_block = np.broadcast_to(per_query[:, None, :], (Q, S, len(INTENT_NAMES)))
+ X_aug = np.concatenate([m.X, intent_block], axis=2)
+
+ aug = RewardMatrix(queries=m.queries, sources=m.sources,
+ feature_names=list(FEATURE_NAMES),
+ X=X_aug, R=m.R, mask=m.mask)
+ aug.save(args.out)
+
+ fired = per_query.sum(axis=0)
+ print(f"in : {args.inp} ({Q}x{S}x{F})")
+ print(f"out: {args.out} ({Q}x{S}x{X_aug.shape[2]})")
+ print(f"queries with >=1 intent tag: {int((per_query.sum(axis=1) > 0).sum())}/{Q}")
+ print(f"per-intent fire count (out of {Q} queries):")
+ for n, c in zip(INTENT_NAMES, fired):
+ print(f" intent_{n:10s} {int(c):4d} ({c / Q * 100:.1f}%)")
+
+
+if __name__ == "__main__":
+ main()