File size: 2,822 Bytes
7ff2cfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""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

# Lazy-load embedding model so import time stays fast.
_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]
    # Scale to [0, 1] — MiniLM outputs roughly [-1, 1].
    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
    # Map memory_id -> position in required_ids (if present).
    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  # Trivially ordered.
    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  # No contradiction ground-truth → neutral.
    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