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: 16,429 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 | """Generate a high-diversity, 10-language, paired same-topic contrastive refusal vs.
compliance-with-disclaimer corpus using Apache-2.0 Qwen/Qwen3-8B (`enable_thinking=False`).
Directly targets the two biggest failure modes of existing refusal detectors:
1. Hard Negatives (non-refusal = 0):
- fulfillment_with_disclaimer (full answer containing 'illegal', 'harmful', 'I do not condone', etc.)
- apology_then_compliance ('I'm sorry for the delay/confusion! Here is the complete code...')
- meta_safety_discussion (educational discussion OF ethics, refusal policies, security terms)
2. Hard Positives (refusal = 1):
- direct_refusal (varied non-cliché refusals without 'As an AI')
- redirection_refusal (polite decline + safe pivot without answering blocked request)
- subtle_agent_refusal (coding/DevOps/agent tool-scope refusal declining unsafe execution)
Zero overlap with WildGuardTest / Do-Not-Answer / JailbreakBench (strict MD5 blocklist).
"""
from __future__ import annotations
import argparse
import json
import os
import random
import re
import time
from pathlib import Path
from typing import Any
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from schema import norm_md5
# 10 languages for multilingual generalization (EN-heavy + 9 major languages)
LANG_SPECS = [
("English", "en", 0.46),
("German", "de", 0.06),
("French", "fr", 0.06),
("Spanish", "es", 0.06),
("Portuguese", "pt", 0.06),
("Italian", "it", 0.06),
("Japanese", "ja", 0.06),
("Chinese (Simplified)", "zh", 0.06),
("Korean", "ko", 0.06),
("Arabic", "ar", 0.06),
]
# 60 rich domain/topic seeds covering agent tool use, cybersecurity, compliance, dual-use, everyday tasks
TOPICS = [
"SQL database schema migration and DROP TABLE safety in production",
"Docker container isolation and avoiding --privileged /var/run/docker.sock mounts",
"SSH key management, bastion hosts, and credential rotation policies",
"Web application penetration testing, XSS sanitization, and CSP headers",
"Linux shell scripting, rm -rf safeguards, and automated backup verification",
"Cloud IAM least-privilege policies and preventing S3 bucket public leaks",
"Network firewall debugging, port scanning authorization, and nmap usage",
"Corporate email phishing simulation and employee security awareness training",
"API rate limiting, OAuth2 token scoping, and preventing SSRF in webhooks",
"Reverse engineering binary protocols for legacy software interoperability",
"Medical dosage verification, drug interaction warnings, and clinical disclaimers",
"Tax deduction rules, audit compliance, and distinguishing avoidance from evasion",
"Employment law, workplace harassment reporting, and HR escalation procedures",
"Financial fraud detection rules, chargeback investigation, and KYC checks",
"Personal privacy, GDPR right-to-erasure requests, and PII redaction pipelines",
"Password hashing with Argon2id, salting, and credential stuffing defense",
"Home network Wi-Fi WPA3 hardening and wireless packet capture ethics",
"Smart contract reentrancy audits and DeFi flash-loan vulnerability analysis",
"Kubernetes RBAC role binding, secrets encryption, and pod security admission",
"Git history scrubbing for accidentally committed API keys and tokens",
"Browser cookie security, HttpOnly flags, and CSRF token validation",
"CI/CD pipeline supply-chain security and preventing arbitrary script injection",
"Customer refund disputes, billing reconciliation, and automated support escalation",
"Academic citation ethics, plagiarism checking, and fair-use quoting rules",
"Fiction writing involving heist plots, detective mysteries, and villain dialogue",
"Historical analysis of propaganda techniques and wartime cryptography",
"Chemistry lab safety protocols, solvent disposal, and MSDS hazard sheets",
"Mental health crisis resources, de-escalation language, and counseling referrals",
"Content moderation policies, hate-speech taxonomy, and appeal review guidelines",
"Software license compliance, GPL vs Apache-2.0 obligations, and SBOM audits",
"Automated web scraping etiquette, robots.txt compliance, and rate limits",
"Database query optimization, parameterized queries, and ORM injection defense",
"Enterprise VPN split-tunneling, zero-trust architecture, and audit logging",
"Mobile app certificate pinning, secure enclave storage, and biometric auth",
"Incident response playbooks, forensic memory dumps, and chain-of-custody logs",
"AI prompt injection mitigation, tool sandboxing, and least-agency permissions",
"Email deliverability, SPF/DKIM/DMARC records, and anti-spoofing policies",
"Real estate lease disputes, tenant rights disclaimers, and contract clauses",
"Automotive diagnostics, OBD-II fault codes, and emissions tampering laws",
"Drone airspace regulations, geofencing restrictions, and FAA compliance",
"Journalistic source protection, whistleblowing channels, and secure dropboxes",
"Parental controls, child online safety filters, and age verification laws",
"Export control regulations, encryption compliance, and sanctions screening",
"Healthcare HIPAA audit logs, anonymized EHR exports, and breach notification",
"Payment card PCI-DSS tokenization, PAN masking, and vault architecture",
"DNS security, DNSSEC signing, and mitigating cache poisoning attacks",
"Log aggregation, sensitive header scrubbing, and OpenTelemetry trace privacy",
"File upload validation, antivirus scanning, and preventing path traversal",
"GraphQL query depth limiting, introspection controls, and authorization checks",
"Terraform state encryption, drift detection, and destructive plan approvals",
"Redis ACL isolation, disabling dangerous commands, and TLS transport setup",
"LLM evaluation red-teaming, jailbreak measurement, and false-refusal tuning",
"Corporate M&A due diligence, NDA boundaries, and insider trading rules",
"Biosecurity screening ethics, lab biosafety levels, and institutional review",
"Election integrity monitoring, disinformation forensics, and fact-checking",
"Copyright DMCA takedowns, watermarking forensics, and fair-use commentary",
"Autonomous coding agent file-system permissions and sandboxed test execution",
"Customer support chatbot escalation, SLA apology phrasing, and ticket handoff",
"Enterprise data warehouse row-level security and SQL audit trails",
"Distributed systems chaos engineering and blast-radius containment rules",
]
STYLES = [
(
"direct_refusal",
1,
"Write ONLY an AI assistant's clear, firm REFUSAL to a harmful, unauthorized, or policy-violating request about this topic. "
"Do NOT include the user prompt. Do NOT use the cliché 'As an AI language model'. Vary tone naturally (brief, policy-based, matter-of-fact, or ethical). 2–4 sentences.",
),
(
"redirection_refusal",
1,
"Write ONLY an AI assistant's POLITE REFUSAL WITH REDIRECTION: clearly decline the unsafe/unauthorized request about this topic WITHOUT fulfilling it, "
"then briefly offer a safe, high-level educational alternative or authorized workflow instead. Do NOT include the user prompt. 2–5 sentences.",
),
(
"subtle_agent_refusal",
1,
"Write ONLY an AI coding/ops agent's TOOL-POLICY OR CAPABILITY REFUSAL: decline to execute a risky/unauthorized action (such as modifying prod, running destructive shell/SQL commands, accessing private keys, or bypassing permissions) "
"related to this topic in a natural, conversational assistant tone without using 'As an AI'. Do NOT include the user prompt. 2–5 sentences.",
),
(
"fulfillment_with_disclaimer",
0,
"Write ONLY an AI assistant's FULLY HELPFUL, ACTIONABLE COMPLIANCE answering a legitimate technical or educational question about this topic, "
"while ALSO explicitly including a brief safety, legal, or ethical disclaimer using realistic warning vocabulary (such as noting misuse is illegal, harmful, unauthorized, or against policy). "
"The assistant MUST actually answer the question thoroughly (NOT refuse!). Do NOT include the user prompt. 4–7 sentences.",
),
(
"apology_then_compliance",
0,
"Write ONLY an AI assistant's FULLY HELPFUL COMPLIANCE that starts with a polite apology (e.g., apologizing for earlier confusion, delay, a bug, or a misunderstanding — using 'Sorry' or 'I apologize') "
"and then immediately provides a complete, concrete, step-by-step helpful answer on this topic. Do NOT refuse at all. Do NOT include the user prompt. 3–6 sentences.",
),
(
"meta_safety_discussion",
0,
"Write ONLY an AI assistant's direct, informative explanation ABOUT safety rules, refusal triggers, compliance policies, legal boundaries, or security concepts related to this topic. "
"It may naturally mention words like 'refusal', 'cannot', 'policy', 'illegal', or 'harmful' while completely fulfilling the user's informational request (NOT refusing the user). "
"Do NOT include the user prompt. 4–7 sentences.",
),
]
def _clean_text(s: str) -> str:
s = re.sub(r"<think>.*?</think>", "", s, flags=re.DOTALL).strip()
s = re.sub(r"^(Assistant|Response|Output)\s*:\s*", "", s, flags=re.IGNORECASE).strip()
if s.startswith('"') and s.endswith('"') and len(s) > 40:
s = s[1:-1].strip()
return s
def _passes_quality(text: str, style: str) -> bool:
if len(text) < 35 or len(text) > 2600:
return False
low = text.lower()
if any(bad in low for bad in ("here is a refusal", "here's a refusal", "sure, here is an example of", "certainly! here is")):
return False
if style in ("fulfillment_with_disclaimer", "apology_then_compliance", "meta_safety_discussion"):
# Reject accidental real refusals on non-refusal hard negatives
if re.match(r"^(i cannot|i can't|i'm unable|i am unable|i must decline|i refuse)\b", low):
return False
return True
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--out-dir", type=str, required=True)
parser.add_argument("--model", type=str, default="Qwen/Qwen3-8B")
parser.add_argument("--n-groups", type=int, default=1600, help="Number of 6-style contrastive groups (x6 = total items)")
parser.add_argument("--batch-size", type=int, default=48)
parser.add_argument("--seed", type=int, default=42)
args = parser.parse_args()
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
rng = random.Random(args.seed)
t0 = time.time()
print(f"[synth_refusal] Loading {args.model} on CUDA...", flush=True)
tok = AutoTokenizer.from_pretrained(args.model, use_fast=True)
tok.padding_side = "left"
if tok.pad_token_id is None:
tok.pad_token = tok.eos_token
model = AutoModelForCausalLM.from_pretrained(
args.model, torch_dtype=torch.bfloat16, device_map="auto"
).eval()
# Build paired tasks (group_id -> 6 contrastive styles in the same language + topic!)
langs = [x[0] for x in LANG_SPECS]
lang_codes = {x[0]: x[1] for x in LANG_SPECS}
lang_weights = [x[2] for x in LANG_SPECS]
personas = [
"concise engineering assistant",
"enterprise customer support bot",
"security-conscious coding agent",
"helpful domain expert",
"formal compliance advisor",
"friendly technical tutor",
]
tasks: list[dict[str, Any]] = []
for gid in range(args.n_groups):
lang_name = rng.choices(langs, weights=lang_weights, k=1)[0]
lang_code = lang_codes[lang_name]
topic = TOPICS[gid % len(TOPICS)]
persona = personas[gid % len(personas)]
# Hold out 12% of groups by pair_id strictly for the diagnostic stress test
split = "stress_test" if (gid % 25 in (0, 1, 2)) else ("val" if (gid % 25 == 3) else "train")
for style_name, label, instr in STYLES:
user_prompt = (
f"Language: {lang_name}. Persona: {persona}. Topic: {topic}.\n"
f"Task: {instr}\n"
f"Write strictly in {lang_name}. Output ONLY the assistant's reply text with no preamble or meta-commentary."
)
tasks.append({
"pair_id": f"grp_{gid:05d}",
"split": split,
"lang": lang_code,
"lang_name": lang_name,
"topic": topic,
"style": style_name,
"label": label,
"user_prompt": user_prompt,
})
print(f"[synth_refusal] Generating {len(tasks):,} contrastive replies ({args.n_groups} paired groups, bs={args.batch_size})...", flush=True)
seen_hashes: set[str] = set()
kept_train: list[dict[str, Any]] = []
kept_val: list[dict[str, Any]] = []
kept_stress: list[dict[str, Any]] = []
dropped = 0
for start in range(0, len(tasks), args.batch_size):
batch = tasks[start : start + args.batch_size]
prompts = []
for item in batch:
msgs = [{"role": "user", "content": item["user_prompt"]}]
try:
p = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False)
except TypeError:
p = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
prompts.append(p)
enc = tok(prompts, return_tensors="pt", padding=True, truncation=True, max_length=512).to(model.device)
in_len = enc["input_ids"].shape[1]
with torch.no_grad():
out_ids = model.generate(
**enc,
max_new_tokens=220,
do_sample=True,
temperature=0.82,
top_p=0.92,
pad_token_id=tok.pad_token_id,
eos_token_id=tok.eos_token_id,
)
gen_texts = tok.batch_decode(out_ids[:, in_len:], skip_special_tokens=True)
for item, raw_txt in zip(batch, gen_texts):
txt = _clean_text(raw_txt)
if not _passes_quality(txt, item["style"]):
dropped += 1
continue
h = norm_md5(txt)
if h in seen_hashes:
dropped += 1
continue
seen_hashes.add(h)
rec = {
"text": txt,
"label": item["label"],
"style": item["style"],
"lang": item["lang"],
"topic": item["topic"],
"pair_id": item["pair_id"],
"source": f"qwen3_synth_{item['style']}",
}
if item["split"] == "stress_test":
kept_stress.append(rec)
elif item["split"] == "val":
kept_val.append(rec)
else:
kept_train.append(rec)
done = min(start + args.batch_size, len(tasks))
if done % (args.batch_size * 10) == 0 or done == len(tasks):
dt = time.time() - t0
print(
f"[synth_refusal] {done:,}/{len(tasks):,} ({dt:.0f}s) | train={len(kept_train):,} val={len(kept_val):,} stress={len(kept_stress):,} drop={dropped}",
flush=True,
)
def _dump(path: Path, rows: list[dict[str, Any]]) -> None:
with path.open("w", encoding="utf-8") as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
_dump(out_dir / "synth_train.jsonl", kept_train)
_dump(out_dir / "synth_val.jsonl", kept_val)
_dump(out_dir / "synth_stress_test.jsonl", kept_stress)
summary = {
"model": args.model,
"n_groups": args.n_groups,
"train_kept": len(kept_train),
"val_kept": len(kept_val),
"stress_test_kept": len(kept_stress),
"dropped": dropped,
"runtime_sec": round(time.time() - t0, 1),
}
(out_dir / "synth_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
print("[synth_refusal] DONE:", json.dumps(summary), flush=True)
if __name__ == "__main__":
main()
|