Upload src/baseline_adapter.py
Browse files- src/baseline_adapter.py +42 -0
src/baseline_adapter.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Simple keyword-retrieval baseline for BrainCore Memory Benchmark."""
|
| 2 |
+
|
| 3 |
+
import pickle
|
| 4 |
+
import time
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class BaselineAdapter:
|
| 9 |
+
"""Ingests memories into a flat list; retrieves via keyword overlap scoring."""
|
| 10 |
+
|
| 11 |
+
def __init__(self):
|
| 12 |
+
self.memories: list[dict] = []
|
| 13 |
+
self._index: dict[str, list[int]] = {} # word -> list of memory indices
|
| 14 |
+
|
| 15 |
+
def ingest(self, raw_memories: list[dict]) -> None:
|
| 16 |
+
self.memories = raw_memories
|
| 17 |
+
self._index.clear()
|
| 18 |
+
for idx, mem in enumerate(raw_memories):
|
| 19 |
+
text = mem.get("text", "")
|
| 20 |
+
for word in set(text.lower().split()):
|
| 21 |
+
self._index.setdefault(word, []).append(idx)
|
| 22 |
+
|
| 23 |
+
def retrieve(self, query: str, top_k: int = 1) -> list[dict]:
|
| 24 |
+
query_words = set(query.lower().split())
|
| 25 |
+
scores: dict[int, int] = {}
|
| 26 |
+
for w in query_words:
|
| 27 |
+
for idx in self._index.get(w, []):
|
| 28 |
+
scores[idx] = scores.get(idx, 0) + 1
|
| 29 |
+
# Break ties by recency (higher index = more recent).
|
| 30 |
+
ranked = sorted(
|
| 31 |
+
scores.items(),
|
| 32 |
+
key=lambda x: (x[1], x[0]),
|
| 33 |
+
reverse=True,
|
| 34 |
+
)
|
| 35 |
+
return [self.memories[i] for i, _ in ranked[:top_k]]
|
| 36 |
+
|
| 37 |
+
def storage_bytes(self) -> int:
|
| 38 |
+
return len(pickle.dumps(self.memories))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def build() -> BaselineAdapter:
|
| 42 |
+
return BaselineAdapter()
|