"""Evaluate a trained model on the template-disjoint test split and the hand-written challenge set. Writes outputs/eval/metrics.json and a confusion matrix. Usage: python src/evaluate.py --model outputs/model --data data """ import argparse import json import os import sys import numpy as np import torch from sklearn.metrics import classification_report, confusion_matrix from transformers import AutoModelForSequenceClassification, AutoTokenizer sys.path.insert(0, os.path.dirname(__file__)) from templates import LABELS # noqa: E402 BENIGN = LABELS.index("benign") def load(path): with open(path) as f: return [json.loads(l) for l in f if l.strip()] @torch.no_grad() def predict(model, tok, texts, bs=64): preds, probs = [], [] for i in range(0, len(texts), bs): b = tok(texts[i:i + bs], truncation=True, max_length=128, padding=True, return_tensors="pt") p = model(**b).logits.softmax(-1) probs.append(p.numpy()) preds.extend(p.argmax(-1).tolist()) return np.array(preds), np.concatenate(probs) def summarize(rows, preds): y = np.array([LABELS.index(r["label"]) for r in rows]) rep = classification_report(y, preds, labels=list(range(len(LABELS))), target_names=LABELS, output_dict=True, zero_division=0) cm = confusion_matrix(y, preds, labels=list(range(len(LABELS)))) is_mal, pred_mal = y != BENIGN, preds != BENIGN binary = { "false_positive_rate": float((pred_mal & ~is_mal).sum() / max(1, (~is_mal).sum())), "detection_rate": float((pred_mal & is_mal).sum() / max(1, is_mal.sum())), "false_negative_rate": float((~pred_mal & is_mal).sum() / max(1, is_mal.sum())), } by_lang = {} for lang in sorted({r.get("language", "?") for r in rows}): m = np.array([r.get("language") == lang for r in rows]) by_lang[lang] = {"n": int(m.sum()), "accuracy": float((preds[m] == y[m]).mean())} return {"n": len(rows), "accuracy": float((preds == y).mean()), "report": rep, "confusion_matrix": cm.tolist(), "binary": binary, "by_language": by_lang} def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", default="outputs/model") ap.add_argument("--data", default="data") ap.add_argument("--out", default="outputs/eval") args = ap.parse_args() os.makedirs(args.out, exist_ok=True) tok = AutoTokenizer.from_pretrained(args.model) model = AutoModelForSequenceClassification.from_pretrained(args.model).eval() results = {} for name, path in [("test", f"{args.data}/test.jsonl"), ("challenge", f"{args.data}/challenge.jsonl")]: if not os.path.exists(path): continue rows = load(path) preds, _ = predict(model, tok, [r["text"] for r in rows]) results[name] = summarize(rows, preds) results[name]["errors"] = [ {"text": r["text"], "label": r["label"], "pred": LABELS[p]} for r, p in zip(rows, preds) if LABELS[p] != r["label"]][:50] s = results[name] print(f"\n== {name} (n={s['n']}) accuracy={s['accuracy']:.4f} " f"macroF1={s['report']['macro avg']['f1-score']:.4f} " f"FPR={s['binary']['false_positive_rate']:.4f} DR={s['binary']['detection_rate']:.4f}") for l in LABELS: r = s["report"][l] print(f" {l:24s} P={r['precision']:.3f} R={r['recall']:.3f} F1={r['f1-score']:.3f} n={int(r['support'])}") with open(os.path.join(args.out, "metrics.json"), "w") as f: json.dump(results, f, indent=1) try: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt cm = np.array(results["test"]["confusion_matrix"]) fig, ax = plt.subplots(figsize=(7.5, 6.5)) ax.imshow(cm, cmap="Blues") ax.set_xticks(range(len(LABELS)), LABELS, rotation=45, ha="right") ax.set_yticks(range(len(LABELS)), LABELS) for i in range(len(LABELS)): for j in range(len(LABELS)): ax.text(j, i, cm[i, j], ha="center", va="center", color="white" if cm[i, j] > cm.max() / 2 else "black", fontsize=9) ax.set_xlabel("Predicted"); ax.set_ylabel("True") ax.set_title("Confusion matrix: template-disjoint test split") fig.tight_layout() fig.savefig(os.path.join(args.out, "confusion_matrix.png"), dpi=150) except ImportError: pass if __name__ == "__main__": main()