File size: 4,358 Bytes
16d01ee | 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 | """Score detectors on the terse held-out set. Reuses the protocol of SamJoshua/tool-output-injection-bench
(code/evaluate.py): fp32 CPU, max_length 512, positive label from config.id2label, argmax decision (= P(positive) > 0.5
for these two-class models), sanity pair before scoring, no threshold tuning."""
import json, sys, time, gc
from collections import defaultdict
import torch
import os
from huggingface_hub import hf_hub_download
for _f in ("evaluate.py", "baseline.py"): # bench protocol code from SamJoshua/tool-output-injection-bench
_p = hf_hub_download("SamJoshua/tool-output-injection-bench", f"code/{_f}", repo_type="dataset")
sys.path.insert(0, os.path.dirname(_p))
import evaluate as E
from baseline import is_injection as regex_flag
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import transformers
torch.manual_seed(0); torch.set_num_threads(6)
rows = [json.loads(l) for l in open("data/terse_heldout.jsonl")]
texts = [r["text"] for r in rows]
H = "Horizon-Labs/prompt-injection-guard-small"
MODELS = [(H, "v2.3"), (H, "v2.6"), ("fmops/distilbert-prompt-injection", "c5da1fefd33c98c447b50dd806fe86aeb9e8c26c"), ("protectai/deberta-v3-base-prompt-injection-v2", "90c9989b1a342275dd0d1a95aad283c04e075671"),
("deepset/deberta-v3-base-injection", "80dda00d0b0d9a03917a7685e2ddbcd28e04dbb1"), ("patronus-studio/wolf-defender-prompt-injection", "af0b16a1d40ca246595e48246ccf9f906a52a50e")]
def summarize(flags):
out = {"overall": {}, "by_format": defaultdict(dict), "by_wrapper": defaultdict(dict), "by_attack_type": {}, "by_carrier": {}}
def rate(sel):
n = len(sel); k = sum(flags[i] for i in sel); return {"flagged": k, "n": n, "rate": round(k / n, 4) if n else None}
ben = [i for i, r in enumerate(rows) if not r["label"]]; att = [i for i, r in enumerate(rows) if r["label"]]
out["overall"] = {"benign_flagged": rate(ben), "attack_caught": rate(att)}
tp = sum(flags[i] for i in att); fp = sum(flags[i] for i in ben); fn = len(att) - tp
p, rc, f1 = E.prf(tp, fp, fn); out["overall"].update(precision=p, recall=rc, f1=f1)
for key, dest in [("format", "by_format"), ("wrapper", "by_wrapper")]:
for v in sorted({r[key] for r in rows}):
out[dest][v]["benign_flagged"] = rate([i for i in ben if rows[i][key] == v])
out[dest][v]["attack_caught"] = rate([i for i in att if rows[i][key] == v])
for key, dest in [("attack_type", "by_attack_type"), ("carrier", "by_carrier")]:
for v in sorted({rows[i][key] for i in att}):
out[dest][v] = rate([i for i in att if rows[i][key] == v])
return out
doc = {"protocol": "argmax over labels (P(positive)>0.5), fp32 CPU, max_length 512, no threshold tuning",
"transformers": transformers.__version__, "torch": torch.__version__, "n_rows": len(rows),
"n_benign": sum(1 for r in rows if not r["label"]), "n_attack": sum(r["label"] for r in rows), "models": []}
preds = {}
flags = [regex_flag(t) for t in texts]
doc["models"].append({"name": "regex-keyword-v1", "revision": None, **summarize(flags)}); preds["regex-keyword-v1"] = [{"flagged": f} for f in flags]
for repo, rev in MODELS:
name = repo + (f"@{rev}" if rev and rev.startswith("v") else "") # other models pinned to the bench revisions; print("scoring", name, flush=True)
tok = AutoTokenizer.from_pretrained(repo, revision=rev)
m = AutoModelForSequenceClassification.from_pretrained(repo, revision=rev, torch_dtype=torch.float32).float().eval()
pos, src = E.resolve_positive(m.config.id2label, repo)
chk = E.sanity(m, tok, pos)
if not chk["ok"]:
doc["models"].append({"name": name, "status": "label_check_failed"}); continue
t0 = time.time(); f, p, lab = E.score_texts(m, tok, texts, pos, 16)
rec = {"name": name, "revision": getattr(m.config, "_commit_hash", None), "label_source": src, "seconds": round(time.time() - t0, 1), **summarize(f)}
doc["models"].append(rec); preds[name] = [{"flagged": a, "prob": b} for a, b in zip(f, p)]
print(" ", rec["overall"], flush=True)
del m; gc.collect()
json.dump(doc, open("results/eval_results.json", "w"), indent=1)
with open("results/predictions.jsonl", "w") as fh:
for i, r in enumerate(rows):
fh.write(json.dumps({"id": r["id"], **{n: preds[n][i] for n in preds}}) + "\n")
print("done")
|