NagaYu's picture
EchoCache guard benchmark: 131 labelled pairs measuring wrong cache reuse
73b50d4 verified
Raw History Blame Contribute Delete
5.02 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Score a semantic-cache matcher against the EchoCache correctness benchmark.
python3 evaluate.py # scores the EchoCache matcher from the Hub
python3 evaluate.py --matcher ./echocache_matcher.py
The headline number is WRONG REUSE: the share of "must not reuse" pairs that a
matcher would serve from cache anyway. Every one of those is a wrong answer
shipped to a user. Reuse recall (how many safe pairs it does reuse) is only
worth reading once wrong reuse is near zero.
Requires: numpy. Optional: huggingface_hub (to fetch the matcher and the data).
"""
import argparse
import importlib.util
import json
import os
import sys
def load_matcher(path=None):
"""Guarantees: returns an imported matcher module, fetching it from the Hub when no path is given."""
if path is None:
from huggingface_hub import hf_hub_download
path = hf_hub_download("NagaYu/echocache-matcher", "echocache_matcher.py")
spec = importlib.util.spec_from_file_location("echocache_matcher", path)
module = importlib.util.module_from_spec(spec)
sys.modules["echocache_matcher"] = module
spec.loader.exec_module(module)
return module
def load_pairs(path=None):
"""Guarantees: returns the benchmark rows, fetching them from the Hub when no path is given."""
if path is None:
candidate = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pairs.jsonl")
if os.path.exists(candidate):
path = candidate
else:
from huggingface_hub import hf_hub_download
path = hf_hub_download("NagaYu/echocache-guard-benchmark", "pairs.jsonl", repo_type="dataset")
with open(path, encoding="utf-8") as handle:
return [json.loads(line) for line in handle if line.strip()]
def score(matcher, pairs, threshold, use_guard):
"""Guarantees: returns the confusion counts and per-relation breakdown for one configuration."""
stats = {"reused_safe": 0, "missed_safe": 0, "wrong_reuse": 0, "correct_refusal": 0}
per_relation = {}
wrong = []
for row in pairs:
verdict = matcher.match(row["query"], row["candidate"], threshold, use_guard)
reused = bool(verdict["reuse"])
bucket = per_relation.setdefault(row["relation"], {"n": 0, "ok": 0})
bucket["n"] += 1
if row["expect_reuse"]:
if reused:
stats["reused_safe"] += 1
bucket["ok"] += 1
else:
stats["missed_safe"] += 1
else:
if reused:
stats["wrong_reuse"] += 1
wrong.append((row["id"], round(verdict["similarity"], 4), row["query"][:48]))
else:
stats["correct_refusal"] += 1
bucket["ok"] += 1
safe = stats["reused_safe"] + stats["missed_safe"]
unsafe = stats["wrong_reuse"] + stats["correct_refusal"]
stats["reuse_recall"] = round(stats["reused_safe"] / safe, 4) if safe else 0.0
stats["wrong_reuse_rate"] = round(stats["wrong_reuse"] / unsafe, 4) if unsafe else 0.0
stats["accuracy"] = round((stats["reused_safe"] + stats["correct_refusal"]) / len(pairs), 4) if pairs else 0.0
return stats, per_relation, wrong
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--matcher", default=None, help="path to echocache_matcher.py (default: fetch from the Hub)")
parser.add_argument("--pairs", default=None, help="path to pairs.jsonl (default: next to this file, else the Hub)")
parser.add_argument("--thresholds", default="0.70,0.80,0.86,0.90,0.92,0.95,0.98")
args = parser.parse_args()
matcher = load_matcher(args.matcher)
pairs = load_pairs(args.pairs)
print("benchmark: %d pairs (%d may reuse, %d must not)\n" % (
len(pairs), sum(1 for p in pairs if p["expect_reuse"]), sum(1 for p in pairs if not p["expect_reuse"])))
print("%-7s %-7s %9s %12s %16s %9s" % ("thresh", "guard", "accuracy", "reuse_recall", "wrong_reuse_rate", "wrong_n"))
print("-" * 66)
for raw in args.thresholds.split(","):
threshold = float(raw)
for use_guard in (True, False):
stats, _, _ = score(matcher, pairs, threshold, use_guard)
print("%-7.2f %-7s %9.4f %12.4f %16.4f %9d" % (
threshold, "on" if use_guard else "off", stats["accuracy"],
stats["reuse_recall"], stats["wrong_reuse_rate"], stats["wrong_reuse"]))
default = getattr(matcher, "DEFAULT_THRESHOLD", 0.92)
stats, per_relation, wrong = score(matcher, pairs, default, True)
print("\nper relation at threshold %.2f, guard on:" % default)
for name in sorted(per_relation):
bucket = per_relation[name]
print(" %-26s %3d/%3d correct" % (name, bucket["ok"], bucket["n"]))
if wrong:
print("\nwrong reuse at threshold %.2f:" % default)
for entry in wrong:
print(" ", entry)
return 0
if __name__ == "__main__":
sys.exit(main())