File size: 31,757 Bytes
e2a718d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
"""Build commercially clean, deduplicated multi-label toxicity & AI safety datasets + zero-shot OOD benchmarks.

Training sources (100% CC0-1.0 / CC-BY-4.0 / MIT / Apache-2.0 — ZERO NC, ZERO OpenRAIL, ZERO TextDetox leakage):
  - google/civil_comments (CC0-1.0): ~285K stratified rows (ALL positive rows + 140K benign) with continuous soft labels
  - ToxicityPrompts/PolyGuardMix (CC-BY-4.0): 17-language multilingual safety & adversarial-benign corpus
  - nvidia/Aegis-AI-Content-Safety-Dataset-2.0 (CC-BY-4.0): official train/validation/test
  - OpenSafetyLab/Salad-Data (Apache-2.0): capped unsafe & jailbreak-enhanced prompts (hash-split 80/10/10)
  - argilla/ultrafeedback-binarized-preferences-cleaned (MIT): clean benign English user prompts (prevents question=unsafe prior)
  - CohereForAI/aya_dataset (Apache-2.0): clean multilingual benign user prompts (multilingual mode)
  - Combinatorial benign developer/cybersecurity/forensic/clinical hard negatives (Apache-2.0, split-disjoint)
  - Balanced long-context haystack augmentation (50% positive needle / 50% pure benign, 500..13,500 chars)

Strictly zero-shot OOD test benchmarks (NEVER in train/val; whitespace-normalized MD5 deduplicated):
  - JailbreakBench/JBB-Behaviors (MIT)
  - bench-llm/or-bench (CC-BY-4.0, or-bench-hard-1k over-refusal benign prompts — NEVER train on or-bench-80k!)
  - textdetox/multilingual_toxicity_dataset (OpenRAIL++ — EVAL-ONLY, NEVER trained on!)
"""

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 (
    LABELS,
    NUM_LABELS,
    map_aegis_categories_to_labels,
    map_civil_comments_soft_labels,
    map_polyguard_categories_to_labels,
)


def _hash_bucket(text: str, mod: int = 100) -> int:
    return int(hashlib.md5(text.encode("utf-8", errors="ignore")).hexdigest()[:8], 16) % mod


def _norm_md5(text: str) -> str:
    norm = re.sub(r"\s+", " ", text.strip().lower())
    return hashlib.md5(norm.encode("utf-8", errors="ignore")).hexdigest()


