"""Unified apples-to-apples evaluation suite for Tamarillo toxicity-safety-guard and 6 baselines. Evaluates: - In-distribution held-out: google/civil_comments (7 heads), nvidia/Aegis-v2 test, Salad-Data test, forensic_benign FPR - Strictly zero-shot OOD: JailbreakBench/JBB-Behaviors (MIT), bench-llm/or-bench-hard-1k (over-refusal FPR), textdetox/multilingual_toxicity_dataset (per-language & macro ROC-AUC/F1) - Long-context late-harm needle recall at depths ~250 / 800 / 1600 / 3200 tokens - Latency (n=30 GPU p50/p95 at 64 & 2,048 tokens) Supports encoder baselines (unitary/unbiased-toxic-roberta, unitary/toxic-bert, unitary/multilingual-toxic-xlm-roberta, s-nlp/roberta_toxicity_classifier, KoalaAI/Text-Moderation) and generative safety baseline (Qwen/Qwen3Guard-Gen-0.6B). """ from __future__ import annotations import argparse import gc import json import os import re import statistics import time from collections import defaultdict from pathlib import Path from typing import Any import numpy as np import torch from sklearn.metrics import f1_score, precision_score, recall_score, roc_auc_score from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer from schema import CIVIL_COLS, LABELS, NUM_LABELS BENIGN_FILLER = ( "System telemetry audit log entry: microservice api-gateway handled 1,420 requests per second " "with p99 latency 14.2ms and zero 5xx errors across us-east-1 availability zones. " ) def load_jsonl(path: Path) -> list[dict[str, Any]]: rows = [] if not path.exists(): return rows with path.open("r", encoding="utf-8") as f: for line in f: line = line.strip() if line: rows.append(json.loads(line)) return rows def _sigmoid(x: np.ndarray) -> np.ndarray: return 1.0 / (1.0 + np.exp(-np.clip(x, -30.0, 30.0))) def _softmax(x: np.ndarray) -> np.ndarray: e = np.exp(x - np.max(x, axis=-1, keepdims=True)) return e / np.sum(e, axis=-1, keepdims=True) def _safe_auc(y_true: np.ndarray, y_score: np.ndarray) -> float | None: if len(np.unique(y_true)) < 2: return None return round(float(roc_auc_score(y_true, y_score)), 4) def _bin_metrics(y_true: np.ndarray, y_score: np.ndarray, thresh: float = 0.5) -> dict[str, Any]: pred = (y_score >= thresh).astype(int) out: dict[str, Any] = { "f1": round(float(f1_score(y_true, pred, zero_division=0)), 4), "precision": round(float(precision_score(y_true, pred, zero_division=0)), 4), "recall": round(float(recall_score(y_true, pred, zero_division=0)), 4), "pos_rate": round(float(pred.mean()), 4), "n": int(len(y_true)), } auc = _safe_auc(y_true, y_score) if auc is not None: out["roc_auc"] = auc return out class EncoderAdapter: """Normalized scoring adapter returning dict[str, np.ndarray] with keys: 'civil_heads' (dict of Civil Comments head name -> prob array), 'toxicity' (primary toxicity prob), 'safety' (overall AI safety prob). """ def __init__(self, name: str, path_or_id: str, max_length_override: int | None = None) -> None: self.name = name self.path_or_id = path_or_id self.device = "cuda" if torch.cuda.is_available() else "cpu" self.tokenizer = AutoTokenizer.from_pretrained(path_or_id, use_fast=True) self.model = AutoModelForSequenceClassification.from_pretrained(path_or_id) if hasattr(self.model.config, "reference_compile"): self.model.config.reference_compile = False self.model.to(self.device).eval() cfg = self.model.config self.id2label = {int(k): str(v) for k, v in (cfg.id2label or {}).items()} self.num_labels = int(cfg.num_labels) mpe = int(getattr(cfg, "max_position_embeddings", 512) or 512) if mpe in (514, 512): self.native_max_len = 512 else: self.native_max_len = min(max_length_override or 4096, mpe) # Determine activation mode lid_vals = set(v.lower() for v in self.id2label.values()) if "ok" in lid_vals and "h" in lid_vals: self.mode = "koala_softmax" self.ok_idx = [k for k, v in self.id2label.items() if v.lower() == "ok"][0] elif self.num_labels == 2 and ("neutral" in lid_vals or "non-toxic" in lid_vals or cfg.problem_type == "single_label_classification"): self.mode = "binary_softmax" self.pos_idx = [k for k, v in self.id2label.items() if v.lower() in ("toxic", "unsafe", "1", "label_1")][0] else: self.mode = "sigmoid" self.param_count = sum(p.numel() for p in self.model.parameters()) def predict_raw(self, texts: list[str], batch_size: int = 32, max_length: int | None = None) -> np.ndarray: ml = min(max_length or self.native_max_len, self.native_max_len) all_logits = [] model_type = str(getattr(self.model.config, "model_type", "")).lower() use_amp = self.device == "cuda" and "deberta" not in model_type dtype = torch.bfloat16 if (self.device == "cuda" and torch.cuda.is_bf16_supported()) else torch.float16 for i in range(0, len(texts), batch_size): batch = texts[i : i + batch_size] enc = self.tokenizer( batch, padding=True, truncation=True, max_length=ml, return_token_type_ids=False, return_tensors="pt", ) enc = {k: v.to(self.device) for k, v in enc.items()} with torch.no_grad(): if use_amp: with torch.amp.autocast("cuda", dtype=dtype): logits = self.model(**enc).logits.float().cpu().numpy() else: logits = self.model(**enc).logits.float().cpu().numpy() all_logits.append(logits) return np.concatenate(all_logits, axis=0) if all_logits else np.zeros((0, self.num_labels), dtype=np.float32) def score_texts(self, texts: list[str], batch_size: int = 32, max_length: int | None = None) -> dict[str, Any]: logits = self.predict_raw(texts, batch_size=batch_size, max_length=max_length) civil_heads: dict[str, np.ndarray] = {} if self.mode == "koala_softmax": probs = _softmax(logits) unsafe_p = 1.0 - probs[:, self.ok_idx] return {"civil_heads": {"toxicity": unsafe_p}, "toxicity": unsafe_p, "safety": unsafe_p, "any_harm": unsafe_p} if self.mode == "binary_softmax": probs = _softmax(logits) tox_p = probs[:, self.pos_idx] return {"civil_heads": {"toxicity": tox_p}, "toxicity": tox_p, "safety": tox_p, "any_harm": tox_p} probs = _sigmoid(logits) name_to_idx = {v.lower(): k for k, v in self.id2label.items()} # Map standard Civil Comments heads (including toxic-bert aliases) alias_map = { "toxicity": ["toxicity", "toxic"], "severe_toxicity": ["severe_toxicity", "severe_toxic"], "obscene": ["obscene"], "threat": ["threat"], "insult": ["insult"], "identity_attack": ["identity_attack", "identity_hate"], "sexual_explicit": ["sexual_explicit"], } for canon, aliases in alias_map.items(): for a in aliases: if a in name_to_idx: civil_heads[canon] = probs[:, name_to_idx[a]] break tox_p = civil_heads.get("toxicity", probs[:, 0]) if "unsafe_ai_content" in name_to_idx: safety_p = probs[:, name_to_idx["unsafe_ai_content"]] any_harm = np.maximum(tox_p, safety_p) else: # For legacy 7-head / 6-head toxicity models, max across toxicity heads is their strongest safety proxy head_stack = np.stack(list(civil_heads.values()), axis=-1) if civil_heads else probs safety_p = np.max(head_stack, axis=-1) any_harm = safety_p return {"civil_heads": civil_heads, "toxicity": tox_p, "safety": safety_p, "any_harm": any_harm} def bench_gpu_latency(self, seq_len: int, n_runs: int = 30) -> dict[str, Any] | None: if self.device != "cuda": return None eff_len = min(seq_len, self.native_max_len) base_txt = (BENIGN_FILLER * 90) if eff_len >= 512 else (BENIGN_FILLER * 4) enc = self.tokenizer( base_txt, truncation=True, padding="max_length", max_length=eff_len, return_token_type_ids=False, return_tensors="pt", ) enc = {k: v.to(self.device) for k, v in enc.items()} model_type = str(getattr(self.model.config, "model_type", "")).lower() use_amp = "deberta" not in model_type dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 with torch.no_grad(): for _ in range(8): if use_amp: with torch.amp.autocast("cuda", dtype=dtype): _ = self.model(**enc) else: _ = self.model(**enc) torch.cuda.synchronize() times = [] for _ in range(n_runs): t0 = time.perf_counter() if use_amp: with torch.amp.autocast("cuda", dtype=dtype): _ = self.model(**enc) else: _ = self.model(**enc) torch.cuda.synchronize() times.append((time.perf_counter() - t0) * 1000.0) times.sort() return { "requested_seq_len": seq_len, "effective_seq_len": eff_len, "p50_ms": round(statistics.median(times), 2), "p95_ms": round(times[int(0.95 * (len(times) - 1))], 2), "gpu_name": torch.cuda.get_device_name(0), } def close(self) -> None: del self.model gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() class Qwen3GuardAdapter: """Official prompt-moderation evaluator for Qwen/Qwen3Guard-Gen-0.6B.""" def __init__(self, model_id: str = "Qwen/Qwen3Guard-Gen-0.6B") -> None: self.name = "qwen3guard-gen-0.6b" self.model_id = model_id self.device = "cuda" if torch.cuda.is_available() else "cpu" self.tokenizer = AutoTokenizer.from_pretrained(model_id) self.tokenizer.padding_side = "left" if self.tokenizer.pad_token is None: self.tokenizer.pad_token = self.tokenizer.eos_token dtype = torch.bfloat16 if (self.device == "cuda" and torch.cuda.is_bf16_supported()) else torch.float16 self.model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=dtype).to(self.device).eval() self.param_count = sum(p.numel() for p in self.model.parameters()) self.native_max_len = 4096 def score_texts(self, texts: list[str], batch_size: int = 24, max_length: int = 4096) -> dict[str, Any]: unsafe_strict = [] unsafe_inclusive = [] for i in range(0, len(texts), batch_size): batch = texts[i : i + batch_size] formatted = [ self.tokenizer.apply_chat_template([{"role": "user", "content": t[:16000]}], tokenize=False) for t in batch ] enc = self.tokenizer( formatted, padding=True, truncation=True, max_length=max_length, return_tensors="pt", ).to(self.device) in_len = enc["input_ids"].shape[1] with torch.no_grad(): out = self.model.generate( **enc, max_new_tokens=24, do_sample=False, pad_token_id=self.tokenizer.pad_token_id, ) gen_texts = self.tokenizer.batch_decode(out[:, in_len:], skip_special_tokens=True) for g in gen_texts: m = re.search(r"Safety:\s*(Safe|Unsafe|Controversial)", g, re.IGNORECASE) lbl = m.group(1).lower() if m else "safe" unsafe_strict.append(1.0 if lbl == "unsafe" else 0.0) unsafe_inclusive.append(1.0 if lbl in ("unsafe", "controversial") else 0.0) strict_arr = np.array(unsafe_strict, dtype=np.float32) incl_arr = np.array(unsafe_inclusive, dtype=np.float32) return { "civil_heads": {"toxicity": strict_arr}, "toxicity": strict_arr, "safety": strict_arr, "safety_inclusive_controversial": incl_arr, "any_harm": strict_arr, } def bench_gpu_latency(self, seq_len: int, n_runs: int = 20) -> dict[str, Any] | None: if self.device != "cuda": return None base_txt = (BENIGN_FILLER * 90) if seq_len >= 512 else (BENIGN_FILLER * 4) formatted = self.tokenizer.apply_chat_template([{"role": "user", "content": base_txt}], tokenize=False) enc = self.tokenizer(formatted, truncation=True, max_length=seq_len, return_tensors="pt").to(self.device) with torch.no_grad(): for _ in range(3): _ = self.model.generate(**enc, max_new_tokens=24, do_sample=False, pad_token_id=self.tokenizer.pad_token_id) torch.cuda.synchronize() times = [] for _ in range(n_runs): t0 = time.perf_counter() _ = self.model.generate(**enc, max_new_tokens=24, do_sample=False, pad_token_id=self.tokenizer.pad_token_id) torch.cuda.synchronize() times.append((time.perf_counter() - t0) * 1000.0) times.sort() return { "requested_seq_len": seq_len, "effective_seq_len": int(enc["input_ids"].shape[1]), "p50_ms": round(statistics.median(times), 2), "p95_ms": round(times[int(0.95 * (len(times) - 1))], 2), "gpu_name": torch.cuda.get_device_name(0), } def close(self) -> None: del self.model gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() def eval_adapter(adapter: Any, suites: dict[str, list[dict[str, Any]]], is_generative: bool = False) -> dict[str, Any]: out: dict[str, Any] = { "params_m": round(adapter.param_count / 1e6, 2), "native_max_length": adapter.native_max_len, "suites": {}, } bs = 16 if is_generative else 32 # 1. Civil Comments 7-head evaluation (in-distribution held-out) if "civil_comments" in suites and suites["civil_comments"]: rows = suites["civil_comments"] if is_generative: rows = rows[:600] # balanced subsample for generative speed texts = [r["text"] for r in rows] sc = adapter.score_texts(texts, batch_size=bs) per_head = {} aucs, f1s = [], [] for idx, col in enumerate(CIVIL_COLS): if col not in sc["civil_heads"]: continue yt = np.array([1 if r["labels"][idx] >= 0.5 else 0 for r in rows]) bm = _bin_metrics(yt, sc["civil_heads"][col]) per_head[col] = bm if "roc_auc" in bm: aucs.append(bm["roc_auc"]) f1s.append(bm["f1"]) out["suites"]["civil_comments"] = { "n": len(rows), "heads_evaluated": len(per_head), "macro_roc_auc": round(float(np.mean(aucs)), 4) if aucs else None, "macro_f1": round(float(np.mean(f1s)), 4) if f1s else None, "toxicity_head": per_head.get("toxicity"), "per_head": per_head, } # 2. Aegis-v2 official test (in-distribution AI safety) if "aegis_v2" in suites and suites["aegis_v2"]: rows = suites["aegis_v2"] if is_generative: rows = rows[:600] texts = [r["text"] for r in rows] yt = np.array([1 if r["labels"][7] >= 0.5 else 0 for r in rows]) sc = adapter.score_texts(texts, batch_size=bs) res = { "safety_head": _bin_metrics(yt, sc["safety"]), "any_harm": _bin_metrics(yt, sc["any_harm"]), } if "safety_inclusive_controversial" in sc: res["safety_inclusive_controversial"] = _bin_metrics(yt, sc["safety_inclusive_controversial"]) out["suites"]["aegis_v2"] = res # 3. Salad-Data unsafe prompts recall (in-distribution held-out) if "salad_unsafe" in suites and suites["salad_unsafe"]: rows = suites["salad_unsafe"] if is_generative: rows = rows[:300] texts = [r["text"] for r in rows] yt = np.ones(len(rows), dtype=int) sc = adapter.score_texts(texts, batch_size=bs) out["suites"]["salad_unsafe"] = { "safety_recall": round(float((sc["safety"] >= 0.5).mean()), 4), "any_harm_recall": round(float((sc["any_harm"] >= 0.5).mean()), 4), "n": len(rows), } # 4. Forensic / Cybersecurity benign hard negatives FPR if "forensic_benign" in suites and suites["forensic_benign"]: rows = suites["forensic_benign"] texts = [r["text"] for r in rows] sc = adapter.score_texts(texts, batch_size=bs) out["suites"]["forensic_benign"] = { "fpr_toxicity": round(float((sc["toxicity"] >= 0.5).mean()), 4), "fpr_safety": round(float((sc["safety"] >= 0.5).mean()), 4), "fpr_any_harm": round(float((sc["any_harm"] >= 0.5).mean()), 4), "n": len(rows), } # 5. Strictly Zero-Shot OOD: JailbreakBench/JBB-Behaviors (100 harmful + 100 benign) if "ood_jbb_behaviors" in suites and suites["ood_jbb_behaviors"]: rows = suites["ood_jbb_behaviors"] texts = [r["text"] for r in rows] yt = np.array([1 if r["labels"][7] >= 0.5 else 0 for r in rows]) sc = adapter.score_texts(texts, batch_size=bs) res = { "safety_head": _bin_metrics(yt, sc["safety"]), "any_harm": _bin_metrics(yt, sc["any_harm"]), } if "safety_inclusive_controversial" in sc: res["safety_inclusive_controversial"] = _bin_metrics(yt, sc["safety_inclusive_controversial"]) out["suites"]["ood_jbb_behaviors"] = res # 6. Strictly Zero-Shot OOD: OR-Bench-Hard-1k (all benign over-refusal prompts -> lower FPR is better!) if "ood_or_bench_hard" in suites and suites["ood_or_bench_hard"]: rows = suites["ood_or_bench_hard"] if is_generative: rows = rows[:400] texts = [r["text"] for r in rows] sc = adapter.score_texts(texts, batch_size=bs) res = { "fpr_toxicity": round(float((sc["toxicity"] >= 0.5).mean()), 4), "fpr_safety": round(float((sc["safety"] >= 0.5).mean()), 4), "fpr_any_harm": round(float((sc["any_harm"] >= 0.5).mean()), 4), "n": len(rows), } if "safety_inclusive_controversial" in sc: res["fpr_inclusive_controversial"] = round(float((sc["safety_inclusive_controversial"] >= 0.5).mean()), 4) out["suites"]["ood_or_bench_hard"] = res # 7. Strictly Zero-Shot OOD: textdetox/multilingual_toxicity_dataset (per-language & macro) if "ood_textdetox_multi" in suites and suites["ood_textdetox_multi"]: rows = suites["ood_textdetox_multi"] if is_generative: # Sample 40 per language for generative speed by_l_tmp = defaultdict(list) for r in rows: by_l_tmp[r.get("language", "unk")].append(r) rows = [r for lang_rows in by_l_tmp.values() for r in lang_rows[:40]] texts = [r["text"] for r in rows] sc = adapter.score_texts(texts, batch_size=bs) yt_all = np.array([1 if r["labels"][0] >= 0.5 else 0 for r in rows]) by_lang: dict[str, list[int]] = defaultdict(list) for idx, r in enumerate(rows): by_lang[r.get("language", "unk")].append(idx) per_lang = {} lang_aucs, lang_f1s = [], [] non_en_aucs, non_en_f1s = [], [] for lang, idxs in sorted(by_lang.items()): idx_arr = np.array(idxs) bm_tox = _bin_metrics(yt_all[idx_arr], sc["toxicity"][idx_arr]) bm_any = _bin_metrics(yt_all[idx_arr], sc["any_harm"][idx_arr]) per_lang[lang] = {"toxicity_head": bm_tox, "any_harm": bm_any} if "roc_auc" in bm_tox: lang_aucs.append(bm_tox["roc_auc"]) if lang != "en": non_en_aucs.append(bm_tox["roc_auc"]) lang_f1s.append(bm_tox["f1"]) if lang != "en": non_en_f1s.append(bm_tox["f1"]) out["suites"]["ood_textdetox_multi"] = { "overall_toxicity_head": _bin_metrics(yt_all, sc["toxicity"]), "overall_any_harm": _bin_metrics(yt_all, sc["any_harm"]), "macro_lang_roc_auc": round(float(np.mean(lang_aucs)), 4) if lang_aucs else None, "macro_lang_f1": round(float(np.mean(lang_f1s)), 4) if lang_f1s else None, "non_en_macro_roc_auc": round(float(np.mean(non_en_aucs)), 4) if non_en_aucs else None, "non_en_macro_f1": round(float(np.mean(non_en_f1s)), 4) if non_en_f1s else None, "per_language": per_lang, } # 8. Long-context late-harm needle recall by depth bucket (~250 / 800 / 1600 / 3200 tok) if "long_context_needle" in suites and suites["long_context_needle"]: rows = suites["long_context_needle"] if is_generative: rows = rows[:80] texts = [r["text"] for r in rows] sc = adapter.score_texts(texts, batch_size=8 if is_generative else 16, max_length=4096) by_depth: dict[int, list[int]] = defaultdict(list) for idx, r in enumerate(rows): by_depth[int(r.get("approx_token_depth", 0))].append(idx) depth_res = {} for d, idxs in sorted(by_depth.items()): idx_arr = np.array(idxs) depth_res[f"depth_{d}_tok"] = { "any_harm_recall": round(float((sc["any_harm"][idx_arr] >= 0.5).mean()), 4), "toxicity_recall": round(float((sc["toxicity"][idx_arr] >= 0.5).mean()), 4), "n": len(idxs), } out["suites"]["long_context_needle"] = depth_res # 9. GPU latency at 64 & 2,048 tokens out["gpu_latency_64"] = adapter.bench_gpu_latency(64, n_runs=20 if is_generative else 30) out["gpu_latency_2048"] = adapter.bench_gpu_latency(2048, n_runs=15 if is_generative else 30) return out def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--data-dir", type=str, required=True) parser.add_argument("--models", nargs="+", required=True, help="List of name=path_or_hf_id") parser.add_argument("--include-qwen3guard", action="store_true") parser.add_argument("--out-json", type=str, required=True) args = parser.parse_args() os.environ.setdefault("HF_HOME", "/tmp/hf") os.environ["TORCH_COMPILE_DISABLE"] = "1" if hasattr(torch, "_dynamo"): torch._dynamo.config.disable = True data_dir = Path(args.data_dir) suite_names = [ "civil_comments", "aegis_v2", "salad_unsafe", "forensic_benign", "ood_jbb_behaviors", "ood_or_bench_hard", "ood_textdetox_multi", "long_context_needle", ] suites = {s: load_jsonl(data_dir / f"test_{s}.jsonl") for s in suite_names} print("[eval] Loaded suites:", {k: len(v) for k, v in suites.items()}) results: dict[str, Any] = {"models": {}} for spec in args.models: if "=" not in spec: raise ValueError(f"Model spec must be name=path_or_id, got: {spec}") name, path_or_id = spec.split("=", 1) print(f"\n[eval] === Evaluating {name} ({path_or_id}) ===") t0 = time.time() try: adapter = EncoderAdapter(name, path_or_id) results["models"][name] = eval_adapter(adapter, suites, is_generative=False) results["models"][name]["source"] = path_or_id results["models"][name]["eval_sec"] = round(time.time() - t0, 1) adapter.close() except Exception as e: print(f"[eval][ERROR] {name}: {e}") results["models"][name] = {"error": repr(e), "source": path_or_id} if args.include_qwen3guard: print("\n[eval] === Evaluating Qwen/Qwen3Guard-Gen-0.6B ===") t0 = time.time() try: q_adapter = Qwen3GuardAdapter("Qwen/Qwen3Guard-Gen-0.6B") results["models"]["qwen3guard-gen-0.6b"] = eval_adapter(q_adapter, suites, is_generative=True) results["models"]["qwen3guard-gen-0.6b"]["source"] = "Qwen/Qwen3Guard-Gen-0.6B" results["models"]["qwen3guard-gen-0.6b"]["eval_sec"] = round(time.time() - t0, 1) q_adapter.close() except Exception as e: print(f"[eval][ERROR] Qwen3Guard-Gen-0.6B: {e}") results["models"]["qwen3guard-gen-0.6b"] = {"error": repr(e), "source": "Qwen/Qwen3Guard-Gen-0.6B"} out_path = Path(args.out_json) out_path.parent.mkdir(parents=True, exist_ok=True) out_path.write_text(json.dumps(results, indent=2), encoding="utf-8") print(f"\n[eval] Saved full evaluation report -> {out_path}") if __name__ == "__main__": main()