File size: 10,885 Bytes
96dc6b1 | 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 | #!/usr/bin/env python3
"""Score Perch benchmark methods with TypeLLM's hosted boolean API.
Every method side is an independent request. Applicable bug/security questions
share that request; a semantic-lint pair uses its same ensure rule on both sides.
The JSONL predictions are append-only and can be resumed after interruption.
"""
from __future__ import annotations
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
import hashlib
import importlib.util
import json
import math
import os
from pathlib import Path
import random
import sys
import threading
import time
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
MODEL = "typellm-latest"
API = "https://api.typellm.ai/v1/generate"
PROTOCOL = "typellm-boolean-v1"
LINT_PROTOCOL = "perch-semantic-ensure-v1"
DEFAULT_INTERVAL = 0.62 # Below the documented account cap of 100 requests/minute.
def module_at(name: str, path: Path):
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ValueError(f"Cannot import {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def probability(value: object) -> float:
if isinstance(value, bool):
raise ValueError("Boolean is not a probability")
score = float(value)
if not math.isfinite(score) or not 0 <= score <= 1:
raise ValueError("Invalid probability")
return score
class RateLimiter:
def __init__(self, interval: float):
self.interval = interval
self.lock = threading.Lock()
self.next_at = time.monotonic()
def wait(self):
with self.lock:
now = time.monotonic()
at = max(now, self.next_at)
self.next_at = at + self.interval
if at > now:
time.sleep(at - now)
def back_off(self, seconds: float):
with self.lock:
self.next_at = max(self.next_at, time.monotonic() + seconds)
def type_question(question: dict) -> dict:
item = question["question"]
true = str(item["criteria"]["true"]).strip()
false = str(item["criteria"]["false"]).strip()
return {
"type": "boolean",
"instructions": f'{item["instructions"].strip()}\nTrue: {true}\nFalse: {false}',
"return_probabilities": True,
}
def lint_question(ensure: str) -> dict:
rule = " ".join(ensure.split())
return {
"type": "boolean",
"instructions": f"Is `rule` true of the code below?\nRule: {rule}\nTrue: {rule}\nFalse: Not so: {rule}",
"return_probabilities": True,
}
def true_score(result: dict) -> float:
values = result.get("probabilities")
if not isinstance(values, dict) or "true" not in values or "false" not in values:
raise ValueError("TypeLLM did not return both boolean probabilities")
true, false = probability(values["true"]), probability(values["false"])
if abs(true + false - 1) > 1e-5:
raise ValueError("Boolean probabilities do not sum to one")
return true
def invoke(key: str, state: dict, questions: dict, limiter: RateLimiter) -> dict:
context = "Perch method context (JSON):\n" + json.dumps(state, ensure_ascii=False, separators=(",", ":"))
payload = json.dumps({"model": MODEL, "context": context, "questions": questions,
"options": {"temperature": 0}, "timeout": 90}, ensure_ascii=False).encode()
headers = {"Authorization": "Bearer " + key, "Content-Type": "application/json"}
for attempt in range(8):
limiter.wait()
started = time.monotonic()
request = Request(API, data=payload, headers=headers, method="POST")
try:
with urlopen(request, timeout=105) as response:
data = json.load(response)
if data.get("model") != MODEL or set(data.get("result", {})) != set(questions):
raise ValueError("TypeLLM returned a different model or incomplete result")
data["request_elapsed_s"] = round(time.monotonic() - started, 3)
return data
except HTTPError as exc:
if exc.code not in (429, 502, 503, 504) or attempt == 7:
raise RuntimeError(f"TypeLLM HTTP {exc.code}") from None
header = exc.headers.get("Retry-After")
try:
delay = max(1.0, min(90.0, float(header)))
except (ValueError, TypeError):
delay = min(60.0, 2.0 ** attempt)
limiter.back_off(delay)
time.sleep(delay + random.random() * 0.2)
except URLError:
if attempt == 7:
raise RuntimeError("TypeLLM transport failed after retries") from None
time.sleep(min(30, 2 ** attempt))
raise AssertionError("unreachable")
def load_pairs(path: Path, track: str):
raw = path.read_bytes()
pairs = [json.loads(line) for line in raw.splitlines() if line]
if not pairs:
raise ValueError("Empty benchmark")
seen = set()
for pair in pairs:
pair_id = pair["pair_id"]
if pair_id in seen:
raise ValueError("Duplicate pair ID")
seen.add(pair_id)
if track != "lint" and pair["domain"] != track:
raise ValueError("Wrong benchmark domain")
if track == "lint" and not pair.get("rule", {}).get("ensure"):
raise ValueError("Missing semantic lint rule")
return pairs, hashlib.sha256(raw).hexdigest()
def saved_predictions(path: Path, pairs: list[dict], digest: str, track: str, pack: dict | None):
expected = {(pair["pair_id"], role) for pair in pairs for role in ("before", "after")}
rows = {}
if not path.exists():
return rows
for line in path.open():
row = json.loads(line)
key = row["pair_id"], row["role"]
if key not in expected or key in rows or row["dataset_sha256"] != digest:
raise ValueError("Unexpected or duplicate saved prediction")
if track == "lint":
if row["protocol"] != LINT_PROTOCOL or row["model"] != MODEL:
raise ValueError("Incompatible saved lint prediction")
if abs(probability(row["score"]) + probability(row["rule_true_probability"]) - 1) > 1e-8:
raise ValueError("Invalid saved lint score")
else:
if (row["protocol_id"] != pack["protocol_id"] or row.get("interface_id") != PROTOCOL
or row["model_revision"] != MODEL
or row["pack_sha256"] != pack["pack_sha256"]):
raise ValueError("Incompatible saved scan prediction")
rows[key] = row
return rows
def score_one(pair: dict, role: str, track: str, pack: dict | None, core,
key: str, digest: str, limiter: RateLimiter, threshold: float) -> dict:
state = pair[role]["state"]
if track == "lint":
questions = {"rule_true": lint_question(pair["rule"]["ensure"])}
else:
selected = core.detection_questions(core.scan_questions(pack, track, pair["language"]), track)
questions = {question["name"]: type_question(question) for question in selected}
if not questions:
raise ValueError("No applicable detection questions")
response = invoke(key, state, questions, limiter)
usage = response.get("usage") or {}
if track == "lint":
true = true_score(response["result"]["rule_true"])
return {"pair_id": pair["pair_id"], "role": role, "domain": pair["domain"],
"model": MODEL, "protocol": LINT_PROTOCOL, "dataset_sha256": digest,
"rule_true_probability": true, "score": 1 - true,
"usage": usage, "elapsed_s": response["request_elapsed_s"]}
scores = {name: core.raised_score(question, true_score(response["result"][name]))
for question in selected for name in (question["name"],)}
score, alert = core.scan_result(scores, selected, track, threshold)
return {"pair_id": pair["pair_id"], "role": role, "domain": track,
"model_id": "typellm", "model_revision": MODEL,
"protocol_id": pack["protocol_id"], "interface_id": PROTOCOL,
"pack_sha256": pack["pack_sha256"],
"dataset_sha256": digest, "question_scores": scores,
"score": score, "alert": alert, "usage": usage,
"elapsed_s": response["request_elapsed_s"]}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--track", choices=("bug", "security", "lint"), required=True)
parser.add_argument("--dataset", type=Path, required=True)
parser.add_argument("--predictions", type=Path, required=True)
parser.add_argument("--question-pack", type=Path, default=Path(__file__).with_name("question-pack.json"))
parser.add_argument("--benchmark-script", type=Path, default=Path(__file__).with_name("benchmark.py"))
parser.add_argument("--threshold", type=float, default=0.5)
parser.add_argument("--workers", type=int, default=8)
parser.add_argument("--interval", type=float, default=DEFAULT_INTERVAL)
parser.add_argument("--limit", type=int, default=0)
args = parser.parse_args()
if not 0 <= args.threshold <= 1 or args.workers < 1 or args.interval < 0.6 or args.limit < 0:
parser.error("Invalid threshold, workers, interval, or limit")
key = os.environ.get("TYPELLM_API_KEY")
if not key:
raise RuntimeError("Set TYPELLM_API_KEY")
core = module_at("perch_benchmark", args.benchmark_script) if args.track != "lint" else None
pack = core.load_pack(args.question_pack) if core else None
pairs, digest = load_pairs(args.dataset, args.track)
existing = saved_predictions(args.predictions, pairs, digest, args.track, pack)
pending = [(pair, role) for pair in pairs for role in ("before", "after")
if (pair["pair_id"], role) not in existing]
if args.limit:
pending = pending[:args.limit]
if not pending:
print(f"{args.track}: already complete", flush=True)
return
args.predictions.parent.mkdir(parents=True, exist_ok=True)
limiter = RateLimiter(args.interval)
with args.predictions.open("a") as output, ThreadPoolExecutor(max_workers=args.workers) as pool:
futures = [pool.submit(score_one, pair, role, args.track, pack, core, key, digest,
limiter, args.threshold)
for pair, role in pending]
for index, future in enumerate(as_completed(futures), 1):
row = future.result()
output.write(json.dumps(row, sort_keys=True) + "\n")
output.flush()
if index % 100 == 0 or index == len(pending):
print(f"{args.track}: {len(existing) + index}/{2 * len(pairs)} sides", flush=True)
if __name__ == "__main__":
main()
|