391 lines
15 KiB
Python
391 lines
15 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Professional evaluation pipeline to benchmark different Sentence Transformer models
|
|
on the OpenAlex topics dataset. Measures Information Retrieval (IR) metrics,
|
|
Taxonomy Clustering metrics, and operational performance metrics.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import random
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
from dotenv import load_dotenv
|
|
|
|
# Add service/src/main to python path to load settings
|
|
current_dir = Path(__file__).parent.resolve()
|
|
project_root = current_dir.parent.parent.resolve()
|
|
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
|
|
load_dotenv(dotenv_path=env_path)
|
|
|
|
sys.path.append(str(project_root / "service" / "src" / "main"))
|
|
from inse.config import settings
|
|
|
|
ELASTIC_URL = settings.elasticsearch_url
|
|
API_KEY = settings.elasticsearch_api_key
|
|
|
|
# Import evaluation libraries
|
|
from sentence_transformers import SentenceTransformer
|
|
from sentence_transformers.evaluation import InformationRetrievalEvaluator
|
|
from sklearn import metrics
|
|
from sklearn.cluster import KMeans
|
|
|
|
DEFAULT_MODELS = [
|
|
"paraphrase-multilingual-mpnet-base-v2",
|
|
"BAAI/bge-m3",
|
|
"google/embeddinggemma-300m",
|
|
"intfloat/multilingual-e5-small",
|
|
"intfloat/multilingual-e5-base",
|
|
"intfloat/multilingual-e5-large",
|
|
"sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
|
|
#english
|
|
"sentence-transformers/all-MiniLM-L6-v2",
|
|
"intfloat/e5-large-v2",
|
|
"BAAI/bge-large-en-v1.5"
|
|
]
|
|
|
|
def fetch_all_topics():
|
|
topics = []
|
|
size = 1000
|
|
offset = 0
|
|
headers = {
|
|
"Authorization": f"ApiKey {API_KEY}",
|
|
"Content-Type": "application/json"
|
|
}
|
|
|
|
with httpx.Client(timeout=60.0) as client:
|
|
while True:
|
|
payload = {
|
|
"query": {"match_all": {}},
|
|
"from": offset,
|
|
"size": size
|
|
}
|
|
resp = client.post(
|
|
f"{ELASTIC_URL.rstrip('/')}/openalex-topics/_search",
|
|
json=payload,
|
|
headers=headers
|
|
)
|
|
resp.raise_for_status()
|
|
data = resp.json()
|
|
hits = data.get("hits", {}).get("hits", [])
|
|
if not hits:
|
|
break
|
|
topics.extend(hits)
|
|
offset += len(hits)
|
|
print(f"Fetched {len(topics)} topics...")
|
|
if len(hits) < size:
|
|
break
|
|
|
|
print(f"Total topics loaded: {len(topics)}")
|
|
return topics
|
|
|
|
def prepare_data(topics, sample_size=None):
|
|
"""
|
|
Formulate the IR dataset and clustering taxonomy ground truth labels.
|
|
"""
|
|
corpus = {}
|
|
queries = {}
|
|
relevant_docs = {}
|
|
|
|
# Clustering labels
|
|
topic_ids = []
|
|
names_for_clustering = []
|
|
descriptions_for_clustering = []
|
|
labels_subfield = []
|
|
labels_field = []
|
|
labels_domain = []
|
|
|
|
# Build complete corpus dictionary of documents
|
|
for t in topics:
|
|
source = t["_source"]
|
|
doc_id = source["id"]
|
|
display_name = source.get("display_name") or ""
|
|
description = source.get("description") or ""
|
|
doc_text = f"{display_name} {description}".strip()
|
|
|
|
corpus[doc_id] = doc_text
|
|
|
|
# Taxonomy labels
|
|
topic_ids.append(doc_id)
|
|
names_for_clustering.append(display_name.strip())
|
|
descriptions_for_clustering.append(description.strip())
|
|
labels_subfield.append(source.get("subfield", {}).get("id") or "unknown_subfield")
|
|
labels_field.append(source.get("field", {}).get("id") or "unknown_field")
|
|
labels_domain.append(source.get("domain", {}).get("id") or "unknown_domain")
|
|
|
|
sampled_topics = topics
|
|
if sample_size and sample_size < len(topics):
|
|
print(f"Sampling {sample_size} topics for query/keyword generation...")
|
|
sampled_topics = random.sample(topics, sample_size)
|
|
|
|
query_count = 0
|
|
for t in sampled_topics:
|
|
source = t["_source"]
|
|
doc_id = source["id"]
|
|
keywords = source.get("keywords") or []
|
|
|
|
for keyword in keywords:
|
|
if not keyword.strip():
|
|
continue
|
|
query_id = f"q_{query_count}"
|
|
queries[query_id] = keyword
|
|
|
|
# Ground truth relevant documents: topic name
|
|
rel_docs = {doc_id}
|
|
relevant_docs[query_id] = rel_docs
|
|
query_count += 1
|
|
|
|
print(f"Dataset Formulated: {len(corpus)} corpus documents, {len(queries)} queries.")
|
|
|
|
return {
|
|
"corpus": corpus,
|
|
"queries": queries,
|
|
"relevant_docs": relevant_docs,
|
|
"clustering": {
|
|
"ids": topic_ids,
|
|
"names": names_for_clustering,
|
|
"descriptions": descriptions_for_clustering,
|
|
"subfield": labels_subfield,
|
|
"field": labels_field,
|
|
"domain": labels_domain
|
|
}
|
|
}
|
|
|
|
def evaluate_model(model_name, data, output_dir):
|
|
"""
|
|
Load a model, measure operational speed, and calculate IR + clustering quality.
|
|
"""
|
|
model_safe_name = model_name.replace("/", "_").replace("-", "_")
|
|
report_file = output_dir / f"model_report_{model_safe_name}.json"
|
|
|
|
print("\n==================================================")
|
|
print(f"Evaluating Model: '{model_name}'")
|
|
print("==================================================")
|
|
|
|
start_load = time.time()
|
|
try:
|
|
model = SentenceTransformer(model_name)
|
|
except Exception as exc:
|
|
print(f"ERROR: Failed to load model '{model_name}': {exc}")
|
|
return None
|
|
|
|
load_time = time.time() - start_load
|
|
print(f"Model loaded in {load_time:.2f} seconds.")
|
|
|
|
num_params = sum(p.numel() for p in model.parameters())
|
|
param_count_m = num_params / 1_000_000
|
|
vector_dim = model.get_sentence_embedding_dimension()
|
|
print(f"Parameters: {param_count_m:.1f}M, Vector Dimension: {vector_dim}")
|
|
|
|
# --- FIXED: Perform a warm-up to initialize computation graphs ---
|
|
print("Warming up model...")
|
|
_ = model.encode(["warmup sentence"])
|
|
|
|
# 2. Measure Query Latency
|
|
sample_queries = list(data["queries"].values())[:100]
|
|
if not sample_queries:
|
|
sample_queries = ["artificial intelligence", "machine learning"]
|
|
|
|
start_lat = time.time()
|
|
for q in sample_queries:
|
|
_ = model.encode(q)
|
|
latency_ms = ((time.time() - start_lat) / len(sample_queries)) * 1000
|
|
print(f"Average Query Latency: {latency_ms:.2f} ms")
|
|
|
|
# 3. Measure Ingestion Throughput
|
|
sample_docs = list(data["corpus"].values())[:200]
|
|
start_batch = time.time()
|
|
_ = model.encode(sample_docs, batch_size=32)
|
|
batch_time = time.time() - start_batch
|
|
throughput_docs_sec = len(sample_docs) / batch_time
|
|
print(f"Ingestion Throughput: {throughput_docs_sec:.2f} docs/sec")
|
|
|
|
# 4. Information Retrieval Evaluation
|
|
print("Running Information Retrieval evaluation (NDCG, MRR, Recall)...")
|
|
|
|
# --- FIXED: Use precision_recall_at_k for true recall metrics ---
|
|
evaluator = InformationRetrievalEvaluator(
|
|
data["queries"],
|
|
data["corpus"],
|
|
data["relevant_docs"], # The evaluator natively accepts sets, no need to cast to lists
|
|
name=model_safe_name,
|
|
mrr_at_k=[10],
|
|
ndcg_at_k=[10],
|
|
precision_recall_at_k=[10] # This ensures true Recall is calculated across multiple sibling matches
|
|
)
|
|
|
|
ir_results = evaluator(model)
|
|
|
|
# Extract keys safely
|
|
ndcg_key = f"{model_safe_name}_cosine_ndcg@10"
|
|
mrr_key = f"{model_safe_name}_cosine_mrr@10"
|
|
recall_key = f"{model_safe_name}_cosine_recall@10" # Changed from accuracy to recall
|
|
|
|
ndcg_score = ir_results.get(ndcg_key, 0.0)
|
|
mrr_score = ir_results.get(mrr_key, 0.0)
|
|
recall_score = ir_results.get(recall_key, 0.0)
|
|
|
|
print(f"NDCG@10: {ndcg_score:.4f}, MRR@10: {mrr_score:.4f}, Recall@10: {recall_score:.4f}")
|
|
|
|
# 5. Clustering evaluation against ground-truth taxonomy
|
|
print("Running Taxonomy Clustering evaluation (NMI)...")
|
|
|
|
unique_subfields = list(set(data["clustering"]["subfield"]))
|
|
n_clusters = len(unique_subfields)
|
|
|
|
# Topic Names Clustering
|
|
print("Clustering Topic Names...")
|
|
clustering_names = data["clustering"]["names"]
|
|
name_embeddings = model.encode(clustering_names, show_progress_bar=False, batch_size=64)
|
|
|
|
nmi_name = 0.0
|
|
ari_name = 0.0
|
|
if n_clusters > 1 and len(name_embeddings) > n_clusters:
|
|
kmeans_name = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto')
|
|
assignments_name = kmeans_name.fit_predict(name_embeddings)
|
|
nmi_name = metrics.normalized_mutual_info_score(data["clustering"]["subfield"], assignments_name)
|
|
ari_name = metrics.adjusted_rand_score(data["clustering"]["subfield"], assignments_name)
|
|
print(f"Names - Subfield Clustering NMI: {nmi_name:.4f}, ARI: {ari_name:.4f}")
|
|
|
|
# Topic Descriptions Clustering
|
|
print("Clustering Topic Descriptions...")
|
|
clustering_descs = data["clustering"]["descriptions"]
|
|
desc_embeddings = model.encode(clustering_descs, show_progress_bar=False, batch_size=64)
|
|
|
|
nmi_desc = 0.0
|
|
ari_desc = 0.0
|
|
if n_clusters > 1 and len(desc_embeddings) > n_clusters:
|
|
kmeans_desc = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto')
|
|
assignments_desc = kmeans_desc.fit_predict(desc_embeddings)
|
|
nmi_desc = metrics.normalized_mutual_info_score(data["clustering"]["subfield"], assignments_desc)
|
|
ari_desc = metrics.adjusted_rand_score(data["clustering"]["subfield"], assignments_desc)
|
|
print(f"Descriptions - Subfield Clustering NMI: {nmi_desc:.4f}, ARI: {ari_desc:.4f}")
|
|
|
|
report = {
|
|
"model_name": model_name,
|
|
"parameters_m": param_count_m,
|
|
"vector_dim": vector_dim,
|
|
"latency_ms": latency_ms,
|
|
"throughput_docs_sec": throughput_docs_sec,
|
|
"ndcg_at_10": ndcg_score,
|
|
"mrr_at_10": mrr_score,
|
|
"recall_at_10": recall_score,
|
|
"name_nmi": nmi_name,
|
|
"name_ari": ari_name,
|
|
"desc_nmi": nmi_desc,
|
|
"desc_ari": ari_desc
|
|
}
|
|
|
|
with open(report_file, "w", encoding="utf-8") as f:
|
|
json.dump(report, f, indent=2, ensure_ascii=False)
|
|
print(f"Saved model report to {report_file}")
|
|
|
|
return report
|
|
|
|
def generate_consolidated_report(output_dir, reports):
|
|
if not reports:
|
|
print("No reports to consolidate.")
|
|
return
|
|
|
|
report_file = output_dir / "model_evaluation_report.md"
|
|
print(f"\nCompiling consolidated report into {report_file}...")
|
|
|
|
sorted_reports = sorted(reports, key=lambda x: x["ndcg_at_10"], reverse=True)
|
|
|
|
lines = [
|
|
"# Sentence Transformer Model Evaluation Report",
|
|
"",
|
|
"This report aggregates performance metrics and accuracy benchmarks for different Sentence Transformer models evaluated against the OpenAlex topic keywords dataset.",
|
|
"",
|
|
"## Overall Leaderboard",
|
|
"",
|
|
"| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |",
|
|
"| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |"
|
|
]
|
|
|
|
for idx, r in enumerate(sorted_reports):
|
|
name_nmi = r.get("name_nmi", 0.0)
|
|
desc_nmi = r.get("desc_nmi", 0.0)
|
|
lines.append(
|
|
f"| {idx+1} | `{r['model_name']}` | {r['vector_dim']} | {r['parameters_m']:.1f}M | {r['latency_ms']:.2f}ms | {r['throughput_docs_sec']:.1f} | **{r['ndcg_at_10']:.4f}** | {r['mrr_at_10']:.4f} | {r['recall_at_10']:.4f} | {name_nmi:.4f} | {desc_nmi:.4f} |"
|
|
)
|
|
|
|
lines.extend([
|
|
"",
|
|
"### Metric Definitions:",
|
|
"* **NDCG@10**: Normalized Discounted Cumulative Gain. Measures how well the query maps to the target topic at the top 10 positions.",
|
|
"* **MRR@10**: Mean Reciprocal Rank. Looks at the average of `1 / rank` for the first correctly matched topic.",
|
|
"* **Recall@10**: Percentage of times the target document (excluding sibling topics) was successfully retrieved in the top 10.",
|
|
"* **Name NMI**: Normalized Mutual Information of K-Means clusters of topic display names against ground truth OpenAlex subfields.",
|
|
"* **Desc NMI**: Normalized Mutual Information of K-Means clusters of topic descriptions against ground truth OpenAlex subfields.",
|
|
"* **Query Latency**: Time to encode a single search keyword.",
|
|
"* **Throughput**: Ingestion batch encoding speed."
|
|
])
|
|
|
|
with open(report_file, "w", encoding="utf-8") as f:
|
|
f.write("\n".join(lines))
|
|
print(f"Report compiled successfully at {report_file}")
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="Evaluate Sentence Transformer models on OpenAlex topics.")
|
|
parser.add_argument("--model", type=str, help="Specific model to evaluate (skips others).")
|
|
parser.add_argument("--sample-size", type=int, help="Sample size of topics to evaluate keywords for (faster run).")
|
|
parser.add_argument("--all", action="store_true", help="Evaluate all topics/keywords (default if sample-size omitted).")
|
|
parser.add_argument("--output-dir", type=str, help="Custom directory to save reports.")
|
|
parser.add_argument("--force-refresh", action="store_true", help="Force reload topics from Elasticsearch instead of cache.")
|
|
|
|
args = parser.parse_args()
|
|
|
|
if Path("/data").is_dir():
|
|
data_dir = Path("/data")
|
|
else:
|
|
project_root = Path(__file__).parent.parent.parent.parent.parent.resolve()
|
|
data_dir = project_root / "service" / "src" / "data"
|
|
data_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
output_dir = Path(args.output_dir) if args.output_dir else data_dir
|
|
output_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
cache_file = data_dir / "raw_topics_cache.json"
|
|
if cache_file.exists() and not args.force_refresh:
|
|
print(f"Loading topics from local cache: {cache_file}")
|
|
with open(cache_file, "r", encoding="utf-8") as f:
|
|
topics = json.load(f)
|
|
else:
|
|
topics = fetch_all_topics()
|
|
with open(cache_file, "w", encoding="utf-8") as f:
|
|
json.dump(topics, f, indent=2, ensure_ascii=False)
|
|
print(f"Cached {len(topics)} topics to {cache_file}")
|
|
|
|
if not topics:
|
|
print("Error: No topics dataset available. Make sure Elasticsearch is running or cache exists.")
|
|
sys.exit(1)
|
|
|
|
data = prepare_data(topics, sample_size=args.sample_size)
|
|
|
|
models_to_evaluate = DEFAULT_MODELS
|
|
if args.model:
|
|
models_to_evaluate = [args.model]
|
|
|
|
print(f"Models scheduled for evaluation: {models_to_evaluate}")
|
|
|
|
reports = []
|
|
for m in models_to_evaluate:
|
|
model_safe_name = m.replace("/", "_").replace("-", "_")
|
|
report_file = output_dir / f"model_report_{model_safe_name}.json"
|
|
|
|
if report_file.exists() and not args.model:
|
|
print(f"Loading cached evaluation report for '{m}' from {report_file}")
|
|
with open(report_file, "r", encoding="utf-8") as f:
|
|
reports.append(json.load(f))
|
|
else:
|
|
rep = evaluate_model(m, data, output_dir)
|
|
if rep:
|
|
reports.append(rep)
|
|
|
|
generate_consolidated_report(output_dir, reports)
|
|
|
|
if __name__ == "__main__":
|
|
main() |