sieve-eval / run_eval.py
NagaYu's picture
sieve-eval: dev and held-out splits, run_eval.py, Sieve 1.0.0 results
39ec9ad verified
Raw History Blame Contribute Delete
8.65 kB
#!/usr/bin/env python3
"""Evaluate the Sieve engine on sieve-eval.
python run_eval.py --split test # engine: sieve.py from the Hub model repo
python run_eval.py --split dev --engine ../../app.py # engine: a local file (app.py and sieve.py are identical)
python run_eval.py --split test --out results.json # also write every metric and every miss as JSON
Two tasks are scored:
* chunk_safety - one retrieved chunk -> is it unsafe to pass on (prompt injection, hidden instructions,
exfiltration lures, high-confidence secrets)? Scored with Sieve's own chunk verdict.
* rag_diagnosis - (question, retrieved chunks[, answer]) -> Sieve's audit. A case passes only if every
expectation it carries holds: the verdict, the diagnosis flags and the per-claim status.
The script needs pandas (the engine's only hard dependency besides the standard library). Gradio is optional.
If a split file is missing locally it is downloaded from the Hub (NagaYu/sieve-eval).
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import sys
from collections import defaultdict
from pathlib import Path
HERE = Path(__file__).resolve().parent
DATASET_REPO = "NagaYu/sieve-eval"
MODEL_REPO = "NagaYu/sieve-rag-auditor"
TASKS = ("chunk_safety", "rag_diagnosis")
def load_engine(path: str | None):
"""Guarantees: imports the Sieve engine from a local file, or downloads sieve.py from the model repo when no path is given."""
if not path:
from huggingface_hub import hf_hub_download
path = hf_hub_download(MODEL_REPO, "sieve.py")
spec = importlib.util.spec_from_file_location("sieve_engine", path)
mod = importlib.util.module_from_spec(spec)
sys.modules["sieve_engine"] = mod
spec.loader.exec_module(mod)
return mod
def load_rows(task: str, split: str) -> list[dict]:
"""Guarantees: returns the rows of one task/split, fetching the file from the Hub if it is not present locally."""
local = HERE / "data" / task / f"{split}.jsonl"
if not local.exists():
from huggingface_hub import hf_hub_download
local = Path(hf_hub_download(DATASET_REPO, f"data/{task}/{split}.jsonl", repo_type="dataset"))
return [json.loads(line) for line in local.read_text(encoding="utf-8").split("\n") if line.strip()]
def eval_safety(engine, rows: list[dict]) -> dict:
"""Guarantees: scores every chunk_safety row with the engine's chunk verdict and returns metrics plus every miss."""
by = defaultdict(lambda: {"n": 0, "correct": 0})
tp = fp = tn = fn = 0
misses = []
for r in rows:
threats = engine.scan_injection({"text": r["text"]})
secrets = engine.scan_sensitive({"text": r["text"]})
if not isinstance(threats, list) or not isinstance(secrets, list):
pred, reasons = "error", ["a scan failed"]
else:
unsafe, reasons = engine._chunk_unsafe(threats, secrets)
pred = "unsafe" if unsafe is True else "safe" if unsafe is False else "error"
ok = pred == r["label"]
for key in ("all", f"lang:{r['lang']}", f"label:{r['label']}"):
by[key]["n"] += 1
by[key]["correct"] += int(ok)
if r["label"] == "unsafe":
tp += pred == "unsafe"
fn += pred != "unsafe"
else:
fp += pred != "safe"
tn += pred == "safe"
if not ok:
fams = sorted({f"{t['family']}/{t['pattern']}/{t['severity']}" for t in threats}) if isinstance(threats, list) else []
misses.append({"id": r["id"], "label": r["label"], "predicted": pred, "lang": r["lang"],
"text": r["text"][:300], "findings": fams, "reasons": reasons, "note": r.get("note", "")})
return {
"n": len(rows),
"accuracy": round(by["all"]["correct"] / max(1, by["all"]["n"]), 4),
"attack_recall": round(tp / max(1, tp + fn), 4),
"false_alarm_rate": round(fp / max(1, fp + tn), 4),
"by": {k: {"n": v["n"], "accuracy": round(v["correct"] / max(1, v["n"]), 4)} for k, v in sorted(by.items())},
"misses": misses,
}
def _claim_status(result: dict, substring: str) -> str | None:
"""Guarantees: returns the status of the first attributed claim whose text contains the substring (None if no claim does)."""
for c in (result.get("attribution") or {}).get("claim_attribution") or []:
if substring in (c.get("claim") or ""):
return c.get("status")
return None
def eval_rag(engine, rows: list[dict]) -> dict:
"""Guarantees: audits every rag_diagnosis row and returns per-expectation and per-case accuracy plus every failed case."""
by = defaultdict(lambda: {"n": 0, "passed": 0})
exp = {"verdict": [0, 0], "flags": [0, 0], "claims": [0, 0]}
failures = []
for r in rows:
res = engine._audit_impl(r["query"], r["chunks"], r.get("answer"), mode=r["mode"], record=False, enrich=False)
problems = []
if r.get("expected_verdict"):
exp["verdict"][1] += 1
if res.get("verdict") == r["expected_verdict"]:
exp["verdict"][0] += 1
else:
problems.append(f"verdict {res.get('verdict')!r} != expected {r['expected_verdict']!r}")
for f in r.get("expected_flags") or []:
exp["flags"][1] += 1
got = (res.get("diagnosis") or {}).get(f["flag"])
ok = (got is True) if f["value"] else (got is not True)
exp["flags"][0] += int(ok)
if not ok:
problems.append(f"diagnosis.{f['flag']} = {got!r}, expected {'true' if f['value'] else 'not true'}")
for c in r.get("expected_claims") or []:
exp["claims"][1] += 1
got = _claim_status(res, c["substring"])
exp["claims"][0] += int(got == c["status"])
if got != c["status"]:
problems.append(f"claim {c['substring']!r}: {got!r} != expected {c['status']!r}")
passed = not problems
for key in ("all", f"lang:{r['lang']}", f"mode:{r['mode']}"):
by[key]["n"] += 1
by[key]["passed"] += int(passed)
if not passed:
failures.append({"id": r["id"], "lang": r["lang"], "mode": r["mode"], "query": r["query"][:200],
"verdict": res.get("verdict"), "problems": problems, "note": r.get("note", "")})
return {
"n": len(rows),
"case_accuracy": round(by["all"]["passed"] / max(1, by["all"]["n"]), 4),
"verdict_accuracy": round(exp["verdict"][0] / max(1, exp["verdict"][1]), 4) if exp["verdict"][1] else None,
"flag_accuracy": round(exp["flags"][0] / max(1, exp["flags"][1]), 4) if exp["flags"][1] else None,
"claim_accuracy": round(exp["claims"][0] / max(1, exp["claims"][1]), 4) if exp["claims"][1] else None,
"expectations": {k: {"correct": v[0], "total": v[1]} for k, v in exp.items()},
"by": {k: {"n": v["n"], "accuracy": round(v["passed"] / max(1, v["n"]), 4)} for k, v in sorted(by.items())},
"failures": failures,
}
def main() -> int:
"""Guarantees: evaluates the requested split, prints a summary, optionally writes the full report, and returns 0."""
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--split", default="test", choices=("dev", "test"))
ap.add_argument("--engine", default=None, help="path to sieve.py / app.py (default: download from the model repo)")
ap.add_argument("--out", default=None, help="write the full report (metrics and every miss) to this JSON file")
a = ap.parse_args()
engine = load_engine(a.engine)
report = {"split": a.split, "engine_version": getattr(engine, "SIEVE_VERSION", "?"),
"chunk_safety": eval_safety(engine, load_rows("chunk_safety", a.split)),
"rag_diagnosis": eval_rag(engine, load_rows("rag_diagnosis", a.split))}
cs, rd = report["chunk_safety"], report["rag_diagnosis"]
print(f"sieve {report['engine_version']} on sieve-eval/{a.split}")
print(f" chunk_safety : n={cs['n']} accuracy={cs['accuracy']:.1%} attack recall={cs['attack_recall']:.1%} "
f"false alarms={cs['false_alarm_rate']:.1%} misses={len(cs['misses'])}")
print(f" rag_diagnosis: n={rd['n']} case accuracy={rd['case_accuracy']:.1%} failures={len(rd['failures'])}")
if a.out:
Path(a.out).write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
return 0
if __name__ == "__main__":
sys.exit(main())