Publish runnable public benchmark evaluator

#10
Files changed (2) hide show
  1. README.md +18 -0
  2. benchmark.py +291 -0
README.md CHANGED
@@ -66,6 +66,24 @@ At 0.5, SecureBERT2.0 flags nearly every security method. Its high F1 therefore
66
 
67
  ## Files
68
 
 
69
  - `results.jsonl`: one aggregate report per domain, track, model, and protocol.
70
  - `split-summary.json`: split sizes and whole-file SHA-256 values. It contains no private rows or repository list.
71
  - `predictions/`: public-pair probabilities for auditing the public scores. No private predictions are included.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  ## Files
68
 
69
+ - [`benchmark.py`](https://huggingface.co/datasets/perchscan/benchmark-results/blob/main/benchmark.py): run a model on the public pairs and calculate the metrics in these tables.
70
  - `results.jsonl`: one aggregate report per domain, track, model, and protocol.
71
  - `split-summary.json`: split sizes and whole-file SHA-256 values. It contains no private rows or repository list.
72
  - `predictions/`: public-pair probabilities for auditing the public scores. No private predictions are included.
73
+
74
+ ## Run the public benchmark
75
+
76
+ The Python 3 script downloads the selected public pair dataset, scores both method versions independently, saves resumable predictions, and writes a JSON metric report. To run Jev, set `TYPESAFE_API_KEY` or `PERCH_API_KEY` in your environment:
77
+
78
+ ```sh
79
+ python3 benchmark.py run --domain bug --scorer jev --predictions bug-jev.jsonl --report bug-jev.json
80
+ python3 benchmark.py run --domain security --scorer jev --predictions security-jev.jsonl --report security-jev.json
81
+ ```
82
+
83
+ To score a different model, use `--scorer command --command 'python3 your_adapter.py' --model-revision YOUR_MODEL --protocol-id YOUR_INPUT_FORMAT`. The adapter stays running, reads one JSON line containing `state`, `domain`, `role`, and `question` per method, and writes one JSON line containing `score` (a number from 0 to 1). `--limit N` performs a small resumable run; the report is written only when every method side has a score.
84
+
85
+ Recalculate a published public result without model calls:
86
+
87
+ ```sh
88
+ python3 benchmark.py score --domain bug --predictions predictions/bug/jev-1.13.0.jsonl --model-revision jev-1.13.0 --protocol-id perch-broad-v1 --report bug-jev.json
89
+ ```
benchmark.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run and score the public Perch method-pair benchmarks.
3
+
4
+ Standard-library only. The command adapter is a persistent NDJSON process: it
5
+ receives one JSON object per line and returns one {"score": probability} per line.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import hashlib
12
+ import json
13
+ import math
14
+ import os
15
+ from pathlib import Path
16
+ import shlex
17
+ import subprocess
18
+ import sys
19
+ import time
20
+ from urllib.error import HTTPError, URLError
21
+ from urllib.request import Request, urlopen
22
+
23
+
24
+ DATASET_URL = {
25
+ domain: f"https://huggingface.co/datasets/perchscan/{domain}-pairs-public/resolve/main/benchmark.jsonl"
26
+ for domain in ("bug", "security")
27
+ }
28
+ QUESTION = {
29
+ "bug": {
30
+ "type": "noul",
31
+ "instructions": "Does this method contain a concrete behavioral bug a caller can reach?",
32
+ "criteria": {
33
+ "true": "A reachable input makes the method violate its visible contract by returning a wrong result, leaving wrong state, or causing an unintended failure.",
34
+ "false": "No concrete reachable case is supported by the method and supplied context. A possible-looking pattern alone is not enough.",
35
+ },
36
+ },
37
+ "security": {
38
+ "type": "noul",
39
+ "instructions": "Does this method contain a concrete security vulnerability an attacker can reach?",
40
+ "criteria": {
41
+ "true": "A concrete path crosses a security boundary and can be exploited; name a reachable source, sensitive operation, and missing or incorrect protection.",
42
+ "false": "No concrete reachable case is supported by the method and supplied context. A possible-looking pattern alone is not enough.",
43
+ },
44
+ },
45
+ }
46
+
47
+
48
+ def dataset_bytes(domain: str, path: Path | None) -> bytes:
49
+ if path is not None:
50
+ return (path / "benchmark.jsonl" if path.is_dir() else path).read_bytes()
51
+ with urlopen(DATASET_URL[domain], timeout=120) as response:
52
+ return response.read()
53
+
54
+
55
+ def load_pairs(domain: str, path: Path | None) -> tuple[list[dict], str]:
56
+ raw = dataset_bytes(domain, path)
57
+ pairs = [json.loads(line) for line in raw.splitlines() if line]
58
+ if not pairs:
59
+ raise ValueError("Benchmark contains no pairs")
60
+ ids = set()
61
+ for pair in pairs:
62
+ if pair["domain"] != domain or pair["pair_id"] in ids:
63
+ raise ValueError("Wrong domain or duplicate pair ID in benchmark")
64
+ ids.add(pair["pair_id"])
65
+ for role in ("before", "after"):
66
+ if pair[role]["labels"][domain] not in (0, 1):
67
+ raise ValueError(f"Invalid {domain} label for {pair['pair_id']}:{role}")
68
+ return pairs, hashlib.sha256(raw).hexdigest()
69
+
70
+
71
+ def probability(value: object) -> float:
72
+ if isinstance(value, bool):
73
+ raise ValueError("Score must be a number, not a boolean")
74
+ score = float(value)
75
+ if not math.isfinite(score) or not 0 <= score <= 1:
76
+ raise ValueError(f"Score must be a finite probability in [0, 1]: {value!r}")
77
+ return score
78
+
79
+
80
+ def prediction_scores(path: Path, pairs: list[dict], domain: str,
81
+ require_complete: bool) -> dict[tuple[str, str], float]:
82
+ expected = {(pair["pair_id"], role) for pair in pairs for role in ("before", "after")}
83
+ scores = {}
84
+ if not path.exists():
85
+ if require_complete:
86
+ raise FileNotFoundError(path)
87
+ return scores
88
+ for line in path.read_text().splitlines():
89
+ if not line:
90
+ continue
91
+ row = json.loads(line)
92
+ key = (row["pair_id"], row["role"])
93
+ if key not in expected or key in scores or row.get("domain", domain) != domain:
94
+ raise ValueError(f"Unexpected or duplicate prediction: {key}")
95
+ scores[key] = probability(row["score"])
96
+ if require_complete and scores.keys() != expected:
97
+ missing = expected - scores.keys()
98
+ raise ValueError(f"Predictions are missing {len(missing)} method sides")
99
+ return scores
100
+
101
+
102
+ def average_precision(items: list[tuple[int, float]]) -> float:
103
+ positives = sum(label for label, _ in items)
104
+ if not positives:
105
+ return 0.0
106
+ ordered = sorted(items, key=lambda item: item[1], reverse=True)
107
+ found = total = 0
108
+ i = 0
109
+ while i < len(ordered):
110
+ j = i + 1
111
+ while j < len(ordered) and ordered[j][1] == ordered[i][1]:
112
+ j += 1
113
+ positives_at_score = sum(label for label, _ in ordered[i:j])
114
+ found += positives_at_score
115
+ total += found / j * positives_at_score
116
+ i = j
117
+ return total / positives
118
+
119
+
120
+ def report(pairs: list[dict], scores: dict[tuple[str, str], float], domain: str,
121
+ digest: str, model_revision: str, protocol_id: str,
122
+ threshold: float) -> dict:
123
+ items = [(pair[role]["labels"][domain], scores[pair["pair_id"], role])
124
+ for pair in pairs for role in ("before", "after")]
125
+ tp = sum(label == 1 and score >= threshold for label, score in items)
126
+ fp = sum(label == 0 and score >= threshold for label, score in items)
127
+ fn = sum(label == 1 and score < threshold for label, score in items)
128
+ tn = sum(label == 0 and score < threshold for label, score in items)
129
+ eligible = correct = ties = 0
130
+ for pair in pairs:
131
+ if pair["before"]["labels"][domain] == 1 and pair["after"]["labels"][domain] == 0:
132
+ eligible += 1
133
+ before, after = scores[pair["pair_id"], "before"], scores[pair["pair_id"], "after"]
134
+ correct += before > after
135
+ ties += before == after
136
+ precision = tp / (tp + fp) if tp + fp else 0.0
137
+ recall = tp / (tp + fn) if tp + fn else 0.0
138
+ return {
139
+ "domain": domain,
140
+ "model_revision": model_revision,
141
+ "protocol_id": protocol_id,
142
+ "threshold": threshold,
143
+ "benchmark_sha256": digest,
144
+ "benchmark_pairs": len(pairs),
145
+ "benchmark_methods": len(items),
146
+ "average_precision": average_precision(items),
147
+ "precision": precision,
148
+ "recall": recall,
149
+ "f1": 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0,
150
+ "false_positives_per_true_positive": fp / tp if tp else None,
151
+ "confusion": {"tp": tp, "fp": fp, "tn": tn, "fn": fn},
152
+ "vulnerable_or_buggy_before_above_fixed_after": {
153
+ "correct": correct, "ties": ties, "eligible": eligible,
154
+ },
155
+ }
156
+
157
+
158
+ def jev_score(state: dict, domain: str, model: str, api_url: str) -> float:
159
+ key = os.getenv("TYPESAFE_API_KEY") or os.getenv("PERCH_API_KEY")
160
+ if not key:
161
+ raise RuntimeError("Set TYPESAFE_API_KEY or PERCH_API_KEY to run Jev")
162
+ name = "bug_any" if domain == "bug" else "security_any"
163
+ payload = json.dumps({"model": model, "state": state, "questions": {name: QUESTION[domain]}}).encode()
164
+ for attempt in range(4):
165
+ request = Request(api_url, data=payload, method="POST", headers={
166
+ "Authorization": f"Bearer {key}", "Content-Type": "application/json",
167
+ })
168
+ try:
169
+ with urlopen(request, timeout=120) as response:
170
+ answer = json.load(response)
171
+ return probability(answer["answers"][name]["noul"])
172
+ except HTTPError as exc:
173
+ if exc.code not in (429, 500, 502, 503, 504) or attempt == 3:
174
+ raise RuntimeError(f"Jev request failed with HTTP {exc.code}") from None
175
+ delay = exc.headers.get("Retry-After")
176
+ time.sleep(float(delay) if delay and delay.isdigit() else 2 ** attempt)
177
+ except URLError:
178
+ if attempt == 3:
179
+ raise RuntimeError("Jev request failed after four network attempts") from None
180
+ time.sleep(2 ** attempt)
181
+ raise AssertionError("unreachable")
182
+
183
+
184
+ def run(args: argparse.Namespace) -> None:
185
+ pairs, digest = load_pairs(args.domain, args.dataset)
186
+ if args.scorer == "jev":
187
+ revision, protocol = args.model_revision or "jev-1.13.0", "perch-broad-v1"
188
+ else:
189
+ if not args.command or not args.model_revision or not args.protocol_id:
190
+ raise ValueError("Command scorer requires --command, --model-revision, and --protocol-id")
191
+ revision, protocol = args.model_revision, args.protocol_id
192
+ if args.predictions.exists():
193
+ for line in args.predictions.read_text().splitlines():
194
+ if line:
195
+ row = json.loads(line)
196
+ if row.get("model_revision") != revision or row.get("protocol_id") != protocol:
197
+ raise ValueError("Existing prediction file uses another model or protocol")
198
+ existing = prediction_scores(args.predictions, pairs, args.domain, False)
199
+ pending = [(pair, role) for pair in pairs for role in ("before", "after")
200
+ if (pair["pair_id"], role) not in existing]
201
+ if args.limit:
202
+ pending = pending[:args.limit]
203
+ command = None
204
+ if args.scorer == "command" and pending:
205
+ command = subprocess.Popen(shlex.split(args.command), stdin=subprocess.PIPE,
206
+ stdout=subprocess.PIPE, text=True, bufsize=1)
207
+ args.predictions.parent.mkdir(parents=True, exist_ok=True)
208
+ try:
209
+ with args.predictions.open("a") as output:
210
+ for index, (pair, role) in enumerate(pending, 1):
211
+ state = pair[role]["state"]
212
+ if args.scorer == "jev":
213
+ score = jev_score(state, args.domain, revision, args.api_url)
214
+ else:
215
+ request = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role,
216
+ "state": state, "question": QUESTION[args.domain]}
217
+ assert command and command.stdin and command.stdout
218
+ command.stdin.write(json.dumps(request, ensure_ascii=False) + "\n")
219
+ command.stdin.flush()
220
+ line = command.stdout.readline()
221
+ if not line:
222
+ raise RuntimeError("Model adapter stopped before returning a score")
223
+ score = probability(json.loads(line)["score"])
224
+ output.write(json.dumps({"domain": args.domain, "pair_id": pair["pair_id"],
225
+ "role": role, "score": score, "model_revision": revision,
226
+ "protocol_id": protocol}) + "\n")
227
+ output.flush()
228
+ if index % 100 == 0 or index == len(pending):
229
+ print(f"Scored {len(existing) + index}/{2 * len(pairs)} method sides", file=sys.stderr)
230
+ finally:
231
+ if command:
232
+ command.stdin.close()
233
+ try:
234
+ command.wait(timeout=30)
235
+ except subprocess.TimeoutExpired:
236
+ command.terminate()
237
+ command.wait(timeout=5)
238
+ finally:
239
+ command.stdout.close()
240
+ scores = prediction_scores(args.predictions, pairs, args.domain, False)
241
+ if len(scores) != 2 * len(pairs):
242
+ print(f"Incomplete: {len(scores)}/{2 * len(pairs)} sides; rerun to resume", file=sys.stderr)
243
+ return
244
+ result = report(pairs, scores, args.domain, digest, revision, protocol, args.threshold)
245
+ args.report.parent.mkdir(parents=True, exist_ok=True)
246
+ args.report.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n")
247
+ print(json.dumps(result, sort_keys=True))
248
+
249
+
250
+ def score_saved(args: argparse.Namespace) -> None:
251
+ pairs, digest = load_pairs(args.domain, args.dataset)
252
+ scores = prediction_scores(args.predictions, pairs, args.domain, True)
253
+ first = json.loads(next(line for line in args.predictions.read_text().splitlines() if line))
254
+ result = report(pairs, scores, args.domain, digest,
255
+ args.model_revision or first.get("model_revision", "unspecified"),
256
+ args.protocol_id or first.get("protocol_id", "unspecified"), args.threshold)
257
+ args.report.parent.mkdir(parents=True, exist_ok=True)
258
+ args.report.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n")
259
+ print(json.dumps(result, sort_keys=True))
260
+
261
+
262
+ def main() -> None:
263
+ parser = argparse.ArgumentParser(description=__doc__)
264
+ sub = parser.add_subparsers(dest="action", required=True)
265
+ for name in ("run", "score"):
266
+ command = sub.add_parser(name)
267
+ command.add_argument("--domain", choices=("bug", "security"), required=True)
268
+ command.add_argument("--dataset", type=Path, help="Local benchmark.jsonl; default downloads public pairs")
269
+ command.add_argument("--predictions", type=Path, required=True)
270
+ command.add_argument("--report", type=Path, required=True)
271
+ command.add_argument("--threshold", type=float, default=0.5)
272
+ command.add_argument("--model-revision")
273
+ command.add_argument("--protocol-id")
274
+ if name == "run":
275
+ command.add_argument("--scorer", choices=("jev", "command"), required=True)
276
+ command.add_argument("--command", help="Persistent NDJSON scorer command")
277
+ command.add_argument("--api-url", default="https://api.typesafe.ai/v1/systemone")
278
+ command.add_argument("--limit", type=int, default=0, help="Score at most N new sides, then resume later")
279
+ args = parser.parse_args()
280
+ if not 0 <= args.threshold <= 1:
281
+ parser.error("--threshold must be in [0, 1]")
282
+ if args.action == "run":
283
+ if args.limit < 0:
284
+ parser.error("--limit must be nonnegative")
285
+ run(args)
286
+ else:
287
+ score_saved(args)
288
+
289
+
290
+ if __name__ == "__main__":
291
+ main()