trentdoney commited on
Commit
7ff2cfd
·
verified ·
1 Parent(s): 9bf65e1

Upload src/metrics.py

Browse files
Files changed (1) hide show
  1. src/metrics.py +89 -0
src/metrics.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Scoring primitives for BrainCore Memory Benchmark."""
2
+
3
+ import re
4
+ import time
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+ from sentence_transformers import SentenceTransformer
9
+ from sklearn.metrics.pairwise import cosine_similarity
10
+
11
+ # Lazy-load embedding model so import time stays fast.
12
+ _EMBEDDER: SentenceTransformer | None = None
13
+
14
+
15
+ def _get_embedder() -> SentenceTransformer:
16
+ global _EMBEDDER
17
+ if _EMBEDDER is None:
18
+ _EMBEDDER = SentenceTransformer("all-MiniLM-L6-v2")
19
+ return _EMBEDDER
20
+
21
+
22
+ def exact_match(pred: str, ref: str) -> float:
23
+ """Case-insensitive, punctuation-stripped exact match."""
24
+ def _norm(s: str) -> str:
25
+ return re.sub(r"[^a-z0-9\s]", "", s.lower()).strip()
26
+ return 1.0 if _norm(pred) == _norm(ref) else 0.0
27
+
28
+
29
+ def semantic_placeholder_score(pred: str, ref: str) -> float:
30
+ """Cosine similarity of sentence embeddings as a soft semantic proxy."""
31
+ emb = _get_embedder()
32
+ vectors = emb.encode([pred, ref], convert_to_numpy=True)
33
+ sim = cosine_similarity(vectors[0:1], vectors[1:2])[0, 0]
34
+ # Scale to [0, 1] — MiniLM outputs roughly [-1, 1].
35
+ return float((sim + 1.0) / 2.0)
36
+
37
+
38
+ def temporal_order_score(
39
+ retrieved_memories: list[dict],
40
+ required_ids: list[str],
41
+ ) -> float:
42
+ """Check whether returned memories respect chronological order."""
43
+ if not retrieved_memories:
44
+ return 0.0
45
+ # Map memory_id -> position in required_ids (if present).
46
+ positions = []
47
+ for mem in retrieved_memories:
48
+ mid = mem.get("memory_id")
49
+ if mid in required_ids:
50
+ positions.append(required_ids.index(mid))
51
+ if len(positions) < 2:
52
+ return 1.0 # Trivially ordered.
53
+ return 1.0 if positions == sorted(positions) else 0.0
54
+
55
+
56
+ def contradiction_resolution_score(
57
+ retrieved_memories: list[dict],
58
+ latest_memory_id: str | None,
59
+ ) -> float:
60
+ """For contradiction queries, check if the *latest* revised fact is top-ranked."""
61
+ if latest_memory_id is None:
62
+ return 1.0 # No contradiction ground-truth → neutral.
63
+ if not retrieved_memories:
64
+ return 0.0
65
+ return 1.0 if retrieved_memories[0].get("memory_id") == latest_memory_id else 0.0
66
+
67
+
68
+ def latency_ms(t0: float, t1: float) -> float:
69
+ return round((t1 - t0) * 1000, 3)
70
+
71
+
72
+ def aggregate(results: list[dict]) -> dict[str, float]:
73
+ """Return mean of each metric across a list of per-query result dicts."""
74
+ keys = [
75
+ "exact_match",
76
+ "semantic_placeholder_score",
77
+ "temporal_order_score",
78
+ "contradiction_resolution_score",
79
+ "latency_ms",
80
+ "storage_bytes",
81
+ ]
82
+ out: dict[str, float] = {}
83
+ for k in keys:
84
+ vals = [r[k] for r in results if k in r]
85
+ if vals:
86
+ out[k] = round(float(np.mean(vals)), 4)
87
+ else:
88
+ out[k] = 0.0
89
+ return out