"""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".*?", "", 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()