Text Classification
Transformers
ONNX
Safetensors
Transformers.js
English
modernbert
refusal-detection
over-refusal
llm-safety
red-teaming
garak
guardrails
ai-security
tamarillo
Eval Results (legacy)
text-embeddings-inference
Run this model with HF Jobs
Run Tamarillo/refusal-guard-tiny-en on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Tamarillo/refusal-guard-tiny-en. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Tamarillo/refusal-guard-tiny-en on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Tamarillo/refusal-guard-tiny-en with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tamarillo/refusal-guard-tiny-en with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="Tamarillo/refusal-guard-tiny-en")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained("Tamarillo/refusal-guard-tiny-en") model = AutoModelForSequenceClassification.from_pretrained("Tamarillo/refusal-guard-tiny-en", device_map="auto") - Transformers.js
How to use Tamarillo/refusal-guard-tiny-en with Transformers.js:
// npm i @huggingface/transformers import { pipeline } from '@huggingface/transformers'; // Allocate pipeline const pipe = await pipeline('text-classification', 'Tamarillo/refusal-guard-tiny-en'); - Notebooks
- Google Colab
- Kaggle
File size: 8,859 Bytes
217d858 | 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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 | """Unified 3-Tier 6-Suite Evaluation for Tamarillo/refusal-guard head-to-head vs live incumbents:
- garak-llm/garak-refusal-detector (149M ModernBERT-base, EN-only, nvidia-open-model-license)
- ProtectAI/distilroberta-base-rejection-v1 (82M distilroberta-base, 512-tok, ARCHIVED)
- VINAY-UMRETHE/tiny-refusal-classifier (5-class ModernBERT)
- NVIDIA/garak keyword MitigationBypass baseline (reproducing #2197)
"""
from __future__ import annotations
import argparse
import json
import time
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 AutoModelForSequenceClassification, AutoTokenizer
from schema import garak_keyword_score
SUITES = [
"ood_do_not_answer",
"ood_jbb_judge",
"heldout_wildguard_en",
"heldout_wildguard_jp",
"diag_phi4_disclaimer",
"diag_phi4_lc2048",
]
def _load_jsonl(path: Path) -> list[dict[str, Any]]:
if not path.exists():
return []
out = []
with path.open("r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
out.append(json.loads(line))
return out
def _refusal_prob_from_logits(logits: torch.Tensor, id2label: dict[int, str]) -> np.ndarray:
probs = torch.softmax(logits.float(), dim=-1).cpu().numpy()
norm_map = {int(k): str(v).strip().lower() for k, v in id2label.items()}
# 5-class VINAY-UMRETHE/tiny-refusal-classifier: 0=compliant, 1..4=refusal/limitation/clarification
if len(norm_map) > 2 and "compliant" in norm_map.values():
comp_idx = [k for k, v in norm_map.items() if v == "compliant"][0]
return 1.0 - probs[:, comp_idx]
# Binary: match explicit refusal / rejection label
for idx, name in norm_map.items():
if name in ("refusal", "rejection", "refused", "yes", "label_1") or (
"refusal" in name and "non" not in name
):
return probs[:, idx]
return probs[:, 1]
def _compute_metrics(y_true: list[int], probs: np.ndarray) -> dict[str, Any]:
y = np.asarray(y_true, dtype=np.int64)
p = np.asarray(probs, dtype=np.float64)
pred = (p >= 0.50).astype(np.int64)
auc = float(roc_auc_score(y, p)) if len(set(y.tolist())) > 1 else 0.5
macro_f1 = float(f1_score(y, pred, average="macro", zero_division=0))
ref_f1 = float(f1_score(y, pred, pos_label=1, zero_division=0))
rec = float(recall_score(y, pred, pos_label=1, zero_division=0))
prec = float(precision_score(y, pred, pos_label=1, zero_division=0))
neg_mask = y == 0
fpr = float(np.mean(pred[neg_mask] == 1)) if np.any(neg_mask) else 0.0
return {
"n": int(len(y)),
"n_pos": int(np.sum(y == 1)),
"n_neg": int(np.sum(y == 0)),
"roc_auc": round(auc, 4),
"macro_f1": round(macro_f1, 4),
"refusal_f1": round(ref_f1, 4),
"recall": round(rec, 4),
"precision": round(prec, 4),
"fpr": round(fpr, 4),
}
@torch.no_grad()
def eval_hf_model(
model_path: str,
suite_data: dict[str, list[dict[str, Any]]],
device: torch.device,
) -> dict[str, Any]:
try:
tok = AutoTokenizer.from_pretrained(model_path, use_fast=True)
except Exception:
from huggingface_hub import hf_hub_download
from transformers import PreTrainedTokenizerFast
tok_file = hf_hub_download(model_path, "tokenizer.json")
tok = PreTrainedTokenizerFast(tokenizer_file=tok_file)
if tok.pad_token is None:
tok.pad_token = tok.eos_token or "[PAD]"
kwargs: dict[str, Any] = {"torch_dtype": torch.bfloat16}
try:
mod = AutoModelForSequenceClassification.from_pretrained(
model_path, attn_implementation="eager", **kwargs
).to(device).eval()
except Exception:
mod = AutoModelForSequenceClassification.from_pretrained(model_path, **kwargs).to(device).eval()
params_m = round(sum(p.numel() for p in mod.parameters()) / 1e6, 2)
max_pos = int(getattr(mod.config, "max_position_embeddings", 512))
# RoBERTa has max_position_embeddings=514 -> usable max_length=512
eval_max = min(2048, max_pos - 2 if "roberta" in str(getattr(mod.config, "model_type", "")).lower() else max_pos)
id2l = {int(k): str(v) for k, v in getattr(mod.config, "id2label", {0: "0", 1: "1"}).items()}
results: dict[str, Any] = {}
for sname, rows in suite_data.items():
if not rows:
continue
order = sorted(range(len(rows)), key=lambda i: len(rows[i]["text"]))
probs = np.zeros(len(rows), dtype=np.float32)
idx = 0
while idx < len(order):
clen = len(rows[order[idx]]["text"])
bs = 48 if clen < 800 else (16 if clen < 2200 else 4)
chunk = order[idx : idx + bs]
enc = tok(
[rows[i]["text"] for i in chunk],
padding=True,
truncation=True,
max_length=eval_max,
return_token_type_ids=False,
return_tensors="pt",
)
enc = {k: v.to(device) for k, v in enc.items()}
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
logits = mod(**enc).logits
p1 = _refusal_prob_from_logits(logits, id2l)
for j, orig_i in enumerate(chunk):
probs[orig_i] = p1[j]
idx += len(chunk)
results[sname] = _compute_metrics([r["label"] for r in rows], probs)
# GPU p50 latency @ 64 & 2,048 tok (or eval_max)
gpu_lat = {}
for sl in (64, 2048):
eff_sl = min(sl, eval_max)
ids = torch.full((1, eff_sl), 100, dtype=torch.long, device=device)
mask = torch.ones((1, eff_sl), dtype=torch.long, device=device)
for _ in range(5):
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
_ = mod(input_ids=ids, attention_mask=mask)
torch.cuda.synchronize()
times = []
for _ in range(25):
t0 = time.perf_counter()
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
_ = mod(input_ids=ids, attention_mask=mask)
torch.cuda.synchronize()
times.append((time.perf_counter() - t0) * 1000.0)
gpu_lat[f"gpu_latency_{sl}"] = {"seq_len": eff_sl, "p50_ms": round(float(np.median(times)), 2)}
del mod
torch.cuda.empty_cache()
return {
"model_path": model_path,
"params_m": params_m,
"native_max_length": eval_max,
"id2label": id2l,
"suites": results,
**gpu_lat,
}
def eval_keyword_baseline(suite_data: dict[str, list[dict[str, Any]]]) -> dict[str, Any]:
results = {}
for sname, rows in suite_data.items():
if not rows:
continue
probs = np.array([garak_keyword_score(r["text"]) for r in rows], dtype=np.float32)
results[sname] = _compute_metrics([r["label"] for r in rows], probs)
return {"model_path": "garak_keyword_baseline", "params_m": 0.0, "native_max_length": 0, "suites": results}
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--data-dir", type=str, required=True)
parser.add_argument("--models", nargs="+", required=True, help="key=path_or_hf_id entries")
parser.add_argument("--include-keyword-baseline", action="store_true")
parser.add_argument("--out-json", type=str, required=True)
args = parser.parse_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
data_dir = Path(args.data_dir)
suite_data = {s: _load_jsonl(data_dir / f"test_{s}.jsonl") for s in SUITES}
out: dict[str, Any] = {"models": {}}
if args.include_keyword_baseline:
out["models"]["garak-keyword-mitigation"] = eval_keyword_baseline(suite_data)
print("[eval] garak-keyword-mitigation:", {k: v["macro_f1"] for k, v in out["models"]["garak-keyword-mitigation"]["suites"].items()}, flush=True)
for spec in args.models:
key, path = spec.split("=", 1)
print(f"[eval] Evaluating {key} ({path})...", flush=True)
try:
res = eval_hf_model(path, suite_data, device)
out["models"][key] = res
print(
f"[eval] {key} ({res['params_m']}M): "
+ " | ".join(f"{k}: F1={v['macro_f1']:.3f} AUC={v['roc_auc']:.3f} FPR={v['fpr']:.3f}" for k, v in res["suites"].items()),
flush=True,
)
except Exception as e:
print(f"[eval] ERROR {key}: {e}", flush=True)
out["models"][key] = {"error": str(e)}
Path(args.out_json).write_text(json.dumps(out, indent=2), encoding="utf-8")
print(f"[eval] Wrote {args.out_json}", flush=True)
if __name__ == "__main__":
main()
|