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
|
|
|
|
|
|
|
| 1 |
+
# Integration Guide β LightGBM Reranker into ResearchIT
|
| 2 |
+
|
| 3 |
+
> **For:** Whoever integrates the reranker into `app/recommend/reranker.py`
|
| 4 |
+
> **Covers:** Steps 5-8 from the Phase 6 roadmap
|
| 5 |
+
> **Prerequisites:** The production model is trained and in `production_model/reranker_v1.txt`
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
## Overview
|
| 10 |
+
|
| 11 |
+
You need to do 4 things:
|
| 12 |
+
1. **Expand `compute_features()` from 5 β 37 features** (biggest change)
|
| 13 |
+
2. **Wire model loading + heuristic fallback** at startup
|
| 14 |
+
3. **Add `lightgbm` to `requirements.txt`** and model file to Docker image
|
| 15 |
+
4. **Integration testing**
|
| 16 |
+
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
## Step 5: Expand `compute_features()` to 37 Features
|
| 20 |
+
|
| 21 |
+
The current heuristic uses 5 features. The LightGBM model expects 37 features in a **specific order** defined in `production_model/feature_schema.json`.
|
| 22 |
+
|
| 23 |
+
### Feature Schema (order matters!)
|
| 24 |
+
|
| 25 |
+
```python
|
| 26 |
+
FEATURE_SCHEMA = [
|
| 27 |
+
# Content/Retrieval (0-19)
|
| 28 |
+
"qdrant_cosine_score", # 0 - from Qdrant ANN search
|
| 29 |
+
"candidate_position", # 1 - rank in ANN results
|
| 30 |
+
"candidate_citation_count", # 2 - from Turso papers table
|
| 31 |
+
"candidate_log_citations", # 3 - log(citation_count + 1)
|
| 32 |
+
"candidate_influential_citations", # 4 - from Turso papers table
|
| 33 |
+
"candidate_age_days", # 5 - (now - update_date).days
|
| 34 |
+
"candidate_recency_score", # 6 - exp(-0.002 * age_days)
|
| 35 |
+
"query_citation_count", # 7 - user's profile paper citations (or 0)
|
| 36 |
+
"query_age_days", # 8 - user's profile paper age (or 0)
|
| 37 |
+
"year_diff", # 9 - |query_year - candidate_year|
|
| 38 |
+
"same_primary_category", # 10 - 1 if same primary_topic
|
| 39 |
+
"co_citation_count", # 11 - shared citers (expensive; can be 0)
|
| 40 |
+
"shared_author_count", # 12 - shared authors between query & candidate
|
| 41 |
+
"candidate_is_newer", # 13 - 1 if candidate.year > query.year
|
| 42 |
+
"query_log_citations", # 14 - log(query_citation_count + 1)
|
| 43 |
+
"citation_count_ratio", # 15 - cand_citations / (query_citations + 1)
|
| 44 |
+
"age_ratio", # 16 - cand_age / (query_age + 1)
|
| 45 |
+
"candidate_citations_per_year", # 17 - citations / max(age_years, 0.5)
|
| 46 |
+
"query_num_references", # 18 - 0 for now (needs citation graph in prod)
|
| 47 |
+
"candidate_num_cited_by", # 19 - 0 for now (needs citation graph in prod)
|
| 48 |
+
|
| 49 |
+
# User Behavior (20-30) β from EWMA profiles, clusters, interactions
|
| 50 |
+
"ewma_longterm_similarity", # 20 - cos(candidate_emb, user.lt_profile)
|
| 51 |
+
"ewma_shortterm_similarity", # 21 - cos(candidate_emb, user.st_profile)
|
| 52 |
+
"ewma_negative_similarity", # 22 - cos(candidate_emb, user.neg_profile)
|
| 53 |
+
"cluster_importance", # 23 - cluster weight from Ward clustering
|
| 54 |
+
"cluster_distance_to_medoid", # 24 - cos(candidate_emb, cluster_medoid)
|
| 55 |
+
"is_suppressed_category", # 25 - 1 if suppressed category
|
| 56 |
+
"onboarding_category_match", # 26 - 1 if matches onboarding prefs
|
| 57 |
+
"user_total_saves", # 27 - total saves from interactions table
|
| 58 |
+
"user_total_dismissals", # 28 - total dismissals
|
| 59 |
+
"user_days_since_last_save", # 29 - days since last save
|
| 60 |
+
"user_session_save_count", # 30 - saves this session
|
| 61 |
+
|
| 62 |
+
# Cross Features (31-36) β computed from above
|
| 63 |
+
"cosine_x_recency", # 31 - feat[0] * feat[6]
|
| 64 |
+
"cosine_x_citations", # 32 - feat[0] * feat[3]
|
| 65 |
+
"category_x_recency", # 33 - feat[10] * feat[6]
|
| 66 |
+
"cosine_x_cocitation", # 34 - feat[0] * log(feat[11] + 1)
|
| 67 |
+
"position_inverse", # 35 - 1 / (feat[1] + 1)
|
| 68 |
+
"citations_x_recency", # 36 - feat[3] * feat[6]
|
| 69 |
+
]
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
### Implementation Sketch
|
| 73 |
+
|
| 74 |
+
```python
|
| 75 |
+
import numpy as np
|
| 76 |
+
from datetime import datetime, timezone
|
| 77 |
+
|
| 78 |
+
def compute_features_v2(
|
| 79 |
+
user_state: dict, # EWMA profiles, cluster info, interaction counts
|
| 80 |
+
candidate: dict, # paper metadata from Turso
|
| 81 |
+
qdrant_score: float, # cosine score from ANN search
|
| 82 |
+
candidate_position: int, # rank position (0-indexed)
|
| 83 |
+
candidate_embedding: np.ndarray, # 1024-dim BGE-M3 embedding
|
| 84 |
+
) -> np.ndarray:
|
| 85 |
+
"""
|
| 86 |
+
Compute 37-feature vector for LightGBM reranker.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
user_state: {
|
| 90 |
+
"lt_profile": np.ndarray, # long-term EWMA (1024-dim or None)
|
| 91 |
+
"st_profile": np.ndarray, # short-term EWMA (1024-dim or None)
|
| 92 |
+
"neg_profile": np.ndarray, # negative EWMA (1024-dim or None)
|
| 93 |
+
"cluster_importance": float, # from Ward clustering
|
| 94 |
+
"cluster_medoid": np.ndarray, # cluster medoid embedding (or None)
|
| 95 |
+
"suppressed_categories": set, # suppressed arXiv categories
|
| 96 |
+
"onboarding_categories": set, # onboarding selections
|
| 97 |
+
"total_saves": int,
|
| 98 |
+
"total_dismissals": int,
|
| 99 |
+
"days_since_last_save": float,
|
| 100 |
+
"session_save_count": int,
|
| 101 |
+
"query_paper": dict | None, # the "seed" paper if applicable
|
| 102 |
+
}
|
| 103 |
+
candidate: {
|
| 104 |
+
"arxiv_id": str,
|
| 105 |
+
"primary_topic": str,
|
| 106 |
+
"update_date": str, # "YYYY-MM-DD"
|
| 107 |
+
"citation_count": int,
|
| 108 |
+
"influential_citations": int,
|
| 109 |
+
"authors": list[str],
|
| 110 |
+
}
|
| 111 |
+
qdrant_score: cosine similarity from ANN search
|
| 112 |
+
candidate_position: rank in ANN results (0-indexed)
|
| 113 |
+
candidate_embedding: paper's BGE-M3 embedding vector
|
| 114 |
+
|
| 115 |
+
Returns:
|
| 116 |
+
np.ndarray of shape (37,) β feature vector in schema order
|
| 117 |
+
"""
|
| 118 |
+
features = np.zeros(37, dtype=np.float32)
|
| 119 |
+
now = datetime.now(timezone.utc)
|
| 120 |
+
|
| 121 |
+
# --- Content/Retrieval features (0-19) ---
|
| 122 |
+
|
| 123 |
+
# 0: qdrant_cosine_score
|
| 124 |
+
features[0] = qdrant_score
|
| 125 |
+
|
| 126 |
+
# 1: candidate_position
|
| 127 |
+
features[1] = float(candidate_position)
|
| 128 |
+
|
| 129 |
+
# 2: candidate_citation_count
|
| 130 |
+
cand_citations = candidate.get("citation_count", 0) or 0
|
| 131 |
+
features[2] = float(cand_citations)
|
| 132 |
+
|
| 133 |
+
# 3: candidate_log_citations
|
| 134 |
+
features[3] = np.log(cand_citations + 1)
|
| 135 |
+
|
| 136 |
+
# 4: candidate_influential_citations
|
| 137 |
+
features[4] = float(candidate.get("influential_citations", 0) or 0)
|
| 138 |
+
|
| 139 |
+
# 5: candidate_age_days
|
| 140 |
+
try:
|
| 141 |
+
pub_date = datetime.strptime(candidate.get("update_date", "")[:10], "%Y-%m-%d")
|
| 142 |
+
pub_date = pub_date.replace(tzinfo=timezone.utc)
|
| 143 |
+
cand_age = max(0, (now - pub_date).days)
|
| 144 |
+
except (ValueError, TypeError):
|
| 145 |
+
cand_age = 365 # default 1 year
|
| 146 |
+
features[5] = float(cand_age)
|
| 147 |
+
|
| 148 |
+
# 6: candidate_recency_score
|
| 149 |
+
features[6] = np.exp(-0.002 * cand_age)
|
| 150 |
+
|
| 151 |
+
# 7-9: Query paper features (from user's seed paper, or defaults)
|
| 152 |
+
query_paper = user_state.get("query_paper") or {}
|
| 153 |
+
query_citations = query_paper.get("citation_count", 0) or 0
|
| 154 |
+
features[7] = float(query_citations)
|
| 155 |
+
|
| 156 |
+
try:
|
| 157 |
+
q_pub = datetime.strptime(query_paper.get("update_date", "")[:10], "%Y-%m-%d")
|
| 158 |
+
q_pub = q_pub.replace(tzinfo=timezone.utc)
|
| 159 |
+
query_age = max(0, (now - q_pub).days)
|
| 160 |
+
except (ValueError, TypeError):
|
| 161 |
+
query_age = 0
|
| 162 |
+
features[8] = float(query_age)
|
| 163 |
+
|
| 164 |
+
cand_year = _parse_year(candidate.get("update_date", ""))
|
| 165 |
+
query_year = _parse_year(query_paper.get("update_date", "")) if query_paper else cand_year
|
| 166 |
+
features[9] = abs(query_year - cand_year)
|
| 167 |
+
|
| 168 |
+
# 10: same_primary_category
|
| 169 |
+
q_cat = query_paper.get("primary_topic", "") if query_paper else ""
|
| 170 |
+
c_cat = candidate.get("primary_topic", "")
|
| 171 |
+
features[10] = 1.0 if (q_cat and c_cat and q_cat == c_cat) else 0.0
|
| 172 |
+
|
| 173 |
+
# 11: co_citation_count (0 unless you have citation graph loaded)
|
| 174 |
+
features[11] = 0.0 # TODO: populate if citation graph is loaded
|
| 175 |
+
|
| 176 |
+
# 12: shared_author_count
|
| 177 |
+
if query_paper and query_paper.get("authors"):
|
| 178 |
+
q_authors = {a.lower().strip() for a in query_paper["authors"] if a}
|
| 179 |
+
c_authors = {a.lower().strip() for a in (candidate.get("authors") or []) if a}
|
| 180 |
+
features[12] = float(len(q_authors & c_authors))
|
| 181 |
+
|
| 182 |
+
# 13: candidate_is_newer
|
| 183 |
+
features[13] = 1.0 if cand_year > query_year else 0.0
|
| 184 |
+
|
| 185 |
+
# 14: query_log_citations
|
| 186 |
+
features[14] = np.log(query_citations + 1)
|
| 187 |
+
|
| 188 |
+
# 15: citation_count_ratio
|
| 189 |
+
features[15] = cand_citations / (query_citations + 1)
|
| 190 |
+
|
| 191 |
+
# 16: age_ratio
|
| 192 |
+
features[16] = cand_age / (query_age + 1) if query_age > 0 else 0.0
|
| 193 |
+
|
| 194 |
+
# 17: candidate_citations_per_year
|
| 195 |
+
cand_age_years = max(cand_age / 365.0, 0.5)
|
| 196 |
+
features[17] = cand_citations / cand_age_years
|
| 197 |
+
|
| 198 |
+
# 18-19: Graph features (0 unless citation graph loaded in prod)
|
| 199 |
+
features[18] = 0.0 # query_num_references
|
| 200 |
+
features[19] = 0.0 # candidate_num_cited_by
|
| 201 |
+
|
| 202 |
+
# --- User Behavior features (20-30) ---
|
| 203 |
+
|
| 204 |
+
# 20: ewma_longterm_similarity
|
| 205 |
+
lt_prof = user_state.get("lt_profile")
|
| 206 |
+
if lt_prof is not None and candidate_embedding is not None:
|
| 207 |
+
features[20] = _cosine_sim(candidate_embedding, lt_prof)
|
| 208 |
+
|
| 209 |
+
# 21: ewma_shortterm_similarity
|
| 210 |
+
st_prof = user_state.get("st_profile")
|
| 211 |
+
if st_prof is not None and candidate_embedding is not None:
|
| 212 |
+
features[21] = _cosine_sim(candidate_embedding, st_prof)
|
| 213 |
+
|
| 214 |
+
# 22: ewma_negative_similarity
|
| 215 |
+
neg_prof = user_state.get("neg_profile")
|
| 216 |
+
if neg_prof is not None and candidate_embedding is not None:
|
| 217 |
+
features[22] = _cosine_sim(candidate_embedding, neg_prof)
|
| 218 |
+
|
| 219 |
+
# 23: cluster_importance
|
| 220 |
+
features[23] = float(user_state.get("cluster_importance", 0.0))
|
| 221 |
+
|
| 222 |
+
# 24: cluster_distance_to_medoid
|
| 223 |
+
medoid = user_state.get("cluster_medoid")
|
| 224 |
+
if medoid is not None and candidate_embedding is not None:
|
| 225 |
+
features[24] = _cosine_sim(candidate_embedding, medoid)
|
| 226 |
+
|
| 227 |
+
# 25: is_suppressed_category
|
| 228 |
+
suppressed = user_state.get("suppressed_categories", set())
|
| 229 |
+
features[25] = 1.0 if c_cat in suppressed else 0.0
|
| 230 |
+
|
| 231 |
+
# 26: onboarding_category_match
|
| 232 |
+
onboarding = user_state.get("onboarding_categories", set())
|
| 233 |
+
features[26] = 1.0 if c_cat in onboarding else 0.0
|
| 234 |
+
|
| 235 |
+
# 27-30: Interaction counts
|
| 236 |
+
features[27] = float(user_state.get("total_saves", 0))
|
| 237 |
+
features[28] = float(user_state.get("total_dismissals", 0))
|
| 238 |
+
features[29] = float(user_state.get("days_since_last_save", 0.0))
|
| 239 |
+
features[30] = float(user_state.get("session_save_count", 0))
|
| 240 |
+
|
| 241 |
+
# --- Cross Features (31-36) ---
|
| 242 |
+
|
| 243 |
+
features[31] = features[0] * features[6] # cosine Γ recency
|
| 244 |
+
features[32] = features[0] * features[3] # cosine Γ log_citations
|
| 245 |
+
features[33] = features[10] * features[6] # category Γ recency
|
| 246 |
+
features[34] = features[0] * np.log(features[11] + 1) # cosine Γ log_cocitation
|
| 247 |
+
features[35] = 1.0 / (features[1] + 1) # position_inverse
|
| 248 |
+
features[36] = features[3] * features[6] # log_citations Γ recency
|
| 249 |
+
|
| 250 |
+
return features
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _cosine_sim(a: np.ndarray, b: np.ndarray) -> float:
|
| 254 |
+
"""Cosine similarity between two vectors."""
|
| 255 |
+
dot = np.dot(a, b)
|
| 256 |
+
norm_a = np.linalg.norm(a)
|
| 257 |
+
norm_b = np.linalg.norm(b)
|
| 258 |
+
if norm_a == 0 or norm_b == 0:
|
| 259 |
+
return 0.0
|
| 260 |
+
return float(dot / (norm_a * norm_b))
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def _parse_year(date_str: str) -> int:
|
| 264 |
+
try:
|
| 265 |
+
return int(date_str[:4])
|
| 266 |
+
except (ValueError, TypeError, IndexError):
|
| 267 |
+
return 2020
|
| 268 |
+
```
|
| 269 |
+
|
| 270 |
+
### Vectorized Version (for batch scoring)
|
| 271 |
+
|
| 272 |
+
For production use, compute features for ALL candidates at once:
|
| 273 |
+
|
| 274 |
+
```python
|
| 275 |
+
def compute_features_batch(
|
| 276 |
+
user_state: dict,
|
| 277 |
+
candidates: list[dict],
|
| 278 |
+
qdrant_scores: list[float],
|
| 279 |
+
candidate_embeddings: np.ndarray, # (N, 1024)
|
| 280 |
+
) -> np.ndarray:
|
| 281 |
+
"""
|
| 282 |
+
Compute features for all candidates at once.
|
| 283 |
+
Returns (N, 37) feature matrix.
|
| 284 |
+
"""
|
| 285 |
+
N = len(candidates)
|
| 286 |
+
features = np.zeros((N, 37), dtype=np.float32)
|
| 287 |
+
|
| 288 |
+
for i, (cand, score) in enumerate(zip(candidates, qdrant_scores)):
|
| 289 |
+
features[i] = compute_features_v2(
|
| 290 |
+
user_state=user_state,
|
| 291 |
+
candidate=cand,
|
| 292 |
+
qdrant_score=score,
|
| 293 |
+
candidate_position=i,
|
| 294 |
+
candidate_embedding=candidate_embeddings[i] if candidate_embeddings is not None else None,
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
return features
|
| 298 |
+
```
|
| 299 |
+
|
| 300 |
+
> **Performance note:** The bottleneck is NOT feature computation or LightGBM prediction (0.4ms). It's fetching candidate metadata from Turso. Batch your Turso queries.
|
| 301 |
+
|
| 302 |
+
---
|
| 303 |
+
|
| 304 |
+
## Step 6: Wire Model Loading + Heuristic Fallback
|
| 305 |
+
|
| 306 |
+
In `app/recommend/reranker.py`:
|
| 307 |
+
|
| 308 |
+
```python
|
| 309 |
+
import os
|
| 310 |
+
import lightgbm as lgb
|
| 311 |
+
import numpy as np
|
| 312 |
+
|
| 313 |
+
# ββ Model Loading ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 314 |
+
|
| 315 |
+
_lgb_model = None
|
| 316 |
+
_model_path = os.environ.get("RERANKER_MODEL_PATH", "production_model/reranker_v1.txt")
|
| 317 |
+
|
| 318 |
+
try:
|
| 319 |
+
_lgb_model = lgb.Booster(model_file=_model_path)
|
| 320 |
+
print(f"[reranker] LightGBM model loaded from {_model_path}")
|
| 321 |
+
print(f"[reranker] num_features: {_lgb_model.num_feature()}")
|
| 322 |
+
print(f"[reranker] num_trees: {_lgb_model.num_trees()}")
|
| 323 |
+
except FileNotFoundError:
|
| 324 |
+
print(f"[reranker] Model file not found: {_model_path} β using heuristic")
|
| 325 |
+
except Exception as e:
|
| 326 |
+
print(f"[reranker] Model load failed: {e} β using heuristic")
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
# ββ Main Reranking Function ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 330 |
+
|
| 331 |
+
def rerank_candidates(
|
| 332 |
+
user_state: dict,
|
| 333 |
+
candidates: list[dict],
|
| 334 |
+
qdrant_scores: list[float],
|
| 335 |
+
candidate_embeddings: np.ndarray | None = None,
|
| 336 |
+
) -> list[dict]:
|
| 337 |
+
"""
|
| 338 |
+
Rerank candidates using LightGBM (or heuristic fallback).
|
| 339 |
+
|
| 340 |
+
Returns candidates sorted by score (best first).
|
| 341 |
+
"""
|
| 342 |
+
if not candidates:
|
| 343 |
+
return []
|
| 344 |
+
|
| 345 |
+
if _lgb_model is not None:
|
| 346 |
+
# LightGBM path
|
| 347 |
+
features = compute_features_batch(user_state, candidates, qdrant_scores, candidate_embeddings)
|
| 348 |
+
scores = _lgb_model.predict(features)
|
| 349 |
+
else:
|
| 350 |
+
# Heuristic fallback (always works, no model needed)
|
| 351 |
+
scores = np.array([
|
| 352 |
+
heuristic_score(user_state, cand, score)
|
| 353 |
+
for cand, score in zip(candidates, qdrant_scores)
|
| 354 |
+
])
|
| 355 |
+
|
| 356 |
+
# Sort by score descending
|
| 357 |
+
order = np.argsort(-scores)
|
| 358 |
+
return [candidates[i] for i in order]
|
| 359 |
+
```
|
| 360 |
+
|
| 361 |
+
### Key Design Decisions
|
| 362 |
+
|
| 363 |
+
1. **The heuristic fallback is PERMANENT.** Don't remove it. It's your safety net if:
|
| 364 |
+
- The model file is missing (fresh deploy)
|
| 365 |
+
- LightGBM import fails (dependency issue)
|
| 366 |
+
- The model produces garbage (bad retrain)
|
| 367 |
+
|
| 368 |
+
2. **Model path is configurable** via `RERANKER_MODEL_PATH` env var. This lets you A/B test different models without code changes.
|
| 369 |
+
|
| 370 |
+
3. **No model versioning yet.** For v1, just replace the file. When you have v2, add version tracking.
|
| 371 |
+
|
| 372 |
+
---
|
| 373 |
+
|
| 374 |
+
## Step 7: Update `requirements.txt`
|
| 375 |
+
|
| 376 |
+
Add to your `requirements.txt`:
|
| 377 |
+
```
|
| 378 |
+
lightgbm>=4.0,<5.0
|
| 379 |
+
```
|
| 380 |
+
|
| 381 |
+
And in your `Dockerfile`, ensure the model file is copied:
|
| 382 |
+
```dockerfile
|
| 383 |
+
COPY production_model/reranker_v1.txt /app/production_model/reranker_v1.txt
|
| 384 |
+
```
|
| 385 |
+
|
| 386 |
+
Or download from this repo at startup:
|
| 387 |
+
```python
|
| 388 |
+
# In app startup
|
| 389 |
+
from huggingface_hub import hf_hub_download
|
| 390 |
+
|
| 391 |
+
model_path = hf_hub_download(
|
| 392 |
+
repo_id="siddhm11/researchit-reranker-phase6",
|
| 393 |
+
filename="production_model/reranker_v1.txt",
|
| 394 |
+
)
|
| 395 |
+
```
|
| 396 |
+
|
| 397 |
+
---
|
| 398 |
+
|
| 399 |
+
## Step 8: Integration Testing
|
| 400 |
+
|
| 401 |
+
### Smoke Test
|
| 402 |
+
```python
|
| 403 |
+
import lightgbm as lgb
|
| 404 |
+
import numpy as np
|
| 405 |
+
|
| 406 |
+
# Load model
|
| 407 |
+
model = lgb.Booster(model_file="production_model/reranker_v1.txt")
|
| 408 |
+
assert model.num_feature() == 37
|
| 409 |
+
|
| 410 |
+
# Predict on dummy input
|
| 411 |
+
dummy = np.zeros((5, 37), dtype=np.float32)
|
| 412 |
+
scores = model.predict(dummy)
|
| 413 |
+
assert scores.shape == (5,)
|
| 414 |
+
assert not np.any(np.isnan(scores))
|
| 415 |
+
print("β
Smoke test passed")
|
| 416 |
+
```
|
| 417 |
+
|
| 418 |
+
### End-to-End Test
|
| 419 |
+
```python
|
| 420 |
+
# Verify the full pipeline: ANN β feature computation β LightGBM β ranked output
|
| 421 |
+
def test_e2e():
|
| 422 |
+
# 1. Simulate a user with EWMA profiles
|
| 423 |
+
user_state = {
|
| 424 |
+
"lt_profile": np.random.randn(1024).astype(np.float32),
|
| 425 |
+
"st_profile": np.random.randn(1024).astype(np.float32),
|
| 426 |
+
"neg_profile": np.random.randn(1024).astype(np.float32),
|
| 427 |
+
"cluster_importance": 0.8,
|
| 428 |
+
"cluster_medoid": np.random.randn(1024).astype(np.float32),
|
| 429 |
+
"suppressed_categories": {"cs.CR"},
|
| 430 |
+
"onboarding_categories": {"cs.CL", "cs.LG"},
|
| 431 |
+
"total_saves": 42,
|
| 432 |
+
"total_dismissals": 10,
|
| 433 |
+
"days_since_last_save": 0.5,
|
| 434 |
+
"session_save_count": 3,
|
| 435 |
+
"query_paper": None,
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
# 2. Simulate candidates from Qdrant
|
| 439 |
+
candidates = [
|
| 440 |
+
{"arxiv_id": f"2024.{i:05d}", "primary_topic": "cs.CL",
|
| 441 |
+
"update_date": "2024-01-15", "citation_count": i*10,
|
| 442 |
+
"influential_citations": i, "authors": ["Alice", "Bob"]}
|
| 443 |
+
for i in range(50)
|
| 444 |
+
]
|
| 445 |
+
qdrant_scores = [0.9 - i*0.01 for i in range(50)]
|
| 446 |
+
candidate_embeddings = np.random.randn(50, 1024).astype(np.float32)
|
| 447 |
+
|
| 448 |
+
# 3. Rerank
|
| 449 |
+
ranked = rerank_candidates(user_state, candidates, qdrant_scores, candidate_embeddings)
|
| 450 |
+
|
| 451 |
+
assert len(ranked) == 50
|
| 452 |
+
# The order should differ from the ANN order (LightGBM reranks)
|
| 453 |
+
original_ids = [c["arxiv_id"] for c in candidates]
|
| 454 |
+
reranked_ids = [c["arxiv_id"] for c in ranked]
|
| 455 |
+
assert original_ids != reranked_ids, "LightGBM should change the order"
|
| 456 |
+
print("β
E2E test passed")
|
| 457 |
+
```
|
| 458 |
+
|
| 459 |
+
### Latency Test
|
| 460 |
+
```python
|
| 461 |
+
import time
|
| 462 |
+
|
| 463 |
+
features = np.random.randn(100, 37).astype(np.float32)
|
| 464 |
+
|
| 465 |
+
# Warmup
|
| 466 |
+
for _ in range(100):
|
| 467 |
+
model.predict(features)
|
| 468 |
+
|
| 469 |
+
# Benchmark
|
| 470 |
+
t0 = time.time()
|
| 471 |
+
for _ in range(1000):
|
| 472 |
+
model.predict(features)
|
| 473 |
+
elapsed = (time.time() - t0) / 1000 * 1000 # ms per call
|
| 474 |
+
|
| 475 |
+
assert elapsed < 1.0, f"Too slow: {elapsed:.3f}ms (target: <1ms)"
|
| 476 |
+
print(f"β
Latency: {elapsed:.3f}ms per 100 candidates")
|
| 477 |
+
```
|
| 478 |
+
|
| 479 |
+
---
|
| 480 |
+
|
| 481 |
+
## Notes for Future Retraining
|
| 482 |
+
|
| 483 |
+
When you have 500+ real user interactions:
|
| 484 |
+
|
| 485 |
+
1. Export interactions from Turso:
|
| 486 |
+
```sql
|
| 487 |
+
SELECT user_id, arxiv_id, action, created_at FROM interactions
|
| 488 |
+
```
|
| 489 |
+
|
| 490 |
+
2. Generate new training triples with **real labels**:
|
| 491 |
+
- `action = 'save'` β label 2
|
| 492 |
+
- `action = 'click'` β label 1
|
| 493 |
+
- `action = 'dismiss'` β label 0
|
| 494 |
+
|
| 495 |
+
3. The 37-feature schema is **stable** β features 20-30 will now be populated with real EWMA profiles, cluster data, and interaction counts.
|
| 496 |
+
|
| 497 |
+
4. Retrain with the same `03_train_lightgbm.py` script on the new data.
|
| 498 |
+
|
| 499 |
+
5. The user behavior features (20-30) should gain significant importance in the new model.
|