redrob-ranker / solution /src /embedding.py
javaliajayakumar's picture
Upload app and scoring solution
1689e06 verified
Raw History Blame Contribute Delete
5.19 kB
"""Semantic encoder with a graceful offline fallback.
Preferred path: sentence-transformers (all-MiniLM-L6-v2, 384-dim).
- First attempts local-files-only to honour the "no network during ranking"
constraint.
- If the model is not cached yet, allows a one-time download (first run).
Fallback path: TF-IDF + truncated SVD (pure scikit-learn, no downloads).
- Engages automatically when sentence-transformers is not installed.
- Produces up to 384 SVD components, L2-normalised — same dot-product API.
Either way, ``encode`` returns L2-normalised vectors so a dot product equals
cosine similarity, and ``cosine_similarity`` is a thin helper.
"""
from __future__ import annotations
import numpy as np
class SemanticEncoder:
"""Wraps sentence-transformers with an automatic scikit-learn fallback."""
def __init__(self, model_name: str = "all-MiniLM-L6-v2") -> None:
self.model_name = model_name
self._backend: str | None = None
self._st_model = None
self._tfidf = None
self._svd = None
# ------------------------------------------------------------------
# Backend detection
# ------------------------------------------------------------------
def _try_load_sentence_transformer(self) -> bool:
"""Try to load the ST model; allow download on first run."""
try:
from sentence_transformers import SentenceTransformer
# First attempt: local cache only (fast, honours offline constraint).
try:
self._st_model = SentenceTransformer(
self.model_name, local_files_only=True
)
self._backend = "sentence_transformer"
print(f" [encoder] sentence-transformers (cached)", flush=True)
return True
except Exception:
pass
# Second attempt: allow download (first-time setup).
print(
f" [encoder] Downloading {self.model_name} …"
" (one-time; cached for future runs)",
flush=True,
)
self._st_model = SentenceTransformer(self.model_name)
self._backend = "sentence_transformer"
print(f" [encoder] sentence-transformers ready", flush=True)
return True
except Exception:
return False
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def fit(self, corpus: list[str]) -> "SemanticEncoder":
"""Prepare the encoder. ``corpus`` is used to train the TF-IDF fallback."""
if self._try_load_sentence_transformer():
return self
# Fallback: TF-IDF + truncated SVD
print(" [encoder] sentence-transformers unavailable → TF-IDF+SVD fallback",
flush=True)
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
self._tfidf = TfidfVectorizer(
lowercase=True,
ngram_range=(1, 2),
min_df=1, # min_df=1 so tiny corpora (sample) still work
max_features=60_000,
sublinear_tf=True,
stop_words="english",
)
matrix = self._tfidf.fit_transform(corpus)
n_comp = min(384, matrix.shape[0] - 1, matrix.shape[1] - 1)
n_comp = max(2, n_comp)
self._svd = TruncatedSVD(n_components=n_comp, random_state=42)
self._svd.fit(matrix)
self._backend = "tfidf_svd"
print(f" [encoder] TF-IDF+SVD ({n_comp} components)", flush=True)
return self
def encode(self, texts: list[str]) -> np.ndarray:
if self._backend == "sentence_transformer":
vecs = self._st_model.encode(
texts,
batch_size=64,
show_progress_bar=False,
convert_to_numpy=True,
normalize_embeddings=True,
)
return vecs.astype(np.float32)
if self._backend == "tfidf_svd":
matrix = self._tfidf.transform(texts)
vecs = self._svd.transform(matrix).astype(np.float32)
return _l2_normalize(vecs)
raise RuntimeError("Encoder not fitted. Call fit() first.")
@property
def backend(self) -> str:
return self._backend or "uninitialized"
# ---------------------------------------------------------------------------
# Utilities
# ---------------------------------------------------------------------------
def _l2_normalize(vecs: np.ndarray) -> np.ndarray:
norms = np.linalg.norm(vecs, axis=1, keepdims=True)
norms[norms == 0] = 1.0
return vecs / norms
def cosine_similarity(query: np.ndarray, matrix: np.ndarray) -> np.ndarray:
"""Compute cosine similarity between a single query vector and a matrix.
Args:
query: shape (d,), must be L2-normalised.
matrix: shape (n, d), must be L2-normalised.
Returns:
shape (n,) of similarities in [-1, 1].
"""
return matrix @ query