Run this model with HF Jobs

Run Tamarillo/refusal-guard-small 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-small. 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-small 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-small / scripts /data_builder.py
greendesk1631's picture
Release Tamarillo/refusal-guard-small (140.6M multilingual Apache-2.0 garak drop-in, 100%-parity FP32/FP16/Gather-INT8 ONNX, Stage-2 PASS)
97ceea8 verified
Raw History Blame Contribute Delete
16.5 kB
"""Build commercially clean training/validation sets and 3-tier 6-suite evaluation sets
for Tamarillo/refusal-guard (`tiny-en` 32M + `small` 141M, internal `base` teacher).
100% commercially clean training sources (ZERO CC-BY-NC, ZERO CC-BY-SA, strict MD5 dedup vs ALL eval sets):
- ToxicityPrompts/PolyGuardMix (CC-BY-4.0, 17 languages — native response_refusal_label)
- Qwen/Qwen3-8B contrastive paired corpus (Apache-2.0, 10 languages + agent tool refusals + disclaimer compliance)
- OpenAssistant/oasst2 (Apache-2.0 — real benign trigger-word assistant responses)
3-Tier Evaluation Suites (MD5-deduplicated; ZERO train/val overlap):
Tier A (Strictly Zero-Shot External OOD):
1. ood_do_not_answer (LibrAI/do-not-answer, CC-BY-NC-SA-4.0, EVAL-ONLY, 6 real LLMs)
2. ood_jbb_judge (JailbreakBench/JBB-Behaviors judge_comparison, MIT, n=300)
Tier B (Same-Taxonomy Held-Out Test — PolyGuardMix derives from WildGuard train):
3. heldout_wildguard_en (sbintuitions/WildGuardTestJP response_original, ODC-BY, n=1,725)
4. heldout_wildguard_jp (sbintuitions/WildGuardTestJP response, ODC-BY, n=1,725)
Tier C (Independent-Generator microsoft/Phi-4-mini-instruct Diagnostic Suites):
5. diag_phi4_disclaimer (~360 disjoint-topic disclaimer-compliance vs subtle/agent refusals)
6. diag_phi4_lc2048 (~240 long-context 1,200–2,048 tok agent traces)
"""
from __future__ import annotations
import argparse
import ast
import json
import random
import re
from collections import Counter
from pathlib import Path
from typing import Any
from datasets import load_dataset
from schema import norm_md5
TRIGGER_RE = re.compile(
r"\b(sorry|apologize|cannot|can't|unable|illegal|harmful|unethical|policy|guidelines|refuse|decline|condone|dangerous|prohibited|disclaimer)\b",
re.IGNORECASE,
)
TRAIN_LOG_BLOCKS = [
"[tool:git_status] branch=release/2026-11 clean=true ahead=0 modified=0\n",
"[tool:http_get] url=https://internal.api/v2/health status=200 latency_ms=14.8 body={\"ok\":true}\n",
"[tool:db_query] SELECT id, status FROM jobs WHERE state='completed' ORDER BY updated_at DESC LIMIT 5; -- 5 rows (2.1ms)\n",
"[tool:file_read] path=docs/runbook.md bytes=4120 encoding=utf-8 sha256=3b1c9d4e...\n",
"[tool:vector_search] top_k=3 scores=[0.91,0.87,0.84] index=engineering-kb\n",
"[tool:test_runner] suite=pytest-unit passed=318 failed=0 skipped=2 elapsed=4.9s\n",
]
def _wrap_lc_train(reply: str, rng: random.Random) -> str:
target_chars = rng.randint(3600, 6600)
parts = ["Agent trace context (tool outputs observed prior to assistant response):\n"]
cur = len(parts[0])
step = 1
while cur < target_chars:
blk = f"[{step:02d}] " + rng.choice(TRAIN_LOG_BLOCKS)
parts.append(blk)
cur += len(blk)
step += 1
parts.append("\nAssistant:\n" + reply)
return "".join(parts)
def _parse_lang(meta_raw: Any) -> str:
if isinstance(meta_raw, dict):
return str(meta_raw.get("language", "english")).strip().lower()
if isinstance(meta_raw, str) and meta_raw.strip().startswith("{"):
try:
d = ast.literal_eval(meta_raw)
if isinstance(d, dict):
return str(d.get("language", "english")).strip().lower()
except Exception:
pass
return "english"
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 main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--out-dir", type=str, required=True)
parser.add_argument("--synth-dir", type=str, required=True)
parser.add_argument("--mode", choices=["en", "multilingual"], default="multilingual")
parser.add_argument("--max-polyguard", type=int, default=48000)
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)
synth_dir = Path(args.synth_dir)
rng = random.Random(args.seed)
eval_hashes: set[str] = set()
test_suites: dict[str, list[dict[str, Any]]] = {}
# 1. Tier B: Held-Out WildGuardTest-EN & WildGuardTest-JP (ODC-BY, n=1,725 each)
print("[data] Loading Held-Out WildGuardTest-EN & WildGuardTest-JP (sbintuitions/WildGuardTestJP)...", flush=True)
ds_wg = list(load_dataset("sbintuitions/WildGuardTestJP", split="test"))
wg_en, wg_jp = [], []
for row in ds_wg:
lbl_raw = str(row.get("response_refusal_label") or "").strip().lower()
if lbl_raw not in ("refusal", "compliance"):
continue
lbl = 1 if lbl_raw == "refusal" else 0
r_en = (row.get("response_original") or "").strip()
r_jp = (row.get("response") or "").strip()
if len(r_en) >= 5:
eval_hashes.add(norm_md5(r_en))
wg_en.append({"text": r_en, "label": lbl, "source": "wildguard_test_en", "adversarial": bool(row.get("adversarial"))})
if len(r_jp) >= 5:
eval_hashes.add(norm_md5(r_jp))
wg_jp.append({"text": r_jp, "label": lbl, "source": "wildguard_test_jp", "adversarial": bool(row.get("adversarial"))})
test_suites["heldout_wildguard_en"] = wg_en
test_suites["heldout_wildguard_jp"] = wg_jp
print(f"[data] WildGuardTest-EN={len(wg_en)}, WildGuardTest-JP={len(wg_jp)}", flush=True)
# 2. Tier A: Strictly Zero-Shot OOD LibrAI/do-not-answer (CC-BY-NC-SA-4.0, EVAL-ONLY!)
print("[data] Loading Strictly Zero-Shot OOD LibrAI/do-not-answer (EVAL-ONLY)...", flush=True)
ds_dna = list(load_dataset("LibrAI/do-not-answer", split="train"))
models_dna = ["GPT4", "ChatGPT", "Claude", "ChatGLM2", "llama2-7b-chat", "vicuna-7b"]
dna_rows = []
dna_seen = set()
for row in ds_dna:
for pref in models_dna:
resp = (row.get(f"{pref}_response") or "").strip()
if len(resp) < 10:
continue
try:
act = int(row.get(f"{pref}_action"))
except Exception:
continue
# Strict Do-Not-Answer paper taxonomy: 0=cannot assist, 4=cannot offer/capability refusal -> refusal (1); 5=direct follow -> compliance (0).
# (Excludes ambiguous/educational action=1 "refute/discuss", action=2 "dual perspective", action=3 "perceive risk with answer".)
if act in (0, 4):
lbl = 1
elif act == 5:
lbl = 0
else:
continue
h = norm_md5(resp)
eval_hashes.add(h)
if h not in dna_seen:
dna_seen.add(h)
dna_rows.append({"text": resp, "label": lbl, "source": f"dna_{pref}"})
rng.shuffle(dna_rows)
test_suites["ood_do_not_answer"] = dna_rows[:1800]
print(f"[data] OOD Do-Not-Answer={len(test_suites['ood_do_not_answer'])} (pos={sum(r['label'] for r in test_suites['ood_do_not_answer'])})", flush=True)
# 3. Tier A: Strictly Zero-Shot OOD JailbreakBench/JBB-Behaviors judge_comparison (MIT, n=300)
print("[data] Loading Strictly Zero-Shot OOD JailbreakBench/JBB-Behaviors (judge_comparison)...", flush=True)
ds_jbb = list(load_dataset("JailbreakBench/JBB-Behaviors", "judge_comparison", split="test"))
jbb_rows = []
for row in ds_jbb:
resp = (row.get("target_response") or "").strip()
if len(resp) < 5:
continue
try:
hm = int(row.get("human_majority"))
except Exception:
continue
# human_majority=1 means jailbroken (complied with harmful prompt -> non-refusal=0); 0 means safe/refused -> refusal=1
lbl = 0 if hm == 1 else 1
eval_hashes.add(norm_md5(resp))
jbb_rows.append({"text": resp, "label": lbl, "source": "jbb_judge_comparison"})
test_suites["ood_jbb_judge"] = jbb_rows
print(f"[data] OOD JBB-JudgeComparison={len(jbb_rows)} (pos={sum(r['label'] for r in jbb_rows)})", flush=True)
# 4. Tier C: Independent-Generator microsoft/Phi-4-mini-instruct Diagnostic Suites
phi4_disc = _load_jsonl(synth_dir / "phi4_disclaimer_stress.jsonl")
phi4_lc_raw = _load_jsonl(synth_dir / "phi4_lc_2048_stress.jsonl")
# Ensure benign agent-trace preamble fits cleanly inside ~1,400–1,800 tokens (well past 512-tok truncation, never clipped at 2,048!)
phi4_lc = []
marker = "\nFinal assistant response:\n"
for r in phi4_lc_raw:
txt = r["text"]
if marker in txt:
pre, tail = txt.split(marker, 1)
lines = pre.splitlines()
kept_pre = []
char_cnt = 0
for ln in lines:
if char_cnt + len(ln) > 3400:
break
kept_pre.append(ln)
char_cnt += len(ln) + 1
txt = "\n".join(kept_pre) + marker + tail
rec = dict(r)
rec["text"] = txt
phi4_lc.append(rec)
for r in phi4_disc + phi4_lc:
eval_hashes.add(norm_md5(r["text"]))
test_suites["diag_phi4_disclaimer"] = phi4_disc
test_suites["diag_phi4_lc2048"] = phi4_lc
print(f"[data] Tier-C Phi-4-mini Diagnostic: disclaimer={len(phi4_disc)}, lc1600={len(phi4_lc)}", flush=True)
# ---------- Build Clean Training & Validation Sets (ZERO overlap with eval_hashes!) ----------
train_rows: list[dict[str, Any]] = []
val_rows: list[dict[str, Any]] = []
seen_tv: set[str] = set()
def _add(text: str, label: int, source: str, kind: str, pair_id: str = "", lang: str = "en", is_val: bool = False) -> bool:
t = (text or "").strip()
if len(t) < 15:
return False
h = norm_md5(t)
if h in eval_hashes or h in seen_tv:
return False
seen_tv.add(h)
rec = {"text": t, "label": int(label), "source": source, "kind": kind, "pair_id": pair_id, "lang": lang}
if is_val:
val_rows.append(rec)
else:
train_rows.append(rec)
return True
# Source 1: Qwen3-8B Contrastive Paired Corpus (Apache-2.0)
s_train = _load_jsonl(synth_dir / "synth_train.jsonl")
s_val = _load_jsonl(synth_dir / "synth_val.jsonl")
synth_tr_added, synth_va_added = 0, 0
for r in s_val:
if args.mode == "en" and r.get("lang") != "en":
continue
kind = "disclaimer_neg" if r["label"] == 0 else "synth_refusal"
if _add(r["text"], r["label"], r["source"], kind, pair_id=r.get("pair_id", ""), lang=r.get("lang", "en"), is_val=True):
synth_va_added += 1
lc_candidates_pos, lc_candidates_neg = [], []
for r in s_train:
if args.mode == "en" and r.get("lang") != "en":
continue
kind = "disclaimer_neg" if r["label"] == 0 else "synth_refusal"
if _add(r["text"], r["label"], r["source"], kind, pair_id=r.get("pair_id", ""), lang=r.get("lang", "en"), is_val=False):
synth_tr_added += 1
if r["label"] == 1:
lc_candidates_pos.append(r)
else:
lc_candidates_neg.append(r)
print(f"[data] Qwen3-8B contrastive: train={synth_tr_added:,}, val={synth_va_added:,}", flush=True)
# Source 2: ToxicityPrompts/PolyGuardMix (CC-BY-4.0, 17 languages — real multi-LLM responses!)
print(f"[data] Streaming ToxicityPrompts/PolyGuardMix (mode={args.mode}, cap={args.max_polyguard:,})...", flush=True)
ds_pg = load_dataset("ToxicityPrompts/PolyGuardMix", split="train", streaming=True)
pg_lang_cap = args.max_polyguard if args.mode == "en" else max(2800, args.max_polyguard // 15)
pg_counts: Counter[tuple[str, int]] = Counter()
pg_added, pg_val = 0, 0
for row in ds_pg:
if pg_added >= args.max_polyguard:
break
resp = (row.get("response") or "").strip()
if len(resp) < 15:
continue
lbl_raw = str(row.get("response_refusal_label") or "").strip().lower()
if lbl_raw in ("yes", "refusal"):
lbl = 1
elif lbl_raw in ("no", "compliance"):
lbl = 0
else:
continue
lang = _parse_lang(row.get("metadata"))
if args.mode == "en" and not lang.startswith("en"):
continue
half_cap = pg_lang_cap // 2
if pg_counts[(lang, lbl)] >= half_cap:
continue
is_val = (pg_val < 2000) and (pg_counts[(lang, lbl)] % 20 == 0)
if _add(resp, lbl, f"polyguard_{lang}", "polyguard_real", lang=lang[:2], is_val=is_val):
pg_counts[(lang, lbl)] += 1
if is_val:
pg_val += 1
else:
pg_added += 1
if len(lc_candidates_pos) < 5000 and lbl == 1 and len(resp) < 1500:
lc_candidates_pos.append({"text": resp, "label": 1, "lang": lang[:2]})
elif len(lc_candidates_neg) < 5000 and lbl == 0 and len(resp) < 1500:
lc_candidates_neg.append({"text": resp, "label": 0, "lang": lang[:2]})
print(f"[data] PolyGuardMix collected: train={pg_added:,}, val={pg_val:,} across {len({k[0] for k in pg_counts})} languages", flush=True)
# Source 3: OpenAssistant/oasst2 (Apache-2.0 — real natural helpful assistant replies, esp. trigger-word benign!)
print("[data] Mining OpenAssistant/oasst2 (Apache-2.0) benign & trigger-word assistant replies...", flush=True)
oasst_added, oasst_trig = 0, 0
for row in load_dataset("OpenAssistant/oasst2", split="train"):
if oasst_added >= 6000:
break
if row.get("role") != "assistant":
continue
lang = str(row.get("lang") or "en").lower()
if args.mode == "en" and lang != "en":
continue
txt = (row.get("text") or "").strip()
if len(txt) < 60 or len(txt) > 2500:
continue
# Skip genuine refusals inside oasst2
if re.match(r"^(i'm sorry,?\s+but\s+i\s+(cannot|can't)|as an ai|i cannot|i can't assist|i'm unable to)", txt.lower()):
continue
has_trig = bool(TRIGGER_RE.search(txt))
if not has_trig and oasst_added >= 2000:
continue
is_val = has_trig and (oasst_trig < 250) and (oasst_trig % 10 == 0)
if _add(txt, 0, "oasst2_trigger_benign" if has_trig else "oasst2_benign", "disclaimer_neg" if has_trig else "clean_benign", lang=lang[:2], is_val=is_val):
oasst_added += 1
if has_trig:
oasst_trig += 1
print(f"[data] oasst2 collected: total={oasst_added:,} (with trigger words={oasst_trig:,})", flush=True)
# Source 4: 1:1 Balanced Long-Context (1,200-2,200 tok) Agent-Trace Wrapping (train only)
rng.shuffle(lc_candidates_pos)
rng.shuffle(lc_candidates_neg)
n_lc = min(2200, len(lc_candidates_pos), len(lc_candidates_neg))
lc_added = 0
for r in lc_candidates_pos[:n_lc] + lc_candidates_neg[:n_lc]:
wrapped = _wrap_lc_train(r["text"], rng)
if _add(wrapped, r["label"], "lc_trace_wrapped", "lc_trace", lang=r.get("lang", "en"), is_val=False):
lc_added += 1
print(f"[data] Balanced 1:1 LC agent-trace wrapped rows added: {lc_added:,}", flush=True)
rng.shuffle(train_rows)
rng.shuffle(val_rows)
def _write(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")
_write(out_dir / "train.jsonl", train_rows)
_write(out_dir / "val.jsonl", val_rows)
for k, rows in test_suites.items():
_write(out_dir / f"test_{k}.jsonl", rows)
stats = {
"mode": args.mode,
"train_count": len(train_rows),
"train_pos_rate": round(sum(r["label"] for r in train_rows) / max(1, len(train_rows)), 4),
"val_count": len(val_rows),
"val_pos_rate": round(sum(r["label"] for r in val_rows) / max(1, len(val_rows)), 4),
"train_kinds": dict(Counter(r["kind"] for r in train_rows)),
"test_suites": {k: {"n": len(v), "pos": sum(r["label"] for r in v)} for k, v in test_suites.items()},
}
(out_dir / "dataset_stats.json").write_text(json.dumps(stats, indent=2), encoding="utf-8")
print("[data] SUMMARY:", json.dumps(stats, indent=2), flush=True)
if __name__ == "__main__":
main()