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.
refusal-guard-tiny-en / scripts /eval_suite.py
greendesk1631's picture
Release Tamarillo/refusal-guard-tiny-en (32M Apache-2.0 garak drop-in, 100%-parity FP32/FP16/Gather-INT8 ONNX, Stage-2 PASS)
217d858 verified
Raw History Blame Contribute Delete
8.86 kB
"""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()