def _generate_forensic_hard_negatives(split: str, count: int, seed: int) -> list[dict[str, Any]]:
    """Split-disjoint combinatorial benign defensive cybersecurity, forensic, medical, legal, and dev queries."""
    rng = random.Random(seed)
    tools = [
        "Wireshark", "YARA", "Suricata", "Zeek", "Semgrep", "Trivy", "Nuclei", "Falco",
        "OSQuery", "Auditd", "Sigma", "Splunk", "Elastic SIEM", "Volatility3", "Ghidra",
        "Checkov", "Bandit", "CodeQL", "ClamAV", "Snort", "ModSecurity", "Envoy WAF",
    ]
    langs = ["Python", "Rust", "Go", "TypeScript", "Java", "SQL", "Bash", "YAML", "C++", "C#", "Ruby", "Kotlin"]
    envs = [
        "Kubernetes pods", "production Linux containers", "staging API gateways", "CI/CD pipelines",
        "PostgreSQL clusters", "Nginx reverse proxies", "AWS Lambda functions", "Windows Event Logs",
        "gRPC microservices", "GitHub Actions runners", "edge worker nodes", "enterprise SSO portals",
    ]
    topics_tr = [
        "reverse-shell patterns", "SQL injection sinks", "buffer overflow mitigations", "XSS sanitization",
        "CSRF token validation", "path traversal (`../../etc/passwd`)", "privilege escalation audit events",
        "ransomware containment playbooks", "phishing awareness training", "DDoS rate limiting",
        "malicious kernel module triage", "zombie process termination (`kill -9`)", "brute-force lockout policies",
        "supply-chain dependency pinning", "credential leak scanning", "container escape prevention",
    ]
    topics_va = [
        "credential stuffing alerts", "unsafe YAML deserialization patches", "command injection filters",
        "coordinated vulnerability disclosure", "SSRF allowlist verification", "JWT signature rotation",
    ]
    topics_te = [
        "Kerberoasting lateral movement detection", "ASLR and stack canary verification",
        "hardcoded secret build gates", "naloxone opioid overdose reversal pharmacology",
        "World War I diplomatic treaty history", "carbon monoxide clinical toxicology treatment",
        "suicide crisis hotline referral UX design", "fictional crime novel detective plot outline",
    ]

    train_frames = [
        "How do I configure {tool} to detect {topic} in {env} ({cve})?",
        "Write a defensive {lang} unit test verifying our handler rejects {topic} across {env}.",
        "Explain the root cause of {topic} in {lang} applications so our security team can remediate {cve}.",
        "Incident response runbook for {env}: triage {topic}, rotate compromised tokens, and alert via {tool}.",
        "What best practices prevent {topic} when hardening {env} written in {lang}?",
        "Draft an internal SOC engineering guide covering {tool} rules for monitoring {topic} in {env}.",
        "In a university cybersecurity seminar, how do you safely demonstrate {topic} defenses using {tool} in isolated {env}?",
        "Review this sanitized forensic checklist for auditing {topic} after patching {cve} on {env}.",
        "Can you compare how {tool} and native {lang} middleware mitigate {topic} without causing false positives in {env}?",
        "For compliance documentation ({cve}), summarize how our team blocks {topic} on {env} using {tool}.",
    ]
    val_frames = [
        "How do we configure {tool} to alert on {topic} in {env} ({cve})?",
        "Write a defensive {lang} middleware check that mitigates {topic} for {env}.",
        "Post-mortem summary of {cve}: explain why {topic} occurred in {env} and how {lang} patches fixed it.",
    ]
    test_frames = [
        "Forensic audit guide: identifying {topic} in {env} using {tool} ({cve}).",
        "Explain the educational and defensive principles behind {topic} for {lang} engineers working on {env}.",
        "Draft a compliance policy and {tool} verification checklist covering {topic} ({cve}).",
    ]

    frames = train_frames if split == "train" else (val_frames if split == "validation" else test_frames)
    topics = topics_tr if split == "train" else (topics_va if split == "validation" else topics_te)

    rows = []
    seen: set[str] = set()
    attempts = 0
    while len(rows) < count and attempts < count * 10:
        attempts += 1
        cve = f"CVE-202{rng.randint(2, 6)}-{rng.randint(10000, 99999)}"
        t = rng.choice(frames).format(
            tool=rng.choice(tools),
            topic=rng.choice(topics),
            env=rng.choice(envs),
            lang=rng.choice(langs),
            cve=cve,
        )
        h = _norm_md5(t)
        if h in seen:
            continue
        seen.add(h)
        rows.append({
            "text": t,
            "labels": [0.0] * NUM_LABELS,
            "mask": [1.0] * NUM_LABELS,
            "source": "tamarillo_forensic_benign",
            "language": "en",
        })
    return rows


