#!/usr/bin/env python3 """Run GuardBench. Scoring never reports a single accuracy number, because the item classes are unbalanced (32 unsafe, 8 safe) and raw accuracy rewards a model that always says VULNERABLE. The headline is balanced accuracy - the mean of per-class recall - so always-vulnerable and always-safe both score 50 percent. Verdicts are parsed from a required final line. A missing line is a scored failure. Each item is asked three ways, because a model whose verdict line depends on the exact prompt phrasing is not reliable and the benchmark should surface that rather than pick its best wording. """ import os, sys, json, re, argparse, time from collections import Counter, defaultdict ROOT = os.path.expanduser("~/loreacyber-ft") sys.path.insert(0, os.path.join(ROOT, "eval")) from raw_generation import build_chat_prompt, generate_raw SYS = ("You are a security code reviewer. Follow the data flow from untrusted input to the sink, " "and check whether any guard that exists is actually applied to the value that reaches it " "and addresses the weakness in question.\n\n" "End your reply with exactly one line, nothing after it:\n" "VERDICT: VULNERABLE \n" "or\n" "VERDICT: SAFE") PROMPTS = [ "Review this code for security problems.\n\n{code}", "Analyze this code for security issues:\n\n{code}", "Is there a vulnerability in this code? Explain your reasoning.\n\n{code}", ] VERDICT = re.compile(r"^\s*VERDICT:\s*(VULNERABLE|SAFE)\b(.*)$", re.I | re.M) def parse(text): if "" in text: text = text.split("")[-1] ms = list(VERDICT.finditer(text)) if not ms: return None, None return ms[-1].group(1).upper(), ms[-1].group(2).strip() def wilson(k, n, z=1.96): if n == 0: return (0.0, 0.0) p = k / n; d = 1 + z*z/n c = (p + z*z/(2*n)) / d m = z * ((p*(1-p) + z*z/(4*n))/n) ** 0.5 / d return max(0.0, c-m), min(1.0, c+m) def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", default="/Volumes/ASAFE/strix/qwen38-27b-4bit") ap.add_argument("--adapter", default=None) ap.add_argument("--tag", required=True) ap.add_argument("--max-tokens", type=int, default=400) ap.add_argument("--prompts", type=int, default=3, help="how many phrasings per item") ap.add_argument("--items", default=os.path.join(ROOT, "guardbench/items.jsonl")) ap.add_argument("--outdir", default=os.path.join(ROOT, "guardbench/results")) a = ap.parse_args() items = [json.loads(l) for l in open(a.items) if l.strip()] os.makedirs(a.outdir, exist_ok=True) partial = os.path.join(a.outdir, f"partial_{a.tag}.jsonl") done, rows = set(), [] if os.path.exists(partial): for line in open(partial): try: r = json.loads(line); done.add((r["id"], r["prompt"])); rows.append(r) except Exception: pass print(f"resuming: {len(rows)} generations already on disk", flush=True) fh = open(partial, "a") from mlx_lm import load, stream_generate from mlx_lm.sample_utils import make_sampler m, tok = load(a.model, adapter_path=a.adapter) s = make_sampler(temp=0.0) t0 = time.time() total = len(items) * a.prompts for i, it in enumerate(items): for pi in range(a.prompts): if (it["id"], pi) in done: continue g = generate_raw(stream_generate, m, tok, build_chat_prompt(tok, SYS, PROMPTS[pi].format(code=it["code"]), enable_thinking=False), max_tokens=a.max_tokens, sampler=s) v, cls = parse(g["raw_output"]) want = "VULNERABLE" if it["label"] == "unsafe" else "SAFE" row = dict(id=it["id"], pattern=it["pattern"], shape=it["shape"], label=it["label"], prompt=pi, verdict=v, verdict_class=cls, correct=(v == want), tokens=g["generation_tokens"], finish=g["finish_reason"], output=g["raw_output"]) rows.append(row) fh.write(json.dumps(row) + "\n"); fh.flush() done = (i+1) * a.prompts if (i+1) % 5 == 0: r = done / (time.time()-t0) print(f" {done}/{total} eta {(total-done)/r/60:.0f}m", flush=True) fh.close() out = os.path.join(a.outdir, f"guardbench_{a.tag}.json") json.dump(dict(tag=a.tag, model=a.model, adapter=a.adapter, rows=rows), open(out, "w"), indent=1) report(rows, a.tag, out) def report(rows, tag, path=None): n = len(rows) byshape = defaultdict(list) for r in rows: byshape[r["shape"]].append(r) safe = [r for r in rows if r["label"] == "safe"] unsafe = [r for r in rows if r["label"] == "unsafe"] rec_safe = sum(r["correct"] for r in safe) / max(1, len(safe)) rec_unsafe = sum(r["correct"] for r in unsafe) / max(1, len(unsafe)) bal = (rec_safe + rec_unsafe) / 2 nov = sum(1 for r in rows if r["verdict"] is None) print(f"\n=== GuardBench: {tag} ===") print(f" BALANCED ACCURACY {bal:.1%} <- headline (always-vuln and always-safe both score 50%)") print(f" recall on unsafe {rec_unsafe:.1%} ({sum(r['correct'] for r in unsafe)}/{len(unsafe)})") print(f" recall on safe {rec_safe:.1%} ({sum(r['correct'] for r in safe)}/{len(safe)})") print(f" raw accuracy {sum(r['correct'] for r in rows)/n:.1%} (do not quote this alone)") print(f" no verdict line {nov}/{n} = {nov/n:.1%} <- brittleness") print("\n by shape:") for sh in ("none","covers","wrong_value","irrelevant","elsewhere"): rs = byshape.get(sh, []) if not rs: continue k = sum(r["correct"] for r in rs) lo, hi = wilson(k, len(rs)) note = {"covers":"false alarms here", "irrelevant":"the guard-is-enough trap", "elsewhere":"helper exists, call site skips it", "wrong_value":"guard on the sibling value"}.get(sh, "") print(f" {sh:12} {k:>3}/{len(rs):<3} = {k/len(rs):>6.1%} [{lo:.0%},{hi:.0%}] {note}") print("\n by prompt phrasing (verdict-line rate):") for pi in sorted({r["prompt"] for r in rows}): rs = [r for r in rows if r["prompt"] == pi] got = sum(1 for r in rs if r["verdict"] is not None) k = sum(r["correct"] for r in rs) print(f" prompt {pi} verdict {got}/{len(rs)} correct {k/len(rs):.1%}") tk = sorted(r["tokens"] for r in rows) print(f"\n median tokens {tk[len(tk)//2]}") if path: print(f" saved {path}") if __name__ == "__main__": main()