terse-tool-output-heldout / code /ansi_ablation.py
SamJoshua's picture
Add terse tool-output held-out test set (400 rows) and results
16d01ee verified
Raw History Blame Contribute Delete
1.71 kB
"""Controlled check: same benign inner lines, plain vs wrapped in ANSI colour codes (green, as most CLIs print 'ok')."""
import json, sys, 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 transformers import AutoTokenizer, AutoModelForSequenceClassification
torch.set_num_threads(6)
rows = [json.loads(l) for l in open("data/terse_heldout.jsonl")]
inner = sorted({r["inner_text"] for r in rows if not r["label"]})
att = sorted({r["inner_text"] for r in rows if r["label"]})
ansi = lambda t: "\n".join(f"\x1b[32m{l}\x1b[0m" for l in t.split("\n"))
out = {"n_benign_unique_inner": len(inner), "n_attack_unique_inner": len(att)}
H = "Horizon-Labs/prompt-injection-guard-small"
for repo, rev in [(H, "v2.3"), (H, "v2.6"), ("patronus-studio/wolf-defender-prompt-injection", "af0b16a1d40ca246595e48246ccf9f906a52a50e")]:
tok = AutoTokenizer.from_pretrained(repo, revision=rev); m = AutoModelForSequenceClassification.from_pretrained(repo, revision=rev).float().eval()
pos, _ = E.resolve_positive(m.config.id2label, repo)
res = {}
for k, ts in [("benign_plain", inner), ("benign_ansi", [ansi(t) for t in inner]), ("attack_plain", att), ("attack_ansi", [ansi(t) for t in att])]:
f, p, _ = E.score_texts(m, tok, ts, pos, 16); res[k] = {"flagged": sum(f), "n": len(f)}
out[repo + "@" + rev[:7]] = res; print(repo, rev[:7], res, flush=True)
json.dump(out, open("results/ansi_ablation.json", "w"), indent=1)