Datasets:
Download run_eval.py from NagaYu/canary-eval: direct link, hf CLI and curl.
- Browser
- Download file 6.42 kB
-
https://huggingface.co/datasets/NagaYu/canary-eval/resolve/main/run_eval.py
- Command line
-
hf download hf://datasets/NagaYu/canary-eval/run_eval.py
-
curl -L -o run_eval.py https://huggingface.co/datasets/NagaYu/canary-eval/resolve/main/run_eval.py
6.42 kB
| #!/usr/bin/env python3 | |
| """Evaluate the Canary contract checkers on canary-eval. | |
| python run_eval.py --engine /path/to/canary.py # a local copy of the engine | |
| python run_eval.py --from-hub # download canary.py from NagaYu/canary-contracts | |
| python run_eval.py --engine canary.py --split test --out results.json | |
| Each row gives a contract (JSON string), an output (or `samples` for `stable`) and the case context | |
| (`inputs` as a JSON string, `context`, `system_prompt`). The expected verdict is `pass`, `fail` or `skipped`. | |
| Any `error` from the engine counts as a miss. Nothing here calls a model. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import collections | |
| import importlib | |
| import json | |
| import logging | |
| import sys | |
| from pathlib import Path | |
| HERE = Path(__file__).resolve().parent | |
| def load_engine(path: str): | |
| """Imports canary.py (or app.py) by its own module name, so the engine's regex worker process can import it too.""" | |
| file = Path(path).absolute() # not resolve(): a Hub cache path is a symlink to a blob named by its hash | |
| sys.path.insert(0, str(file.parent)) | |
| return importlib.import_module(file.stem) | |
| def load_cases(split: str) -> list[dict]: | |
| """Reads data/<split>.jsonl (or both splits for 'all'); a split missing locally is downloaded from the Hub.""" | |
| splits = ["dev", "test"] if split == "all" else [split] | |
| rows = [] | |
| for name in splits: | |
| path = HERE / "data" / f"{name}.jsonl" | |
| if not path.exists(): # e.g. the GitHub checkout, which does not carry the held-out split | |
| from huggingface_hub import hf_hub_download | |
| path = hf_hub_download("NagaYu/canary-eval", f"data/{name}.jsonl", repo_type="dataset") | |
| print(f"{name}: read from the Hub (NagaYu/canary-eval)", file=sys.stderr) | |
| with open(path, encoding="utf-8") as fh: | |
| rows.extend(json.loads(line) for line in fh if line.strip()) | |
| return rows | |
| def evaluate(engine, rows: list[dict]) -> dict: | |
| """Scores every case once and returns aggregate metrics plus every miss.""" | |
| per_type = collections.defaultdict(lambda: collections.Counter()) | |
| per_lang = collections.defaultdict(lambda: collections.Counter()) | |
| per_split = collections.defaultdict(lambda: collections.Counter()) | |
| misses = [] | |
| confusion = collections.Counter() | |
| for row in rows: | |
| contract = dict(json.loads(row["contract"]), id="C", severity="critical") | |
| case = {"case_id": "k", "contract_ids": ["C"], "inputs": json.loads(row["inputs"] or "{}")} | |
| if row["context"]: | |
| case["context"] = row["context"] | |
| if row["system_prompt"]: | |
| case["system_prompt"] = row["system_prompt"] | |
| output = row["samples"] if row["samples"] else row["output"] | |
| result = engine.score_case(case, output, [contract]) | |
| if result.get("ok"): | |
| got = result["results"][0]["result"] | |
| detail = result["results"][0]["detail"] | |
| else: | |
| got, detail = "error", json.dumps(result.get("error"), ensure_ascii=False)[:300] | |
| ok = got == row["label"] | |
| confusion[(row["label"], got)] += 1 | |
| for counter in (per_type[row["contract_type"]], per_lang[row["lang"]], per_split[row["split"]]): | |
| counter["n"] += 1 | |
| counter["correct"] += ok | |
| if not ok: | |
| misses.append({"id": row["id"], "split": row["split"], "contract_type": row["contract_type"], "lang": row["lang"], | |
| "expected": row["label"], "got": got, "detail": detail, "category": row.get("category", "")}) | |
| def acc(counter): | |
| return round(counter["correct"] / counter["n"], 4) if counter["n"] else None | |
| expected_fail = sum(v for (exp, _got), v in confusion.items() if exp == "fail") | |
| expected_pass = sum(v for (exp, _got), v in confusion.items() if exp == "pass") | |
| missed_fail = sum(v for (exp, got), v in confusion.items() if exp == "fail" and got != "fail") | |
| false_alarm = sum(v for (exp, got), v in confusion.items() if exp == "pass" and got != "pass") | |
| total = sum(per_split[s]["n"] for s in per_split) | |
| correct = sum(per_split[s]["correct"] for s in per_split) | |
| return { | |
| "cases": total, | |
| "accuracy": round(correct / total, 4) if total else None, | |
| "fail_recall": round(1 - missed_fail / expected_fail, 4) if expected_fail else None, | |
| "false_alarm_rate": round(false_alarm / expected_pass, 4) if expected_pass else None, | |
| "per_split": {k: {"n": v["n"], "accuracy": acc(v)} for k, v in sorted(per_split.items())}, | |
| "per_contract_type": {k: {"n": v["n"], "accuracy": acc(v)} for k, v in sorted(per_type.items())}, | |
| "per_lang": {k: {"n": v["n"], "accuracy": acc(v)} for k, v in sorted(per_lang.items())}, | |
| "confusion": {f"{exp}->{got}": v for (exp, got), v in sorted(confusion.items())}, | |
| "misses": misses, | |
| } | |
| def main() -> int: | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| src = parser.add_mutually_exclusive_group(required=True) | |
| src.add_argument("--engine", help="path to canary.py (or app.py of the Gradio build)") | |
| src.add_argument("--from-hub", action="store_true", help="download canary.py from NagaYu/canary-contracts") | |
| parser.add_argument("--split", default="test", choices=["dev", "test", "all"]) | |
| parser.add_argument("--out", help="write the full report (including misses) to this JSON file") | |
| args = parser.parse_args() | |
| logging.disable(logging.CRITICAL) | |
| path = args.engine | |
| if args.from_hub: | |
| from huggingface_hub import hf_hub_download | |
| path = hf_hub_download("NagaYu/canary-contracts", "canary.py") | |
| engine = load_engine(path) | |
| report = evaluate(engine, load_cases(args.split)) | |
| report["engine"] = f"{engine.APP_NAME} {engine.APP_VERSION}" | |
| summary = {k: v for k, v in report.items() if k != "misses"} | |
| print(json.dumps(summary, indent=2, ensure_ascii=False)) | |
| print(f"\n{len(report['misses'])} miss(es)") | |
| for m in report["misses"]: | |
| print(f" {m['id']:10s} {m['contract_type']:16s} {m['lang']} expected {m['expected']:7s} got {m['got']:7s} {m['detail'][:90]}") | |
| if args.out: | |
| Path(args.out).write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |