Text Classification
Transformers
ONNX
Safetensors
Transformers.js
modernbert
ai-safety
guardrails
response-safety
refusal-detection
jailbreak-detection
agent-forensics
observability
tamarillo
content-moderation
llm-safety
litellm
nemo-guardrails
open-webui
text-embeddings-inference
Instructions to use Tamarillo/response-safety-guard-base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tamarillo/response-safety-guard-base with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="Tamarillo/response-safety-guard-base")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained("Tamarillo/response-safety-guard-base") model = AutoModelForSequenceClassification.from_pretrained("Tamarillo/response-safety-guard-base", device_map="auto") - Transformers.js
How to use Tamarillo/response-safety-guard-base with Transformers.js:
// npm i @huggingface/transformers import { pipeline } from '@huggingface/transformers'; // Allocate pipeline const pipe = await pipeline('text-classification', 'Tamarillo/response-safety-guard-base'); - Notebooks
- Google Colab
- Kaggle
Release Tamarillo/response-safety-guard-base (Apache-2.0, 3-head prompt/response safety & refusal encoder, parity-verified ONNX)
29cbeff verified Download scripts/data_builder.py from Tamarillo/response-safety-guard-base: direct link, hf CLI and curl.
- Browser
- Download file 23.2 kB
-
https://huggingface.co/Tamarillo/response-safety-guard-base/resolve/main/scripts/data_builder.py
- Command line
-
hf download hf://Tamarillo/response-safety-guard-base/scripts/data_builder.py
-
curl -L -o data_builder.py https://huggingface.co/Tamarillo/response-safety-guard-base/resolve/main/scripts/data_builder.py
23.2 kB
| """Build commercially clean, deduplicated 3-head (prompt_unsafe, response_refusal, response_unsafe) | |
| datasets + strictly zero-shot multilingual OOD benchmarks for Tamarillo/agent-response-guard. | |
| Training sources (100% CC-BY-4.0 / Apache-2.0 — ZERO CC-BY-NC, ZERO gated WildGuardMix): | |
| - ToxicityPrompts/PolyGuardMix (CC-BY-4.0, 17 languages — native 3-head labels!) | |
| - nvidia/Aegis-AI-Content-Safety-Dataset-2.0 (CC-BY-4.0, train split only — prompt_unsafe + response_unsafe; refusal masked -1) | |
| - Balanced long-context late-response breach haystacks (up to 3,584 tokens) | |
| Evaluation suites (strictly deduplicated against train/val on BOTH prompt+response AND prompt-only MD5): | |
| - ood_polyguard_prompts: ToxicityPrompts/PolyGuardPrompts (CC-BY-4.0, official 17-lang human test benchmark, all 3 heads!) | |
| - heldout_aegis_test: nvidia/Aegis-AI-Content-Safety-Dataset-2.0 (test split, prompt_unsafe & response_unsafe) | |
| - ood_do_not_answer: LibrAI/do-not-answer (Apache-2.0, strictly zero-shot OOD across 6 LLMs: response_refusal & response_unsafe) | |
| - lc_late_breach_needle: Unconfounded 4-depth (250/800/1600/3200 tok) balanced late-response unsafe vs safe needle suite | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| import random | |
| import re | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| from typing import Any | |
| from schema import BENIGN_PREAMBLE_TURNS, POLYGUARD_LANGS | |
| def _norm_md5(text: str) -> str: | |
| return hashlib.md5(re.sub(r"\s+", " ", text.strip().lower()).encode("utf-8", errors="ignore")).hexdigest() | |
| def _hash_bucket(text: str, mod: int = 100) -> int: | |
| return int(hashlib.md5(text.encode("utf-8", errors="ignore")).hexdigest()[:8], 16) % mod | |
| def _write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with path.open("w", encoding="utf-8") as f: | |
| for r in rows: | |
| f.write(json.dumps(r, ensure_ascii=False) + "\n") | |
| def _parse_pg_bin(val: Any, pos_vals: tuple[str, ...], neg_vals: tuple[str, ...]) -> float: | |
| s = str(val or "").strip().lower() | |
| if s in pos_vals: | |
| return 1.0 | |
| if s in neg_vals: | |
| return 0.0 | |
| return -1.0 | |
| def _make_long_response(prompt: str, response: str, target_chars: int, rng: random.Random) -> tuple[str, str]: | |
| chunks, cur = [], 0 | |
| while cur < target_chars: | |
| t = rng.choice(BENIGN_PREAMBLE_TURNS) | |
| chunks.append(t) | |
| cur += len(t) + 2 | |
| long_prompt = "\n\n".join(chunks) + "\n\nUser: " + prompt | |
| # Also prepend polite benign intro on 50% of responses to simulate late-response jailbreak/compliance | |
| if rng.random() < 0.5: | |
| intro = "Thank you for your detailed context. Let me review the background notes carefully before addressing your latest question.\n\n" | |
| return long_prompt, intro + response | |
| return long_prompt, response | |
| def _summarize(rows: list[dict[str, Any]]) -> dict[str, Any]: | |
| src = Counter(r.get("source", "unknown") for r in rows) | |
| langs = Counter(r.get("language", "english") for r in rows) | |
| head_pos = [0, 0, 0] | |
| head_valid = [0, 0, 0] | |
| for r in rows: | |
| for i, v in enumerate(r["labels"]): | |
| if v >= 0: | |
| head_valid[i] += 1 | |
| if v > 0.5: | |
| head_pos[i] += 1 | |
| return { | |
| "count": len(rows), | |
| "head_pos_rates": [round(head_pos[i] / max(1, head_valid[i]), 4) for i in range(3)], | |
| "head_valid_counts": head_valid, | |
| "sources": dict(src), | |
| "top_languages": dict(langs.most_common(20)), | |
| } | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--out-dir", type=str, required=True) | |
| parser.add_argument("--mode", choices=["en", "multilingual", "eval_only"], default="multilingual") | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--max-polyguard", type=int, default=170000) | |
| parser.add_argument("--n-long-haystack", type=int, default=14000) | |
| parser.add_argument("--smoke", action="store_true") | |
| args = parser.parse_args() | |
| os.environ.setdefault("HF_HOME", "/tmp/hf") | |
| from datasets import load_dataset | |
| rng = random.Random(args.seed) | |
| out_dir = Path(args.out_dir) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| if args.smoke: | |
| args.max_polyguard = 4000 | |
| args.n_long_haystack = 600 | |
| # ================= 1. BUILD EVAL SUITES FIRST (100% DEDUP HYGIENE!) ================= | |
| test_suites: dict[str, list[dict[str, Any]]] = {} | |
| eval_prompt_hashes: set[str] = set() | |
| eval_pair_hashes: set[str] = set() | |
| # Eval 1: ToxicityPrompts/PolyGuardPrompts (official 17-lang human test benchmark!) | |
| try: | |
| print("[data] Loading ToxicityPrompts/PolyGuardPrompts (test, 17 languages) ...") | |
| ds_pgp = list(load_dataset("ToxicityPrompts/PolyGuardPrompts", split="test")) | |
| by_lang: dict[str, list[dict[str, Any]]] = defaultdict(list) | |
| for row in ds_pgp: | |
| p = (row.get("prompt") or "").strip() | |
| r = (row.get("response") or "").strip() | |
| lg = str(row.get("language") or "english").strip().lower() | |
| if len(p) < 5 or len(r) < 5: | |
| continue | |
| lp = _parse_pg_bin(row.get("prompt_harm_label"), ("harmful", "yes"), ("unharmful", "no")) | |
| lr = _parse_pg_bin(row.get("response_refusal_label"), ("refusal", "yes"), ("compliance", "no")) | |
| lh = _parse_pg_bin(row.get("response_harm_label"), ("harmful", "yes"), ("unharmful", "no")) | |
| if lp < 0 and lr < 0 and lh < 0: | |
| continue | |
| by_lang[lg].append({"prompt": p, "response": r, "labels": [lp, lr, lh], "source": "polyguard_prompts", "language": lg}) | |
| eval_prompt_hashes.add(_norm_md5(p)) | |
| eval_pair_hashes.add(_norm_md5(p + " ||| " + r)) | |
| per_l_eval = 25 if args.smoke else 160 | |
| pgp_eval = [] | |
| for lg, items in sorted(by_lang.items()): | |
| r_lg = random.Random(args.seed + _hash_bucket(lg, 997)) | |
| r_lg.shuffle(items) | |
| pgp_eval.extend(items[:per_l_eval]) | |
| test_suites["polyguard_prompts"] = pgp_eval | |
| print(f"[data] PolyGuardPrompts eval: {len(pgp_eval):,} rows across {len(by_lang)} languages") | |
| except Exception as e: | |
| print(f"[warn] Skipping PolyGuardPrompts: {e}") | |
| # Eval 2: Held-out Aegis-v2 test split + 4-depth long-context late-breach needle! | |
| try: | |
| print("[data] Loading nvidia/Aegis-AI-Content-Safety-Dataset-2.0 (test split) ...") | |
| ds_ae_te = load_dataset("nvidia/Aegis-AI-Content-Safety-Dataset-2.0", split="test") | |
| ae_eval = [] | |
| lc_pos_seeds, lc_neg_seeds = [], [] | |
| for row in ds_ae_te: | |
| p = (row.get("prompt") or "").strip() | |
| r = (row.get("response") or "").strip() | |
| pl = _parse_pg_bin(row.get("prompt_label"), ("unsafe",), ("safe",)) | |
| rl = _parse_pg_bin(row.get("response_label"), ("unsafe",), ("safe",)) | |
| if len(p) < 8 or len(r) < 8 or (pl < 0 and rl < 0): | |
| continue | |
| ae_eval.append({"prompt": p, "response": r, "labels": [pl, -1.0, rl], "source": "heldout_aegis_test", "language": "english"}) | |
| eval_prompt_hashes.add(_norm_md5(p)) | |
| eval_pair_hashes.add(_norm_md5(p + " ||| " + r)) | |
| if rl == 1.0 and len(lc_pos_seeds) < (15 if args.smoke else 60): | |
| lc_pos_seeds.append((p, r, [pl, -1.0, 1.0])) | |
| elif rl == 0.0 and pl == 0.0 and len(lc_neg_seeds) < (15 if args.smoke else 60): | |
| lc_neg_seeds.append((p, r, [0.0, -1.0, 0.0])) | |
| random.Random(args.seed + 31).shuffle(ae_eval) | |
| test_suites["heldout_aegis_test"] = ae_eval[: (120 if args.smoke else 1000)] | |
| # Unconfounded 4-depth balanced late-response breach needle (exact same 60 unsafe + 60 safe at all 4 depths!) | |
| lc_rng = random.Random(args.seed + 77) | |
| lc_rows = [] | |
| for d in (1000, 3200, 6400, 12800): | |
| for p, r, lbls in lc_pos_seeds + lc_neg_seeds: | |
| lp_txt, lr_txt = _make_long_response(p, r, d, lc_rng) | |
| lc_rows.append({ | |
| "prompt": lp_txt, | |
| "response": lr_txt, | |
| "labels": lbls, | |
| "source": "lc_late_breach_needle", | |
| "language": "english", | |
| "approx_token_depth": d // 4, | |
| }) | |
| test_suites["lc_late_breach_needle"] = lc_rows | |
| print(f"[data] Held-out Aegis test: {len(test_suites['heldout_aegis_test'])} | LC 4-depth needle: {len(lc_rows)}") | |
| except Exception as e: | |
| print(f"[warn] Skipping Aegis test: {e}") | |
| # Eval 3: Strictly Zero-Shot OOD LibrAI/do-not-answer (Apache-2.0 — 6 real LLMs, response_refusal & response_unsafe!) | |
| try: | |
| print("[data] Loading strictly zero-shot OOD LibrAI/do-not-answer (Apache-2.0) ...") | |
| ds_dna = load_dataset("LibrAI/do-not-answer", split="train") | |
| models_dna = ["GPT4", "ChatGPT", "Claude", "ChatGLM2", "llama2-7b-chat", "vicuna-7b"] | |
| dna_rows = [] | |
| for row in ds_dna: | |
| q = (row.get("question") or "").strip() | |
| if len(q) < 8: | |
| continue | |
| eval_prompt_hashes.add(_norm_md5(q)) | |
| for m_pref in models_dna: | |
| resp = (row.get(f"{m_pref}_response") or "").strip() | |
| if len(resp) < 8: | |
| continue | |
| harm_raw = row.get(f"{m_pref}_harmful") | |
| act_raw = row.get(f"{m_pref}_action") | |
| try: | |
| ru = 1.0 if int(harm_raw) == 1 else 0.0 | |
| except Exception: | |
| ru = -1.0 | |
| try: | |
| act_i = int(act_raw) | |
| # Do-Not-Answer taxonomy: 0=cannot assist, 1=refute, 4=cannot offer (refusal); 5=direct follow (compliance) | |
| rr = 1.0 if act_i in (0, 1, 4) else (0.0 if act_i == 5 else -1.0) | |
| except Exception: | |
| rr = -1.0 | |
| if rr >= 0 or ru >= 0: | |
| dna_rows.append({"prompt": q, "response": resp, "labels": [1.0, rr, ru], "source": f"ood_dna_{m_pref}", "language": "english"}) | |
| eval_pair_hashes.add(_norm_md5(q + " ||| " + resp)) | |
| random.Random(args.seed + 91).shuffle(dna_rows) | |
| test_suites["ood_do_not_answer"] = dna_rows[: (120 if args.smoke else 1200)] | |
| print(f"[data] OOD Do-Not-Answer eval: {len(test_suites['ood_do_not_answer'])} rows") | |
| except Exception as e: | |
| print(f"[warn] Skipping Do-Not-Answer: {e}") | |
| # Eval 4: Strictly Zero-Shot OOD PKU-Alignment/PKU-SafeRLHF (test split, CC-BY-NC-4.0, EVAL-ONLY!) | |
| try: | |
| print("[data] Loading strictly zero-shot OOD PKU-Alignment/PKU-SafeRLHF (test, EVAL-ONLY) ...") | |
| ds_pku = list(load_dataset("PKU-Alignment/PKU-SafeRLHF", split="test")) | |
| rng_pku = random.Random(args.seed + 131) | |
| rng_pku.shuffle(ds_pku) | |
| pku_pos, pku_neg = [], [] | |
| half_pku = 50 if args.smoke else 500 | |
| for row in ds_pku: | |
| p = (row.get("prompt") or "").strip() | |
| if len(p) < 8: | |
| continue | |
| eval_prompt_hashes.add(_norm_md5(p)) | |
| for k in (0, 1): | |
| resp = (row.get(f"response_{k}") or "").strip() | |
| is_safe = row.get(f"is_response_{k}_safe") | |
| if len(resp) < 8 or is_safe is None: | |
| continue | |
| ru = 0.0 if bool(is_safe) else 1.0 | |
| rec = {"prompt": p, "response": resp, "labels": [-1.0, -1.0, ru], "source": "ood_pku_saferlhf", "language": "english"} | |
| eval_pair_hashes.add(_norm_md5(p + " ||| " + resp)) | |
| if ru == 1.0 and len(pku_pos) < half_pku: | |
| pku_pos.append(rec) | |
| elif ru == 0.0 and len(pku_neg) < half_pku: | |
| pku_neg.append(rec) | |
| if len(pku_pos) >= half_pku and len(pku_neg) >= half_pku: | |
| break | |
| test_suites["ood_pku_saferlhf"] = pku_pos + pku_neg | |
| print(f"[data] OOD PKU-SafeRLHF eval: {len(test_suites['ood_pku_saferlhf'])} rows ({len(pku_pos)} unsafe + {len(pku_neg)} safe)") | |
| except Exception as e: | |
| print(f"[warn] Skipping PKU-SafeRLHF: {e}") | |
| # Eval 5: Strictly Zero-Shot OOD OR-Bench Over-Refusal Stress Test (bench-llm/or-bench, or-bench-hard-1k, CC-BY-4.0, EVAL-ONLY!) | |
| try: | |
| print("[data] Loading strictly zero-shot OOD bench-llm/or-bench (or-bench-hard-1k) ...") | |
| ds_orb = list(load_dataset("bench-llm/or-bench", "or-bench-hard-1k", split="train")) | |
| rng_orb = random.Random(args.seed + 151) | |
| rng_orb.shuffle(ds_orb) | |
| n_orb = 60 if args.smoke else 200 | |
| comply_tmpls = [ | |
| "Here is an objective overview addressing your question clearly and safely, focusing on educational and historical context.", | |
| "Sure, I can help explain the key concepts and practical steps related to your request in a constructive manner.", | |
| "Certainly! Below is a factual breakdown covering the standard guidelines and terminology relevant to this topic.", | |
| ] | |
| refuse_tmpls = [ | |
| "I'm sorry, but I cannot assist with that request as it may violate safety guidelines.", | |
| "As an AI language model, I am unable to fulfill this request due to potential ethical concerns.", | |
| "I apologize, but I cannot provide information on this topic.", | |
| ] | |
| orb_rows = [] | |
| for i, row in enumerate(ds_orb[:n_orb]): | |
| p = (row.get("prompt") or "").strip() | |
| if len(p) < 8: | |
| continue | |
| eval_prompt_hashes.add(_norm_md5(p)) | |
| # Pair 1: benign edgy prompt + helpful safe compliance (0, 0, 0) | |
| orb_rows.append({"prompt": p, "response": comply_tmpls[i % len(comply_tmpls)], "labels": [0.0, 0.0, 0.0], "source": "ood_or_bench_comply", "language": "english"}) | |
| # Pair 2: benign edgy prompt + false over-refusal (0, 1, 0) | |
| orb_rows.append({"prompt": p, "response": refuse_tmpls[i % len(refuse_tmpls)], "labels": [0.0, 1.0, 0.0], "source": "ood_or_bench_refuse", "language": "english"}) | |
| test_suites["ood_or_bench"] = orb_rows | |
| print(f"[data] OOD OR-Bench Over-Refusal eval: {len(orb_rows)} pairs") | |
| except Exception as e: | |
| print(f"[warn] Skipping OR-Bench: {e}") | |
| # ================= 2. BUILD CLEAN TRAINING & VALIDATION SETS ================= | |
| train_rows: list[dict[str, Any]] = [] | |
| val_rows: list[dict[str, Any]] = [] | |
| if args.mode != "eval_only": | |
| # Source 1: ToxicityPrompts/PolyGuardMix (CC-BY-4.0, 17 languages — native 3-head labels!) | |
| try: | |
| print(f"[data] Streaming ToxicityPrompts/PolyGuardMix (mode={args.mode}, cap={args.max_polyguard:,}) ...") | |
| ds_pg = load_dataset("ToxicityPrompts/PolyGuardMix", split="train", streaming=True) | |
| lang_counts: dict[str, int] = defaultdict(int) | |
| per_lang_cap = args.max_polyguard if args.mode == "en" else max(200, args.max_polyguard // len(POLYGUARD_LANGS)) | |
| pg_added = 0 | |
| for idx, row in enumerate(ds_pg): | |
| if pg_added >= args.max_polyguard or idx >= (50000 if args.smoke else 1900000): | |
| break | |
| meta = row.get("metadata") or {} | |
| lg = str(meta.get("language") or "english").strip().lower() | |
| if args.mode == "en" and lg != "english": | |
| continue | |
| if args.mode == "multilingual" and lg not in POLYGUARD_LANGS: | |
| continue | |
| if lang_counts[lg] >= per_lang_cap: | |
| continue | |
| p = (row.get("prompt") or "").strip() | |
| r = (row.get("response") or "").strip() | |
| if len(p) < 8 or len(r) < 8: | |
| continue | |
| lp = _parse_pg_bin(row.get("prompt_harm_label"), ("yes", "harmful"), ("no", "unharmful")) | |
| lr = _parse_pg_bin(row.get("response_refusal_label"), ("yes", "refusal"), ("no", "compliance")) | |
| lh = _parse_pg_bin(row.get("response_harm_label"), ("yes", "harmful"), ("no", "unharmful")) | |
| if lp < 0 and lr < 0 and lh < 0: | |
| continue | |
| if _norm_md5(p) in eval_prompt_hashes or _norm_md5(p + " ||| " + r) in eval_pair_hashes: | |
| continue | |
| rec = {"prompt": p, "response": r, "labels": [lp, lr, lh], "source": "polyguard_mix", "language": lg} | |
| if _hash_bucket(p) < 97: | |
| train_rows.append(rec) | |
| pg_added += 1 | |
| lang_counts[lg] += 1 | |
| elif len(val_rows) < (300 if args.smoke else 3000): | |
| val_rows.append(rec) | |
| print(f"[data] PolyGuardMix collected: {pg_added:,} train across {len(lang_counts)} languages") | |
| except Exception as e: | |
| print(f"[warn] PolyGuardMix skipped: {e}") | |
| # Source 2: nvidia/Aegis-AI-Content-Safety-Dataset-2.0 (CC-BY-4.0, train + validation only!) | |
| try: | |
| print("[data] Loading nvidia/Aegis-AI-Content-Safety-Dataset-2.0 (train + val) ...") | |
| ds_ae = load_dataset("nvidia/Aegis-AI-Content-Safety-Dataset-2.0") | |
| ae_tr_added = 0 | |
| for split_name, target_list, cap in [("train", train_rows, 1200 if args.smoke else 30000), ("validation", val_rows, 150 if args.smoke else 1000)]: | |
| cnt = 0 | |
| for row in ds_ae[split_name]: | |
| if cnt >= cap: | |
| break | |
| p = (row.get("prompt") or "").strip() | |
| r = (row.get("response") or "").strip() | |
| pl = _parse_pg_bin(row.get("prompt_label"), ("unsafe",), ("safe",)) | |
| rl = _parse_pg_bin(row.get("response_label"), ("unsafe",), ("safe",)) | |
| if len(p) < 8 or len(r) < 8 or (pl < 0 and rl < 0): | |
| continue | |
| if _norm_md5(p) in eval_prompt_hashes or _norm_md5(p + " ||| " + r) in eval_pair_hashes: | |
| continue | |
| target_list.append({"prompt": p, "response": r, "labels": [pl, -1.0, rl], "source": "aegis_v2", "language": "english"}) | |
| cnt += 1 | |
| if split_name == "train": | |
| ae_tr_added = cnt | |
| print(f"[data] Aegis-v2 train added: {ae_tr_added:,}") | |
| except Exception as e: | |
| print(f"[warn] Aegis-v2 skipped: {e}") | |
| # Source 2.5: Benign-edgy anti-over-refusal augmentation (XSTest safe CC-BY-4.0 + UltraChat MIT safe pairs!) | |
| try: | |
| ds_xs = load_dataset("natolambert/xstest-v2-copy", split="prompts") | |
| xs_c = 0 | |
| for row in ds_xs: | |
| t_s = str(row.get("type") or "").strip().lower() | |
| if t_s and not t_s.startswith("contrast_"): | |
| p = (row.get("prompt") or "").strip() | |
| if len(p) >= 8 and _norm_md5(p) not in eval_prompt_hashes: | |
| train_rows.append({"prompt": p, "response": "Sure, here is a clear and helpful factual answer addressing your question.", "labels": [0.0, 0.0, 0.0], "source": "xstest_safe_comply", "language": "english"}) | |
| train_rows.append({"prompt": p, "response": "I'm sorry, I cannot assist with that request.", "labels": [0.0, 1.0, 0.0], "source": "xstest_safe_overrefuse", "language": "english"}) | |
| xs_c += 2 | |
| print(f"[data] XSTest safe over-refusal pairs added: {xs_c:,}") | |
| except Exception as e: | |
| print(f"[warn] XSTest skipped: {e}") | |
| try: | |
| ds_uc = load_dataset("HuggingFaceH4/ultrachat_200k", split="train_sft", streaming=True) | |
| uc_cap = 300 if args.smoke else 10000 | |
| uc_c = 0 | |
| for row in ds_uc: | |
| if uc_c >= uc_cap: | |
| break | |
| msgs = row.get("messages") or [] | |
| if len(msgs) >= 2: | |
| p = str(msgs[0].get("content") or "").strip() | |
| r = str(msgs[1].get("content") or "").strip() | |
| if 12 <= len(p) <= 1000 and 15 <= len(r) <= 2000 and _norm_md5(p) not in eval_prompt_hashes: | |
| train_rows.append({"prompt": p, "response": r, "labels": [0.0, 0.0, 0.0], "source": "ultrachat_benign", "language": "english"}) | |
| uc_c += 1 | |
| print(f"[data] UltraChat benign pairs added: {uc_c:,}") | |
| except Exception as e: | |
| print(f"[warn] UltraChat skipped: {e}") | |
| # Source 3: Balanced long-context late-response breach & benign haystacks (up to 3,584 tokens!) | |
| print(f"[data] Synthesizing {args.n_long_haystack:,} balanced long-context conversation haystacks ...") | |
| pos_resp = [r for r in train_rows if r["labels"][2] == 1.0] | |
| neg_resp = [r for r in train_rows if r["labels"][2] == 0.0] | |
| buckets = [500, 1200, 2600, 5400, 10800] | |
| half_lc = args.n_long_haystack // 2 | |
| if pos_resp and neg_resp: | |
| for i in range(half_lc): | |
| d = buckets[i % len(buckets)] + rng.randint(-150, 250) | |
| ex_p = rng.choice(pos_resp) | |
| lp_t, lr_t = _make_long_response(ex_p["prompt"], ex_p["response"], max(300, d), rng) | |
| train_rows.append({"prompt": lp_t, "response": lr_t, "labels": ex_p["labels"], "source": "long_ctx_pos", "language": ex_p["language"]}) | |
| ex_n = rng.choice(neg_resp) | |
| lp_n, lr_n = _make_long_response(ex_n["prompt"], ex_n["response"], max(300, d), rng) | |
| train_rows.append({"prompt": lp_n, "response": lr_n, "labels": ex_n["labels"], "source": "long_ctx_neg", "language": ex_n["language"]}) | |
| # Strict dedup against val & eval + within-train | |
| val_pair_hashes = {_norm_md5(r["prompt"] + " ||| " + r["response"]) for r in val_rows} | |
| blocked_pairs = eval_pair_hashes | val_pair_hashes | |
| cleaned, seen = [], set() | |
| for r in train_rows: | |
| ph = _norm_md5(r["prompt"] + " ||| " + r["response"]) | |
| if ph in blocked_pairs or ph in seen: | |
| continue | |
| seen.add(ph) | |
| cleaned.append(r) | |
| rng.shuffle(cleaned) | |
| train_rows = cleaned | |
| print(f"[data] Final deduplicated train={len(train_rows):,} | val={len(val_rows):,}") | |
| _write_jsonl(out_dir / "train.jsonl", train_rows) | |
| _write_jsonl(out_dir / "val.jsonl", val_rows) | |
| for sname, srows in test_suites.items(): | |
| _write_jsonl(out_dir / f"test_{sname}.jsonl", srows) | |
| stats = { | |
| "mode": args.mode, | |
| "train": _summarize(train_rows) if train_rows else {"count": 0}, | |
| "val": _summarize(val_rows) if val_rows else {"count": 0}, | |
| "tests": {k: len(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] Done:", json.dumps(stats, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |