File size: 13,796 Bytes
6c5f29f | 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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | """Evaluate human-edited OracleMem natural examples as a finite package.
The JSONL examples in ``llm_memory_validation/human_style_examples`` already
contain candidate memories, costs, evidence units, and coverage edges. This
script converts them into one OracleMem instance and evaluates standard writer
policies against an exact package optimum.
The exact solver here is a dynamic program for this artifact: every example is
one multiple-choice group and evidence-unit ids are namespaced by example, so
candidate singleton values are additive across groups.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any, Dict, Iterable, Mapping, Optional, Sequence
REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
from oraclemem.evaluate import (
CandidateMemory,
DEFAULT_ESTIMATOR_MODEL,
DEFAULT_ESTIMATOR_PROFILE,
EstimatedUtilityModel,
OracleMemInstance,
SelectionResult,
TOMBSTONE_TYPES,
feasibility_report,
greedy_select,
objective_value,
policy_metadata_for_method,
representation_mix,
select_method,
selected_candidates,
total_cost,
update_metrics,
write_benchmark_outputs,
)
DEFAULT_METHODS = (
"opt",
"oracle_gvt",
"estimated_gvt",
"memgpt_tiered",
"amem_graph",
"amac_admission",
"mem0_extract",
"density_only",
"greedy",
"fact_only",
"summary_only",
"recency_raw",
"no_tombstone_opt",
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Evaluate human-edited OracleMem natural examples."
)
parser.add_argument(
"--examples-jsonl",
default="llm_memory_validation/human_style_examples/examples_100.jsonl",
help="Canonical human-style examples JSONL file.",
)
parser.add_argument(
"--out-dir",
default="llm_memory_validation/human_style_examples/eval_package_100",
help="Output directory for raw_results.jsonl and summaries.",
)
parser.add_argument(
"--budgets",
default="150,300,600,1000",
help="Comma or space separated integer storage budgets.",
)
parser.add_argument(
"--methods",
default=",".join(DEFAULT_METHODS),
help="Comma or space separated methods.",
)
return parser.parse_args()
def parse_tokens(value: str) -> tuple[str, ...]:
return tuple(token for token in value.replace(",", " ").split() if token)
def load_examples(path: str | Path) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
for line_number, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), 1):
if not line.strip():
continue
row = json.loads(line)
row["_line_number"] = line_number
rows.append(row)
return rows
def _unit_key(example_id: str, unit_id: str) -> str:
return f"{example_id}::{unit_id}"
def build_instance(rows: Sequence[Mapping[str, Any]]) -> OracleMemInstance:
candidates: list[CandidateMemory] = []
unit_weights: Dict[str, float] = {}
current_units: list[str] = []
invalidation_units: list[str] = []
stale_units: list[str] = []
for time_index, row in enumerate(rows):
example_id = str(row["example_id"])
required = {
_unit_key(example_id, str(unit_id))
for unit_id in row.get("required_unit_ids_for_query", [])
}
unit_states = {
_unit_key(example_id, str(unit["unit_id"])): str(unit.get("state", "current"))
for unit in row.get("evidence_units", [])
}
for unit_id in required:
unit_weights[unit_id] = 1.0
state = unit_states.get(unit_id, "")
if any(marker in state for marker in ("update", "current", "query_required", "correction")):
current_units.append(unit_id)
if any(marker in state for marker in ("invalidation", "tombstone", "update", "correction")):
invalidation_units.append(unit_id)
if any(marker in state for marker in ("stale", "superseded", "expired")):
stale_units.append(unit_id)
for candidate in row.get("candidate_memories", []):
coverage = {
_unit_key(example_id, str(unit_id)): float(score)
for unit_id, score in dict(candidate.get("coverage", {})).items()
if _unit_key(example_id, str(unit_id)) in required
}
candidate_id = f"{example_id}::{candidate['candidate_id']}"
candidates.append(
CandidateMemory(
candidate_id=candidate_id,
experience_id=example_id,
representation_type=str(candidate.get("representation_type", "unknown")),
serialized=str(candidate.get("text", "")),
cost=max(0, int(candidate.get("cost_tokens_estimate", 0))),
coverage=coverage,
time_index=time_index,
generator="human_edited",
confidence=1.0,
)
)
return OracleMemInstance(
instance_id="human_audited_seed_0",
candidates=candidates,
unit_weights=unit_weights,
seed=0,
current_units=tuple(sorted(set(current_units))),
invalidation_units=tuple(sorted(set(invalidation_units))),
stale_units=tuple(sorted(set(stale_units))),
)
def exact_mckp_dp(
instance: OracleMemInstance,
budget: int,
*,
disallow_types: Iterable[str] = (),
) -> tuple[str, ...]:
"""Exact multiple-choice DP for disjoint-unit human example groups."""
disallowed = set(disallow_types)
groups: dict[str, list[CandidateMemory]] = {}
for candidate in instance.candidates:
if candidate.representation_type in disallowed:
continue
groups.setdefault(candidate.experience_id, []).append(candidate)
# budget -> (value, ids, cost)
states: dict[int, tuple[float, tuple[str, ...], int]] = {0: (0.0, (), 0)}
for experience_id in sorted(groups):
next_states = dict(states)
for used_budget, (value, ids, used_cost) in states.items():
for candidate in groups[experience_id]:
new_cost = used_budget + candidate.cost
if new_cost > budget:
continue
candidate_value = objective_value([candidate], instance.unit_weights)
new_value = value + candidate_value
new_ids = ids + (candidate.candidate_id,)
incumbent = next_states.get(new_cost)
if incumbent is None or (
new_value > incumbent[0] + 1e-12
or (abs(new_value - incumbent[0]) <= 1e-12 and new_cost < incumbent[2])
):
next_states[new_cost] = (new_value, new_ids, new_cost)
states = next_states
best = max(states.values(), key=lambda item: (item[0], -item[2], item[1]))
return best[1]
def make_result(
instance: OracleMemInstance,
*,
budget: int,
method: str,
selected_ids: Sequence[str],
optimum_value: float,
reference_value: float,
policy_metadata: Optional[Mapping[str, Any]] = None,
) -> SelectionResult:
selected = selected_candidates(instance.candidates, selected_ids)
value = objective_value(selected, instance.unit_weights)
feasibility = feasibility_report(instance.candidates, selected_ids, budget)
ratio_to_opt = value / optimum_value if optimum_value > 0 else None
ratio_to_reference = value / reference_value if reference_value > 0 else None
return SelectionResult(
instance_id=instance.instance_id,
seed=instance.seed,
distribution="human_audited",
budget=budget,
method=method,
selected_candidate_ids=tuple(selected_ids),
selected_cost=int(feasibility["selected_cost"]),
objective_value=value,
denominator_label="exact_human_audited_package_dp",
ratio_to_opt=ratio_to_opt,
ratio_to_upper_bound=ratio_to_opt,
ratio_to_reference=ratio_to_reference,
optimum_value=optimum_value,
upper_bound=optimum_value,
upper_bound_source="exact_mckp_dp_disjoint_units",
reference_value=reference_value,
runtime_sec=0.0,
budget_feasible=bool(feasibility["budget_feasible"]),
group_feasible=bool(feasibility["group_feasible"]),
representation_mix=representation_mix(selected),
update_metrics=update_metrics(instance, selected),
retrieval_metrics={},
policy_metadata=dict(policy_metadata or {}),
)
def evaluate_human_package(
instance: OracleMemInstance,
budgets: Sequence[int],
methods: Sequence[str],
*,
estimator_model: str = DEFAULT_ESTIMATOR_MODEL,
estimator_profile: str = DEFAULT_ESTIMATOR_PROFILE,
estimator_state: Optional[EstimatedUtilityModel] = None,
) -> list[SelectionResult]:
rows: list[SelectionResult] = []
for budget in budgets:
exact_ids = exact_mckp_dp(instance, budget)
optimum_value = objective_value(
selected_candidates(instance.candidates, exact_ids), instance.unit_weights
)
reference_ids = greedy_select(instance.candidates, budget, instance.unit_weights)
reference_value = objective_value(
selected_candidates(instance.candidates, reference_ids), instance.unit_weights
)
no_tombstone_ids: Optional[tuple[str, ...]] = None
if "no_tombstone_opt" in methods:
no_tombstone_ids = exact_mckp_dp(instance, budget, disallow_types=TOMBSTONE_TYPES)
for method in methods:
if method == "opt":
selected_ids = exact_ids
elif method == "no_tombstone_opt":
selected_ids = no_tombstone_ids or ()
else:
selected_ids = select_method(
method,
instance.candidates,
budget,
instance.unit_weights,
exact_ids=exact_ids,
estimator_model=estimator_model,
estimator_profile=estimator_profile,
estimator_state=estimator_state,
)
rows.append(
make_result(
instance,
budget=budget,
method=method,
selected_ids=selected_ids,
optimum_value=optimum_value,
reference_value=reference_value,
policy_metadata=policy_metadata_for_method(
method,
estimator_model=estimator_model,
estimator_profile=estimator_profile,
estimator_state=estimator_state,
),
)
)
return rows
def write_report(out_dir: Path, examples_path: Path, rows: Sequence[Mapping[str, Any]], results: Sequence[SelectionResult]) -> None:
out_dir.mkdir(parents=True, exist_ok=True)
domain_counts: Dict[str, int] = {}
for row in rows:
domain = str(row["domain"])
domain_counts[domain] = domain_counts.get(domain, 0) + 1
lines = [
"# Human-Edited/Audited OracleMem Package Evaluation",
"",
f"- Source examples: `{examples_path}`",
f"- Records: {len(rows)}",
"- Annotation status: human-edited/audited source examples as provided by the authors; no inter-annotator agreement file is included.",
"- Denominator: exact dynamic-programming optimum over the finite human-audited package.",
"- Aggregation: the 100 examples are evaluated as one finite package, so package-level ratios are reported rather than cross-annotator agreement statistics.",
"",
"## Domain Counts",
"",
]
for domain, count in sorted(domain_counts.items()):
lines.append(f"- `{domain}`: {count}")
lines.extend(["", "## Package Ratio To OPT", ""])
by_budget_method: Dict[tuple[int, str], list[float]] = {}
for result in results:
by_budget_method.setdefault((result.budget, result.method), []).append(result.ratio_to_opt or 0.0)
for budget in sorted({result.budget for result in results}):
lines.append(f"### Budget {budget}")
for method in sorted({result.method for result in results}):
values = by_budget_method.get((budget, method), [])
if values:
mean = sum(values) / len(values)
lines.append(f"- `{method}`: {mean:.3f}")
lines.append("")
(out_dir / "REPORT.md").write_text("\n".join(lines), encoding="utf-8")
def main() -> None:
args = parse_args()
examples_path = Path(args.examples_jsonl)
rows = load_examples(examples_path)
instance = build_instance(rows)
budgets = tuple(int(token) for token in parse_tokens(args.budgets))
methods = parse_tokens(args.methods)
results = evaluate_human_package(instance, budgets, methods)
paths = write_benchmark_outputs(results, args.out_dir)
write_report(Path(args.out_dir), examples_path, rows, results)
print(
json.dumps(
{
"examples": len(rows),
"candidates": len(instance.candidates),
"required_units": len(instance.unit_weights),
"budgets": budgets,
"methods": methods,
**paths,
},
indent=2,
)
)
if __name__ == "__main__":
main()
|