| """Scoring primitives for BrainCore Memory Benchmark.""" |
|
|
| import re |
| import time |
| from typing import Any |
|
|
| import numpy as np |
| from sentence_transformers import SentenceTransformer |
| from sklearn.metrics.pairwise import cosine_similarity |
|
|
| |
| _EMBEDDER: SentenceTransformer | None = None |
|
|
|
|
| def _get_embedder() -> SentenceTransformer: |
| global _EMBEDDER |
| if _EMBEDDER is None: |
| _EMBEDDER = SentenceTransformer("all-MiniLM-L6-v2") |
| return _EMBEDDER |
|
|
|
|
| def exact_match(pred: str, ref: str) -> float: |
| """Case-insensitive, punctuation-stripped exact match.""" |
| def _norm(s: str) -> str: |
| return re.sub(r"[^a-z0-9\s]", "", s.lower()).strip() |
| return 1.0 if _norm(pred) == _norm(ref) else 0.0 |
|
|
|
|
| def semantic_placeholder_score(pred: str, ref: str) -> float: |
| """Cosine similarity of sentence embeddings as a soft semantic proxy.""" |
| emb = _get_embedder() |
| vectors = emb.encode([pred, ref], convert_to_numpy=True) |
| sim = cosine_similarity(vectors[0:1], vectors[1:2])[0, 0] |
| |
| return float((sim + 1.0) / 2.0) |
|
|
|
|
| def temporal_order_score( |
| retrieved_memories: list[dict], |
| required_ids: list[str], |
| ) -> float: |
| """Check whether returned memories respect chronological order.""" |
| if not retrieved_memories: |
| return 0.0 |
| |
| positions = [] |
| for mem in retrieved_memories: |
| mid = mem.get("memory_id") |
| if mid in required_ids: |
| positions.append(required_ids.index(mid)) |
| if len(positions) < 2: |
| return 1.0 |
| return 1.0 if positions == sorted(positions) else 0.0 |
|
|
|
|
| def contradiction_resolution_score( |
| retrieved_memories: list[dict], |
| latest_memory_id: str | None, |
| ) -> float: |
| """For contradiction queries, check if the *latest* revised fact is top-ranked.""" |
| if latest_memory_id is None: |
| return 1.0 |
| if not retrieved_memories: |
| return 0.0 |
| return 1.0 if retrieved_memories[0].get("memory_id") == latest_memory_id else 0.0 |
|
|
|
|
| def latency_ms(t0: float, t1: float) -> float: |
| return round((t1 - t0) * 1000, 3) |
|
|
|
|
| def aggregate(results: list[dict]) -> dict[str, float]: |
| """Return mean of each metric across a list of per-query result dicts.""" |
| keys = [ |
| "exact_match", |
| "semantic_placeholder_score", |
| "temporal_order_score", |
| "contradiction_resolution_score", |
| "latency_ms", |
| "storage_bytes", |
| ] |
| out: dict[str, float] = {} |
| for k in keys: |
| vals = [r[k] for r in results if k in r] |
| if vals: |
| out[k] = round(float(np.mean(vals)), 4) |
| else: |
| out[k] = 0.0 |
| return out |
|
|