File size: 10,227 Bytes
5f0f37c | 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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | """
reproducibility/src/memory_backends.py
--------------------------------------
Unified memory backends implementing the agent memory conditions evaluated in NORA:
- M1: ChunkedBM25 (500-character recursive chunked unstructured memory, L1)
- M2: FullNodeBM25 (Intact full-node document memory, L2)
- M3u: StructuredUniformBM25F (Equal field weights, L3u)
- M3t: StructuredBM25F (Domain-tuned field weights, L3t)
All backends implement the standard interface:
backend.search(query_text: str, top_k: int = 5) -> List[dict]
where each dict contains:
{"node_id": str, "text": str, "score": float, "rank": int}
"""
import json
import re
import os
import numpy as np
from pathlib import Path
from rank_bm25 import BM25Okapi
# Multi-environment path discovery for processed datasets
CURRENT_DIR = Path(__file__).resolve().parent
candidates_base = [
CURRENT_DIR.parent / "dataset" / "processed",
CURRENT_DIR.parent.parent / "reproducibility" / "dataset" / "processed",
CURRENT_DIR.parent.parent / "data"
]
DATA_BASE = None
for cand in candidates_base:
if cand.exists():
DATA_BASE = cand
break
if DATA_BASE is None:
DATA_BASE = CURRENT_DIR.parent / "dataset" / "processed"
def tokenize(text: str) -> list:
"""Verified Bengali character normalizer and tokenizer."""
if not text:
return []
text = str(text)
text = text.replace('\u09dc', '\u09b0').replace('\u09dd', '\u09b0') # ড়, ঢ় -> র
text = text.replace('\u09df', '\u09af').replace('\u09ce', '\u09a4') # য় -> য, ৎ -> ত
text = re.sub(r'[^\w\s\u0980-\u09FF]', ' ', text)
return text.split()
# --- Domain-tuned BM25F field configurations (Paper Table 11) ---
DOMAIN_CONFIGS = {
"agriculture": {
"fields": ["disease_pest_name_bn", "colloquial_aliases_bn", "symptoms_bn",
"favorable_conditions_bn", "management_bn", "prevention_bn",
"chemical_management_bn", "affected_crop_bn", "content_bn"],
"weights": [3.5, 2.0, 1.5,
1.0, 0.8, 0.8,
0.5, 0.5, 1.0],
"list_fields": {"colloquial_aliases_bn", "symptoms_bn", "management_bn"},
},
"legal": {
"fields": ["act_title_bn", "short_title_bn", "act_no_bn", "preamble_bn",
"definitions_bn", "section_titles_bn", "penalties_bn",
"powers_bn", "procedures_bn", "content_bn"],
"weights": [5.0, 2.0, 0.5, 1.0,
0.8, 0.8, 0.5,
0.5, 0.5, 1.0],
"list_fields": {"section_titles_bn"},
},
"education": {
"fields": ["experiment_name_bn", "procedure_steps", "observation_conclusion",
"apparatus_and_chemicals", "precautions", "full_text_bn"],
"weights": [2.0, 3.0, 1.5,
0.8, 0.5, 1.0],
"list_fields": {"apparatus_and_chemicals", "procedure_steps"},
},
}
def _locate_file(domain: str, filename: str) -> Path:
direct = DATA_BASE / domain / filename
if direct.exists():
return direct
sub = DATA_BASE / domain / "corpus" / filename
if sub.exists():
return sub
raise FileNotFoundError(f"Could not locate {filename} in {DATA_BASE}/{domain}")
class ChunkedBM25:
"""M1 – Chunked text memory (500-char recursive chunking, L1)."""
def __init__(self, domain: str):
self.domain = domain
chunk_path = _locate_file(domain, "unstructured_chunks.json")
with open(chunk_path, encoding="utf-8") as f:
raw = json.load(f)
self.chunks = []
for c in raw:
text = c.get("content_bn", c.get("text", ""))
# Store parent node IDs
nid = c.get("node_id", "")
nids = c.get("node_ids", [nid] if nid else [])
self.chunks.append({"text": text, "node_ids": nids, "chunk_id": c.get("chunk_id", "")})
self.corpus_tokens = [tokenize(c["text"]) for c in self.chunks]
self.bm25 = BM25Okapi(self.corpus_tokens, k1=1.5, b=0.75)
def search(self, query_text: str, top_k: int = 5) -> list:
q_tokens = tokenize(query_text)
if not q_tokens:
return []
scores = self.bm25.get_scores(q_tokens)
top_indices = np.argsort(scores)[::-1]
results = []
seen_nodes = set()
for idx in top_indices:
c = self.chunks[idx]
primary_nid = c["node_ids"][0] if c["node_ids"] else "unknown"
if primary_nid not in seen_nodes:
seen_nodes.add(primary_nid)
results.append({
"node_id": primary_nid,
"all_node_ids": c["node_ids"],
"text": c["text"],
"score": float(scores[idx]),
"rank": len(results) + 1,
})
if len(results) == top_k:
break
return results
class FullNodeBM25:
"""M2 – Full intact node document memory (L2)."""
def __init__(self, domain: str):
self.domain = domain
node_path = _locate_file(domain, "structured_nodes.json")
with open(node_path, encoding="utf-8") as f:
raw = json.load(f)
self.nodes = []
for n in raw:
text = n.get("content_bn", n.get("full_text_bn", n.get("content", "")))
self.nodes.append({"node_id": n["node_id"], "text": text})
self.corpus_tokens = [tokenize(n["text"]) for n in self.nodes]
self.bm25 = BM25Okapi(self.corpus_tokens, k1=1.5, b=0.75)
def search(self, query_text: str, top_k: int = 5) -> list:
q_tokens = tokenize(query_text)
if not q_tokens:
return []
scores = self.bm25.get_scores(q_tokens)
top_indices = np.argsort(scores)[::-1][:top_k]
return [{
"node_id": self.nodes[idx]["node_id"],
"all_node_ids": [self.nodes[idx]["node_id"]],
"text": self.nodes[idx]["text"],
"score": float(scores[idx]),
"rank": rank + 1,
} for rank, idx in enumerate(top_indices)]
class StructuredBM25F:
"""M3 – Structured multi-field memory (BM25F, L3)."""
def __init__(self, domain: str, uniform_weights: bool = False):
self.domain = domain
self.uniform_weights = uniform_weights
node_path = _locate_file(domain, "structured_nodes.json")
with open(node_path, encoding="utf-8") as f:
self.raw_nodes = json.load(f)
config = DOMAIN_CONFIGS[domain]
self.fields = config["fields"]
self.weights = [1.0] * len(self.fields) if uniform_weights else config["weights"]
self.list_fields = config["list_fields"]
# Build field-token corpus
self.field_tokens = {f: [] for f in self.fields}
self.field_lens = {f: [] for f in self.fields}
self.node_ids = []
for node in self.raw_nodes:
self.node_ids.append(node["node_id"])
for f in self.fields:
val = node.get(f, "")
if f in self.list_fields and isinstance(val, list):
val = " ".join(val)
elif isinstance(val, list):
val = " ".join(str(x) for x in val)
tokens = tokenize(str(val))
self.field_tokens[f].append(tokens)
self.field_lens[f].append(len(tokens))
self.N = len(self.raw_nodes)
self.avgdl = {f: float(np.mean(self.field_lens[f])) if self.field_lens[f] else 1.0
for f in self.fields}
# Build document-frequency table
self.df = {}
for f in self.fields:
for doc_toks in self.field_tokens[f]:
for term in set(doc_toks):
self.df[term] = self.df.get(term, 0) + 1
def search(self, query_text: str, top_k: int = 5, k1: float = 1.5, b: float = 0.75) -> list:
q_tokens = tokenize(query_text)
if not q_tokens:
return []
scores = np.zeros(self.N)
for term in set(q_tokens):
if term not in self.df:
continue
df_val = self.df[term]
idf = np.log((self.N - df_val + 0.5) / (df_val + 0.5) + 1.0)
w_tf = np.zeros(self.N)
for f_idx, f in enumerate(self.fields):
w = self.weights[f_idx]
avg = self.avgdl[f]
b_f = 0.5 if self.domain == "education" else b
lens = np.array(self.field_lens[f], dtype=float)
lens_norm = 1.0 - b_f + b_f * (lens / (avg if avg > 0 else 1.0))
tfs = np.array([doc.count(term) for doc in self.field_tokens[f]], dtype=float)
w_tf += w * (tfs / np.maximum(lens_norm, 1e-6))
k1_val = 3.0 if self.domain == "education" else k1
scores += idf * ((w_tf * (k1_val + 1.0)) / (k1_val + w_tf + 1e-6))
top_indices = np.argsort(scores)[::-1][:top_k]
results = []
for rank, idx in enumerate(top_indices):
node = self.raw_nodes[idx]
text = node.get("content_bn", node.get("full_text_bn", node.get("content", "")))
results.append({
"node_id": self.node_ids[idx],
"all_node_ids": [self.node_ids[idx]],
"text": text,
"score": float(scores[idx]),
"rank": rank + 1,
})
return results
def build_backend(condition: str, domain: str):
"""Factory function for memory backends."""
if condition == "M1":
return ChunkedBM25(domain)
elif condition == "M2":
return FullNodeBM25(domain)
elif condition == "M3u":
return StructuredBM25F(domain, uniform_weights=True)
elif condition in ("M3", "M3t"):
return StructuredBM25F(domain, uniform_weights=False)
else:
raise ValueError(f"Unknown memory condition: {condition}")
|