Beyond-Chunking / src /memory_backends.py
RaiyanKhaan's picture
Upload complete Beyond-Chunking reproducibility package and benchmark datasets
5f0f37c verified
Raw History Blame Contribute Delete
10.2 kB
"""
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}")