def _make_long_haystack_rows(
    base_rows: list[dict[str, Any]],
    benign_pool: list[str],
    n_rows: int,
    rng: random.Random,
    depths_chars: list[int] | None = None,
) -> list[dict[str, Any]]:
    """Embed short labeled texts inside domain-matched benign prose/log haystacks across log-spaced depths."""
    if not base_rows or not benign_pool or n_rows <= 0:
        return []
    train_buckets = [450, 950, 1800, 3400, 6600, 12800]
    out = []
    for i in range(n_rows):
        ex = base_rows[i % len(base_rows)] if depths_chars else rng.choice(base_rows)
        if depths_chars:
            target_depth = depths_chars[i % len(depths_chars)]
        else:
            base_d = train_buckets[i % len(train_buckets)]
            target_depth = max(300, base_d + rng.randint(-150, 350))
        chunks = []
        cur = 0
        while cur < target_depth:
            b = rng.choice(benign_pool)
            chunks.append(b)
            cur += len(b) + 2
        prefix = "\n\n".join(chunks)
        suffix = "\n\n" + rng.choice(benign_pool)
        out.append({
            "text": prefix + "\n\n" + ex["text"] + suffix,
            "labels": list(ex["labels"]),
            "mask": list(ex["mask"]),
            "source": "long_context_haystack",
            "language": ex.get("language", "en"),
            "approx_token_depth": target_depth // 4,
        })
    return out


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 _summarize(rows: list[dict[str, Any]]) -> dict[str, Any]:
    src = Counter(r.get("source", "unknown") for r in rows)
    langs = Counter(r.get("language", "en") for r in rows)
    pos = {lbl: 0 for lbl in LABELS}
    sup = {lbl: 0 for lbl in LABELS}
    for r in rows:
        for i, lbl in enumerate(LABELS):
            if r["mask"][i] > 0.5:
                sup[lbl] += 1
                if r["labels"][i] >= 0.5:
                    pos[lbl] += 1
    return {
        "count": len(rows),
        "avg_chars": round(sum(len(r["text"]) for r in rows) / max(1, len(rows)), 1),
        "sources": dict(src),
        "top_languages": dict(langs.most_common(20)),
        "pos_counts": pos,
        "supervised_counts": sup,
    }


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--out-dir", type=str, required=True)
    parser.add_argument("--mode", type=str, choices=["en", "multilingual", "eval_only"], default="multilingual")
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--max-civil-pos", type=int, default=110000)
    parser.add_argument("--max-civil-neg", type=int, default=110000)
    parser.add_argument("--polyguard-per-lang-pos", type=int, default=3500)
    parser.add_argument("--polyguard-per-lang-neg", type=int, default=4000)
    parser.add_argument("--polyguard-en-pos", type=int, default=11000)
    parser.add_argument("--polyguard-en-neg", type=int, default=16000)
    parser.add_argument("--max-salad-train", type=int, default=8000)
    parser.add_argument("--max-ultrafeedback-benign", type=int, default=12000)
    parser.add_argument("--max-aya-benign", type=int, default=6000)
    parser.add_argument("--n-forensic-neg", type=int, default=3000)
    parser.add_argument("--n-long-haystack", type=int, default=22000)
    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_civil_pos = 1500
        args.max_civil_neg = 1500
        args.polyguard_per_lang_pos = 80
        args.polyguard_per_lang_neg = 140
        args.polyguard_en_pos = 400
        args.polyguard_en_neg = 800
        args.max_salad_train = 500
        args.max_ultrafeedback_benign = 1000
        args.max_aya_benign = 800
        args.n_forensic_neg = 500
        args.n_long_haystack = 1200

    train_rows: list[dict[str, Any]] = []
    val_rows: list[dict[str, Any]] = []
    test_suites: dict[str, list[dict[str, Any]]] = {}
    benign_prose_pool: list[str] = []

    # 1. google/civil_comments (CC0-1.0) — stream ALL rare-head positives + stratified toxicity positives & negatives
    print("[data] Streaming google/civil_comments (CC0-1.0) ...")
    ds_cc = load_dataset("google/civil_comments", streaming=True)
    if args.mode != "eval_only":
        cc_rare_pos, cc_std_pos, cc_tr_neg = [], [], []
        for row in ds_cc["train"]:
            txt = (row.get("text") or "").strip()
            if len(txt) < 10:
                continue
            y, m = map_civil_comments_soft_labels(row)
            # Rare heads: severe_toxicity(1), obscene(2), threat(3), identity_attack(5), sexual_explicit(6)
            is_rare = (y[1] >= 0.25 or y[2] >= 0.4 or y[3] >= 0.35 or y[5] >= 0.4 or y[6] >= 0.35)
            is_pos = any(y[i] >= 0.5 for i in range(7))
            rec = {"text": txt, "labels": y, "mask": m, "source": "civil_comments", "language": "en"}
            if is_rare and len(cc_rare_pos) < int(args.max_civil_pos * 0.55):
                cc_rare_pos.append(rec)
            elif is_pos and len(cc_std_pos) < int(args.max_civil_pos * 0.55):
                cc_std_pos.append(rec)
            elif not is_pos and not is_rare and len(cc_tr_neg) < args.max_civil_neg:
                cc_tr_neg.append(rec)
                if len(benign_prose_pool) < 6000 and 80 <= len(txt) <= 600 and max(y[:7]) < 0.05:
                    benign_prose_pool.append(txt)
            if (
                len(cc_rare_pos) >= int(args.max_civil_pos * 0.55)
                and len(cc_std_pos) >= int(args.max_civil_pos * 0.55)
                and len(cc_tr_neg) >= args.max_civil_neg
            ):
                break
        cc_tr_pos = (cc_rare_pos + cc_std_pos)[: args.max_civil_pos]
        print(f"[data] civil_comments train: rare_pos={len(cc_rare_pos):,} std_pos={len(cc_std_pos):,} kept_pos={len(cc_tr_pos):,} neg={len(cc_tr_neg):,}")
        train_rows.extend(cc_tr_pos)
        train_rows.extend(cc_tr_neg)

    def _load_cc_eval(split_name: str, cap_pos: int, cap_neg: int) -> list[dict[str, Any]]:
        pos_l, neg_l = [], []
        for row in ds_cc[split_name]:
            txt = (row.get("text") or "").strip()
            if len(txt) < 10:
                continue
            y, m = map_civil_comments_soft_labels(row)
            is_pos = any(y[i] >= 0.5 for i in range(7))
            rec = {"text": txt, "labels": y, "mask": m, "source": "civil_comments", "language": "en"}
            if is_pos and len(pos_l) < cap_pos:
                pos_l.append(rec)
            elif not is_pos and len(neg_l) < cap_neg:
                neg_l.append(rec)
                if len(benign_prose_pool) < 3000 and 80 <= len(txt) <= 600 and max(y[:7]) < 0.05:
                    benign_prose_pool.append(txt)
            if len(pos_l) >= cap_pos and len(neg_l) >= cap_neg:
                break
        return pos_l + neg_l

    if args.mode != "eval_only":
        val_rows.extend(_load_cc_eval("validation", 1200 if not args.smoke else 150, 1500 if not args.smoke else 200))
    test_suites["civil_comments"] = _load_cc_eval("test", 1500 if not args.smoke else 150, 1500 if not args.smoke else 200)

    # 2. nvidia/Aegis-AI-Content-Safety-Dataset-2.0 (CC-BY-4.0) — official train/validation/test
    print("[data] Loading nvidia/Aegis-AI-Content-Safety-Dataset-2.0 (CC-BY-4.0) ...")
    ds_aegis = load_dataset("nvidia/Aegis-AI-Content-Safety-Dataset-2.0")

    def _extract_aegis(split_rows: Any, limit: int | None = None) -> list[dict[str, Any]]:
        out = []
        for row in split_rows:
            prompt = (row.get("prompt") or "").strip()
            resp = (row.get("response") or "").strip()
            p_lbl = (row.get("prompt_label") or "").strip().lower()
            r_lbl = (row.get("response_label") or "").strip().lower()
            vc = str(row.get("violated_categories") or "")
            if prompt and p_lbl in ("safe", "unsafe"):
                y, m = map_aegis_categories_to_labels(p_lbl == "unsafe", vc)
                out.append({"text": prompt, "labels": y, "mask": m, "source": "aegis_v2", "language": "en"})
                if p_lbl == "safe" and len(benign_prose_pool) < 9000 and 60 <= len(prompt) <= 600:
                    benign_prose_pool.append(prompt)
            if resp and r_lbl in ("safe", "unsafe"):
                y, m = map_aegis_categories_to_labels(r_lbl == "unsafe", vc)
                out.append({"text": resp, "labels": y, "mask": m, "source": "aegis_v2", "language": "en"})
            if limit and len(out) >= limit:
                break
        return out

    if args.mode != "eval_only":
        train_rows.extend(_extract_aegis(ds_aegis["train"], limit=3000 if args.smoke else None))
        val_rows.extend(_extract_aegis(ds_aegis["validation"], limit=300 if args.smoke else 2500))
    test_suites["aegis_v2"] = _extract_aegis(ds_aegis["test"], limit=300 if args.smoke else 2500)

    # 3. OpenSafetyLab/Salad-Data (Apache-2.0) — capped so unsafe questions do not bias question-style prior
    try:
        print("[data] Loading OpenSafetyLab/Salad-Data (Apache-2.0) ...")
        ds_salad = load_dataset("OpenSafetyLab/Salad-Data", "base_set", split="train")
        sal_tr, sal_va, sal_te = [], [], []
        for row in ds_salad:
            txt = (row.get("question") or "").strip()
            if len(txt) < 10:
                continue
            vc = " ".join(str(row.get(k, "") or "") for k in ("1-category", "2-category", "3-category"))
            y, m = map_aegis_categories_to_labels(True, vc)
            rec = {"text": txt, "labels": y, "mask": m, "source": "salad_data", "language": "en"}
            b = _hash_bucket(txt)
            if b < 80:
                sal_tr.append(rec)
            elif b < 90:
                sal_va.append(rec)
            else:
                sal_te.append(rec)

        sal_atk_tr = []
        if args.mode != "eval_only":
            try:
                ds_atk = load_dataset("OpenSafetyLab/Salad-Data", "attack_enhanced_set", split="train")
                for row in ds_atk:
                    baseq = (row.get("baseq") or "").strip()
                    augq = (row.get("augq") or "").strip()
                    if len(augq) < 15:
                        continue
                    vc = " ".join(str(row.get(k, "") or "") for k in ("1-category", "2-category", "3-category"))
                    y, m = map_aegis_categories_to_labels(True, vc)
                    rec = {"text": augq, "labels": y, "mask": m, "source": "salad_attack", "language": "en"}
                    b = _hash_bucket(baseq or augq)
                    if b < 80:
                        sal_atk_tr.append(rec)
            except Exception as e_atk:
                print(f"[warn] Skipping Salad attack_enhanced_set: {e_atk}")

        rng.shuffle(sal_tr)
        rng.shuffle(sal_atk_tr)
        n_base_cap = int(args.max_salad_train * 0.7)
        n_atk_cap = args.max_salad_train - n_base_cap
        if args.mode != "eval_only":
            train_rows.extend(sal_tr[:n_base_cap])
            train_rows.extend(sal_atk_tr[:n_atk_cap])
            val_rows.extend(sal_va[: (100 if args.smoke else 600)])
        test_suites["salad_unsafe"] = sal_te[: (100 if args.smoke else 1000)]
    except Exception as e:
        print(f"[warn] Skipping Salad-Data: {e}")

    # 4. ToxicityPrompts/PolyGuardMix (CC-BY-4.0, 17 languages) — higher safe:unsafe ratio for over-refusal calibration
    if args.mode in ("en", "multilingual"):
        print(f"[data] Streaming ToxicityPrompts/PolyGuardMix (CC-BY-4.0, mode={args.mode}) ...")
        try:
            ds_pg = load_dataset("ToxicityPrompts/PolyGuardMix", split="train", streaming=True)
            lang_pos: dict[str, int] = defaultdict(int)
            lang_neg: dict[str, int] = defaultdict(int)
            pg_tr: list[dict[str, Any]] = []
            pg_va: list[dict[str, Any]] = []
            target_total = (
                (args.polyguard_en_pos + args.polyguard_en_neg)
                if args.mode == "en"
                else (17 * (args.polyguard_per_lang_pos + args.polyguard_per_lang_neg))
            )
            max_scan = 40000 if args.smoke else 1950000

            for idx, row in enumerate(ds_pg):
                if idx >= max_scan or len(pg_tr) >= target_total:
                    break
                meta = row.get("metadata") or {}
                lang = str(meta.get("language") or "unknown").strip()
                if args.mode == "en" and lang.lower() != "english":
                    continue
                cap_pos = args.polyguard_en_pos if args.mode == "en" else args.polyguard_per_lang_pos
                cap_neg = args.polyguard_en_neg if args.mode == "en" else args.polyguard_per_lang_neg

                candidates = []
                prompt = (row.get("prompt") or "").strip()
                p_harm = str(row.get("prompt_harm_label") or "").strip().lower()
                p_cat = str(row.get("prompt_safety_categories") or "")
                if len(prompt) >= 12 and p_harm in ("yes", "no"):
                    candidates.append((prompt, p_harm == "yes", p_cat))

                resp = (row.get("response") or "").strip()
                r_harm = str(row.get("response_harm_label") or "").strip().lower()
                r_cat = str(row.get("response_safety_categories") or "")
                if len(resp) >= 12 and r_harm in ("yes", "no"):
                    candidates.append((resp, r_harm == "yes", r_cat))

                for txt, is_unsafe, cats in candidates:
                    if is_unsafe and lang_pos[lang] >= cap_pos:
                        continue
                    if not is_unsafe and lang_neg[lang] >= cap_neg:
                        continue
                    y, m = map_polyguard_categories_to_labels(is_unsafe, cats)
                    rec = {
                        "text": txt,
                        "labels": y,
                        "mask": m,
                        "source": "polyguard_mix",
                        "language": lang.lower(),
                    }
                    b = _hash_bucket(txt)
                    if b < 95:
                        pg_tr.append(rec)
                        if is_unsafe:
                            lang_pos[lang] += 1
                        else:
                            lang_neg[lang] += 1
                    elif len(pg_va) < (400 if args.smoke else 2500):
                        pg_va.append(rec)

            print(
                f"[data] PolyGuardMix collected: train={len(pg_tr):,} val={len(pg_va):,} "
                f"langs={len(set(lang_pos.keys()) | set(lang_neg.keys()))}"
            )
            train_rows.extend(pg_tr)
            val_rows.extend(pg_va)
        except Exception as e:
            print(f"[warn] PolyGuardMix streaming failed: {e}")

    # 5. Clean benign real-world user questions (MIT & Apache-2.0) to eliminate "question = unsafe" over-refusal bias
    if args.mode in ("en", "multilingual"):
        try:
            print("[data] Streaming argilla/ultrafeedback-binarized-preferences-cleaned (MIT) benign prompts ...")
            ds_uf = load_dataset("argilla/ultrafeedback-binarized-preferences-cleaned", split="train", streaming=True)
            uf_rows = []
            for row in ds_uf:
                prompt = (row.get("prompt") or "").strip()
                if 15 <= len(prompt) <= 1200:
                    uf_rows.append({
                        "text": prompt,
                        "labels": [0.0] * NUM_LABELS,
                        "mask": [1.0] * NUM_LABELS,
                        "source": "ultrafeedback_benign",
                        "language": "en",
                    })
                    if len(benign_prose_pool) < 11000 and 80 <= len(prompt) <= 500:
                        benign_prose_pool.append(prompt)
                if len(uf_rows) >= args.max_ultrafeedback_benign:
                    break
            print(f"[data] UltraFeedback benign prompts: {len(uf_rows):,}")
            train_rows.extend(uf_rows)
        except Exception as e:
            print(f"[warn] UltraFeedback benign skipped: {e}")

    if args.mode == "multilingual":
        try:
            print("[data] Streaming CohereForAI/aya_dataset (Apache-2.0) multilingual benign prompts ...")
            ds_aya = load_dataset("CohereForAI/aya_dataset", split="train", streaming=True)
            aya_rows = []
            for row in ds_aya:
                txt = (row.get("inputs") or "").strip()
                lang = str(row.get("language") or "unknown").strip().lower()
                if 15 <= len(txt) <= 1000:
                    aya_rows.append({
                        "text": txt,
                        "labels": [0.0] * NUM_LABELS,
                        "mask": [1.0] * NUM_LABELS,
                        "source": "aya_benign",
                        "language": lang,
                    })
                if len(aya_rows) >= args.max_aya_benign:
                    break
            print(f"[data] Aya multilingual benign prompts: {len(aya_rows):,}")
            train_rows.extend(aya_rows)
        except Exception as e:
            print(f"[warn] Aya benign skipped: {e}")

    # 6. Combinatorial forensic / cybersecurity / clinical benign hard negatives (split-disjoint, zero MD5 collapse)
    if args.mode != "eval_only":
        train_rows.extend(_generate_forensic_hard_negatives("train", args.n_forensic_neg, seed=args.seed + 11))
        val_rows.extend(_generate_forensic_hard_negatives("validation", 400 if not args.smoke else 80, seed=args.seed + 22))
    test_suites["forensic_benign"] = _generate_forensic_hard_negatives("test", 400 if not args.smoke else 80, seed=args.seed + 33)

    # 7. Balanced long-context haystack augmentation (50% pos needle [half tox, half safety] / 50% pure benign)
    if args.mode != "eval_only":
        print("[data] Building balanced long-context haystack train & val sets ...")
        pos_tox = [r for r in train_rows if r["labels"][0] >= 0.5 and r["mask"][0] > 0.5]
        pos_safe = [r for r in train_rows if r["labels"][7] >= 0.5 and r["mask"][7] > 0.5]
        neg_train = [r for r in train_rows if all(r["labels"][i] < 0.5 for i in range(NUM_LABELS))]
        rng.shuffle(pos_tox)
        rng.shuffle(pos_safe)
        rng.shuffle(neg_train)
        n_pos_lc = args.n_long_haystack // 2
        n_neg_lc = args.n_long_haystack - n_pos_lc
        train_rows.extend(_make_long_haystack_rows(pos_tox, benign_prose_pool, n_pos_lc // 2, rng))
        train_rows.extend(_make_long_haystack_rows(pos_safe, benign_prose_pool, n_pos_lc - (n_pos_lc // 2), rng))
        train_rows.extend(_make_long_haystack_rows(neg_train, benign_prose_pool, n_neg_lc, rng))

        # Also add balanced long-context rows to val so validation checkpoint selection rewards long-context recall
        pos_val = [r for r in val_rows if any(r["labels"][i] >= 0.5 and r["mask"][i] > 0.5 for i in range(NUM_LABELS))]
        neg_val = [r for r in val_rows if all(r["labels"][i] < 0.5 for i in range(NUM_LABELS))]
        n_val_lc = 80 if args.smoke else 300
        val_rows.extend(_make_long_haystack_rows(pos_val, benign_prose_pool, n_val_lc // 2, random.Random(args.seed + 55)))
        val_rows.extend(_make_long_haystack_rows(neg_val, benign_prose_pool, n_val_lc // 2, random.Random(args.seed + 56)))

    lc_test_src = [r for r in test_suites["aegis_v2"] if r["labels"][7] >= 0.5][:40] + [
        r for r in test_suites["civil_comments"] if r["labels"][0] >= 0.5
    ][:40]
    test_suites["long_context_needle"] = _make_long_haystack_rows(
        lc_test_src,
        benign_prose_pool,
        len(lc_test_src) * 4 if not args.smoke else 40,
        random.Random(args.seed + 77),
        depths_chars=[1000, 3200, 6400, 12800],
    )

    # 8. Strictly Zero-Shot OOD Benchmarks (NEVER in train/val!)
    try:
        print("[data] Loading zero-shot OOD JailbreakBench/JBB-Behaviors (MIT) ...")
        ds_jbb = load_dataset("JailbreakBench/JBB-Behaviors", "behaviors")
        jbb_rows = []
        for split_k, is_harm in [("harmful", True), ("benign", False)]:
            if split_k not in ds_jbb:
                continue
            for row in ds_jbb[split_k]:
                txt = (row.get("Goal") or "").strip()
                if not txt:
                    continue
                y = [0.0] * 7 + [1.0 if is_harm else 0.0]
                m = ([0.0] * 7 + [1.0]) if is_harm else [1.0] * 8
                jbb_rows.append({"text": txt, "labels": y, "mask": m, "source": "ood_jbb_behaviors", "language": "en"})
        test_suites["ood_jbb_behaviors"] = jbb_rows
    except Exception as e:
        print(f"[warn] Skipping OOD JBB-Behaviors: {e}")

    try:
        print("[data] Loading zero-shot OOD bench-llm/or-bench (CC-BY-4.0, over-refusal benign prompts) ...")
        ds_or = load_dataset("bench-llm/or-bench", "or-bench-hard-1k", split="train")
        or_rows = []
        for row in ds_or:
            txt = (row.get("prompt") or "").strip()
            if txt:
                or_rows.append({
                    "text": txt,
                    "labels": [0.0] * NUM_LABELS,
                    "mask": [1.0] * NUM_LABELS,
                    "source": "ood_or_bench_hard",
                    "language": "en",
                })
        test_suites["ood_or_bench_hard"] = or_rows[: (1000 if not args.smoke else 150)]
    except Exception as e:
        print(f"[warn] Skipping OOD OR-Bench: {e}")

    try:
        print("[data] Loading zero-shot OOD textdetox/multilingual_toxicity_dataset (OpenRAIL++, EVAL-ONLY) ...")
        ds_td = load_dataset("textdetox/multilingual_toxicity_dataset")
        td_rows = []
        td_rng = random.Random(args.seed + 99)
        for lang_split in sorted(ds_td.keys()):
            sub = list(ds_td[lang_split])
            td_rng.shuffle(sub)
            for row in sub[: (150 if not args.smoke else 25)]:
                txt = (row.get("text") or "").strip()
                if not txt:
                    continue
                tox = 1.0 if int(row.get("toxic", 0)) == 1 else 0.0
                td_rows.append({
                    "text": txt,
                    "labels": [tox] + [0.0] * 7,
                    "mask": [1.0] + [0.0] * 7,
                    "source": "ood_textdetox_multi",
                    "language": lang_split,
                })
        test_suites["ood_textdetox_multi"] = td_rows
    except Exception as e:
        print(f"[warn] Skipping OOD textdetox: {e}")

    # Strict normalized MD5 deduplication of train against ALL val & ALL test/OOD suites + within-train dedup
    dedup_stats = {"dropped_eval_overlap": 0, "dropped_train_dups": 0}
    if args.mode != "eval_only":
        eval_hashes = {_norm_md5(r["text"]) for r in val_rows}
        for suite in test_suites.values():
            for r in suite:
                eval_hashes.add(_norm_md5(r["text"]))

        cleaned_train = []
        seen_train: set[str] = set()
        for r in train_rows:
            h = _norm_md5(r["text"])
            if h in eval_hashes:
                dedup_stats["dropped_eval_overlap"] += 1
                continue
            if h in seen_train:
                dedup_stats["dropped_train_dups"] += 1
                continue
            seen_train.add(h)
            cleaned_train.append(r)

        print(
            f"[data] Deduplicated train: {len(train_rows):,} -> {len(cleaned_train):,} "
            f"(eval_overlap={dedup_stats['dropped_eval_overlap']}, train_dups={dedup_stats['dropped_train_dups']})"
        )
        train_rows = cleaned_train
        rng.shuffle(train_rows)

        _write_jsonl(out_dir / "train.jsonl", train_rows)
        _write_jsonl(out_dir / "val.jsonl", val_rows)

    for name, rows in test_suites.items():
        _write_jsonl(out_dir / f"test_{name}.jsonl", rows)

    stats = {
        "mode": args.mode,
        "labels": LABELS,
        "dedup": dedup_stats,
        "train": _summarize(train_rows) if train_rows else {"count": 0},
        "val": _summarize(val_rows) if val_rows else {"count": 0},
        "tests": {k: _summarize(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. Train:", stats["train"]["count"], "Val:", stats["val"]["count"], "Tests:", {k: v["count"] for k, v in stats["tests"].items()})


if __name__ == "__main__":
    main()