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: 17,692 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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 | """Train or distill Tamarillo/refusal-guard (`ModernBertForSequenceClassification`,
`0: non-refusal`, `1: refusal`, `attn_implementation="eager"`).
Modern 2025-2026 Recipe:
- Internal Teacher (`mmBERT-base`): Label-Smoothed CE + Paired Same-Topic Contrastive Margin
+ R-Drop Symmetric KL Consistency + EMA (decay=0.996)
- Published Students (`mmBERT-small` 141M, `ettin-encoder-32m` 32M): Logit-Standardized KD
(T=2.5 KL + centered-logit MSE from internal base teacher) + CE + Paired Contrastive Margin + EMA
- Strict checkpoint selection on unseen validation (`0.50 * val_macro_f1 + 0.50 * (1 - val_disclaimer_fpr)`)
- Dynamic length-sorted sub-batching to prevent eager-attention OOM on 2.5K-token traces!
"""
from __future__ import annotations
import argparse
import copy
import json
import math
import random
import time
from collections import defaultdict
from pathlib import Path
from typing import Any
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.metrics import f1_score, roc_auc_score
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_cosine_schedule_with_warmup
from schema import ID2LABEL, LABEL2ID
def _load_jsonl(path: Path) -> list[dict[str, Any]]:
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 _make_paired_batches(rows: list[dict[str, Any]], batch_size: int, rng: random.Random) -> list[list[dict[str, Any]]]:
"""Pack same-`pair_id` contrastive items into the same batch so pairwise margin loss fires every step!"""
by_pair: dict[str, list[dict[str, Any]]] = defaultdict(list)
singles: list[dict[str, Any]] = []
for r in rows:
pid = r.get("pair_id") or ""
if pid:
by_pair[pid].append(r)
else:
singles.append(r)
groups: list[list[dict[str, Any]]] = []
for pid, grp in by_pair.items():
pos = [x for x in grp if x["label"] == 1]
neg = [x for x in grp if x["label"] == 0]
if pos and neg:
rng.shuffle(pos)
rng.shuffle(neg)
# Pair up to 2 pos + 2 neg per group chunk
groups.append(pos[:2] + neg[:2])
for extra in pos[2:] + neg[2:]:
singles.append(extra)
else:
singles.extend(grp)
rng.shuffle(singles)
for i in range(0, len(singles), 4):
groups.append(singles[i : i + 4])
rng.shuffle(groups)
batches: list[list[dict[str, Any]]] = []
cur: list[dict[str, Any]] = []
for g in groups:
if len(cur) + len(g) > batch_size and cur:
batches.append(cur)
cur = list(g)
else:
cur.extend(g)
if cur:
batches.append(cur)
return batches
@torch.no_grad()
def precompute_teacher_logits(
teacher_dir: str,
rows: list[dict[str, Any]],
max_length: int,
device: torch.device,
) -> np.ndarray:
print(f"[train] Precomputing teacher logits from {teacher_dir} for {len(rows):,} examples...", flush=True)
t0 = time.time()
t_tok = AutoTokenizer.from_pretrained(teacher_dir, use_fast=True)
t_mod = AutoModelForSequenceClassification.from_pretrained(
teacher_dir, attn_implementation="eager", torch_dtype=torch.bfloat16
).to(device).eval()
order = sorted(range(len(rows)), key=lambda i: len(rows[i]["text"]))
out = np.zeros((len(rows), 2), dtype=np.float32)
idx = 0
while idx < len(order):
# Dynamic batch size by char length to avoid eager OOM
clen = len(rows[order[idx]]["text"])
bs = 48 if clen < 600 else (24 if clen < 1600 else (8 if clen < 3200 else 4))
chunk = order[idx : idx + bs]
texts = [rows[i]["text"] for i in chunk]
enc = t_tok(texts, padding=True, truncation=True, max_length=max_length, 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 = t_mod(**enc).logits.float().cpu().numpy()
for j, orig_i in enumerate(chunk):
out[orig_i] = logits[j]
idx += len(chunk)
del t_mod
torch.cuda.empty_cache()
print(f"[train] Precomputed teacher logits in {time.time() - t0:.1f}s", flush=True)
return out
@torch.no_grad()
def evaluate_val(
model: nn.Module,
tokenizer: Any,
val_rows: list[dict[str, Any]],
max_length: int,
device: torch.device,
) -> dict[str, float]:
model.eval()
order = sorted(range(len(val_rows)), key=lambda i: len(val_rows[i]["text"]))
probs = np.zeros(len(val_rows), dtype=np.float32)
idx = 0
while idx < len(order):
clen = len(val_rows[order[idx]]["text"])
bs = 48 if clen < 800 else (16 if clen < 2200 else 4)
chunk = order[idx : idx + bs]
enc = tokenizer(
[val_rows[i]["text"] for i in chunk],
padding=True,
truncation=True,
max_length=max_length,
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 = model(**enc).logits.float()
p1 = torch.softmax(logits, dim=-1)[:, 1].cpu().numpy()
for j, orig_i in enumerate(chunk):
probs[orig_i] = p1[j]
idx += len(chunk)
y = np.array([r["label"] for r in val_rows], dtype=np.int64)
pred = (probs >= 0.50).astype(np.int64)
macro_f1 = float(f1_score(y, pred, average="macro"))
auc = float(roc_auc_score(y, probs)) if len(set(y.tolist())) > 1 else 0.5
disc_idx = [i for i, r in enumerate(val_rows) if r.get("kind") == "disclaimer_neg"]
disc_fpr = float(np.mean(pred[disc_idx] == 1)) if disc_idx else 0.0
sel = 0.55 * macro_f1 + 0.20 * auc + 0.25 * (1.0 - disc_fpr)
return {
"val_macro_f1": round(macro_f1, 5),
"val_roc_auc": round(auc, 5),
"val_disclaimer_fpr": round(disc_fpr, 5),
"selection_score": round(sel, 5),
}
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-model", type=str, required=True)
parser.add_argument("--data-dir", type=str, required=True)
parser.add_argument("--output-dir", type=str, required=True)
parser.add_argument("--teacher-dir", type=str, default="")
parser.add_argument("--max-length", type=int, default=2560)
parser.add_argument("--epochs", type=float, default=2.5)
parser.add_argument("--lr", type=float, default=3e-5)
parser.add_argument("--batch-size", type=int, default=32)
parser.add_argument("--grad-accum", type=int, default=2)
parser.add_argument("--seed", type=int, default=42)
args = parser.parse_args()
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
data_dir = Path(args.data_dir)
out_dir = Path(args.output_dir)
out_dir.mkdir(parents=True, exist_ok=True)
train_rows = _load_jsonl(data_dir / "train.jsonl")
val_rows = _load_jsonl(data_dir / "val.jsonl")
for idx, r in enumerate(train_rows):
r["_idx"] = idx
teacher_logits = None
if args.teacher_dir:
teacher_logits = precompute_teacher_logits(args.teacher_dir, train_rows, args.max_length, device)
tokenizer = AutoTokenizer.from_pretrained(args.base_model, use_fast=True)
model = AutoModelForSequenceClassification.from_pretrained(
args.base_model,
num_labels=2,
id2label=ID2LABEL,
label2id=LABEL2ID,
attn_implementation="eager",
).to(device)
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
ema_model = copy.deepcopy(model).eval()
for p in ema_model.parameters():
p.requires_grad_(False)
# Optimizer & schedule
no_decay = ("bias", "LayerNorm.weight", "norm.weight")
grouped = [
{"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": 0.01},
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
]
optimizer = torch.optim.AdamW(grouped, lr=args.lr)
steps_per_epoch = max(1, math.ceil(len(train_rows) / (args.batch_size * args.grad_accum)))
total_steps = max(10, int(round(steps_per_epoch * args.epochs)))
warmup_steps = max(20, int(total_steps * 0.08))
scheduler = get_cosine_schedule_with_warmup(optimizer, warmup_steps, total_steps)
print(
f"[train] {args.base_model} | train={len(train_rows):,} val={len(val_rows):,} "
f"kd={bool(args.teacher_dir)} total_steps={total_steps} lr={args.lr}",
flush=True,
)
rng = random.Random(args.seed)
t0 = time.time()
best_sel = -1.0
best_metrics: dict[str, Any] = {}
val_history: list[dict[str, Any]] = []
global_step = 0
eval_every = max(100, total_steps // 6)
epoch_i = 0
def _run_val(step_num: int) -> None:
nonlocal best_sel, best_metrics
for wname, m_eval in (("raw", model), ("ema", ema_model)):
met = evaluate_val(m_eval, tokenizer, val_rows, args.max_length, device)
met["step"] = step_num
met["weights"] = wname
val_history.append(met)
print(
f"[val step={step_num} {wname}] macro_f1={met['val_macro_f1']:.4f} auc={met['val_roc_auc']:.4f} "
f"disc_fpr={met['val_disclaimer_fpr']:.4f} sel={met['selection_score']:.4f}",
flush=True,
)
if met["selection_score"] > best_sel:
best_sel = met["selection_score"]
best_metrics = dict(met)
m_eval.save_pretrained(out_dir)
tokenizer.save_pretrained(out_dir)
model.train()
optimizer.zero_grad(set_to_none=True)
accum_i = 0
running_loss = 0.0
while global_step < total_steps:
epoch_i += 1
batches = _make_paired_batches(train_rows, args.batch_size, rng)
for batch in batches:
if global_step >= total_steps:
break
model.train()
# Keep paired contrastive rows first (all short!) and isolate long LC traces into small sub-batches
paired_sub = [r for r in batch if r.get("pair_id")]
unpaired_sub = sorted([r for r in batch if not r.get("pair_id")], key=lambda r: len(r["text"]))
ordered_batch = paired_sub + unpaired_sub
# Build length-safe micro-chunks (eager O(T^2) attention never OOMs!)
chunks: list[list[dict[str, Any]]] = []
ci = 0
while ci < len(ordered_batch):
# Look ahead to keep chunks uniform & VRAM-safe
clen = len(ordered_batch[ci]["text"])
lim = 16 if clen < 900 else (8 if clen < 1800 else (4 if clen < 3200 else 2))
# Don't accidentally mix a long item into a big chunk
end_i = ci + 1
while end_i < len(ordered_batch) and (end_i - ci) < lim:
nxt_len = len(ordered_batch[end_i]["text"])
nxt_lim = 16 if nxt_len < 900 else (8 if nxt_len < 1800 else (4 if nxt_len < 3200 else 2))
if (end_i - ci + 1) > min(lim, nxt_lim):
break
lim = min(lim, nxt_lim)
end_i += 1
chunks.append(ordered_batch[ci:end_i])
ci = end_i
n_chunks = len(chunks)
batch_loss_val = 0.0
for sub in chunks:
max_chars = max(len(r["text"]) for r in sub)
enc = tokenizer(
[r["text"] for r in sub],
padding=True,
truncation=True,
max_length=args.max_length,
return_token_type_ids=False,
return_tensors="pt",
)
enc = {k: v.to(device) for k, v in enc.items()}
labels = torch.tensor([r["label"] for r in sub], dtype=torch.long, device=device)
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
logits = model(**enc).logits.float()
# 1. Label-smoothed CE (with 1.4x weight on hard disclaimer_neg examples)
weights = torch.tensor(
[1.4 if r.get("kind") == "disclaimer_neg" else 1.0 for r in sub],
dtype=torch.float32,
device=device,
)
ce_per = F.cross_entropy(logits, labels, reduction="none", label_smoothing=0.04)
loss = (ce_per * weights).mean()
# 2. Paired Same-Topic Contrastive Margin Loss
diff_margin = logits[:, 1] - logits[:, 0] # positive => refusal
pair_groups: dict[str, tuple[list[int], list[int]]] = {}
for li, r in enumerate(sub):
pid = r.get("pair_id") or ""
if not pid:
continue
if pid not in pair_groups:
pair_groups[pid] = ([], [])
pair_groups[pid][0 if r["label"] == 1 else 1].append(li)
pair_losses = []
for pos_is, neg_is in pair_groups.values():
if pos_is and neg_is:
for pi in pos_is:
for ni in neg_is:
pair_losses.append(F.relu(2.2 - (diff_margin[pi] - diff_margin[ni])))
if pair_losses:
loss = loss + 0.35 * torch.stack(pair_losses).mean()
# 3. Logit-Standardized KD (students) OR R-Drop Consistency (teacher on short chunks)
if teacher_logits is not None:
t_log = torch.tensor(
teacher_logits[[r["_idx"] for r in sub]],
dtype=torch.float32,
device=device,
)
T = 2.5
kd_kl = F.kl_div(
F.log_softmax(logits / T, dim=-1),
F.softmax(t_log / T, dim=-1),
reduction="batchmean",
) * (T * T)
# Centered logit MSE (logit standardization)
s_cent = logits - logits.mean(dim=-1, keepdim=True)
t_cent = t_log - t_log.mean(dim=-1, keepdim=True)
kd_mse = F.mse_loss(s_cent, t_cent)
loss = 0.65 * loss + 0.35 * (kd_kl + 0.25 * kd_mse)
elif max_chars < 1600 and len(sub) >= 4:
logits2 = model(**enc).logits.float()
p1 = F.log_softmax(logits, dim=-1)
p2 = F.log_softmax(logits2, dim=-1)
rdrop = 0.5 * (
F.kl_div(p1, p2.exp(), reduction="batchmean")
+ F.kl_div(p2, p1.exp(), reduction="batchmean")
)
loss = loss + 0.25 * rdrop
scaled_loss = loss / (args.grad_accum * n_chunks)
scaled_loss.backward()
batch_loss_val += float(loss.detach().item()) / n_chunks
running_loss += batch_loss_val
accum_i += 1
if accum_i >= args.grad_accum:
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
scheduler.step()
optimizer.zero_grad(set_to_none=True)
accum_i = 0
global_step += 1
# EMA update
decay = min(0.996, (1.0 + global_step) / (10.0 + global_step))
with torch.no_grad():
for ep, mp in zip(ema_model.parameters(), model.parameters()):
ep.data.mul_(decay).add_(mp.data, alpha=1.0 - decay)
if global_step % 100 == 0:
print(
f"[step {global_step}/{total_steps}] loss={running_loss / 100:.4f} "
f"lr={scheduler.get_last_lr()[0]:.2e} elapsed={time.time() - t0:.0f}s",
flush=True,
)
running_loss = 0.0
if global_step % eval_every == 0 or global_step == total_steps:
_run_val(global_step)
if global_step > 0 and (not val_history or val_history[-1]["step"] != global_step):
_run_val(global_step)
summary = {
"base_model": args.base_model,
"distilled_from": args.teacher_dir if args.teacher_dir else None,
"max_length": args.max_length,
"epochs": args.epochs,
"lr": args.lr,
"train_examples": len(train_rows),
"val_examples": len(val_rows),
"train_runtime_sec": round(time.time() - t0, 1),
"best_val_metrics": best_metrics,
"val_history": val_history,
}
(out_dir / "training_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
print("[train] COMPLETE:", json.dumps(best_metrics), flush=True)
if __name__ == "__main__":
main()
|