File size: 28,127 Bytes
ce6548c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Round-2 Dataset Builder: 2-Stage NLI-to-Groundedness Curriculum + Length-Matched
Multi-Passage Partial-Hallucination Composer + Minimal-Edit Counterfactuals.

Outputs:
  - stage1_nli.jsonl (~60K clean semantic NLI: Mixtral-NLI + WANLI + MultiNLI-OANC)
  - stage2_grounded.jsonl (~90K length-debiased multilingual groundedness with exact char spans
    & same-doc group_ids: Mixtral-NLI + WANLI + MultiNLI + MiniCheck + SummEdits(2x) + DocNLI(8K)
    + PsiloQA(14 langs, noise-fixed) + 10K Multi-Passage Composed Pairs + 5K Minimal-Edit CFs
    + 6K Same-Haystack Long-Context Pairs)
  - val.jsonl (~3,200 rows balanced across sources + composed multi-passage pairs)
  - FULL official 6 eval suites (100% IDENTICAL to groundedness_guard/data_builder.py!)
"""

from __future__ import annotations

import argparse
import json
import os
import random
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any

from data_builder_probe import (
    MNLI_PERMISSIVE_GENRES,
    _embed_in_rag_haystack,
    _extract_difflib_spans,
    _extract_ragtruth_context,
    _hash_bucket,
    _make_rec,
    _mutate_counterfactual,
    _norm_md5,
    _summarize,
    _write_jsonl,
)
from schema import COUNTERFACTUAL_ANCHORS, PSILOQA_LANGS


def _compose_multipassage_pairs(
    pos_items: list[dict[str, Any]],
    neg_by_gid: dict[str, list[dict[str, Any]]],
    target_pairs: int,
    rng: random.Random,
    eval_claim_hashes: set[str],
    eval_pair_hashes: set[str],
) -> list[dict[str, Any]]:
    """Build LENGTH-MATCHED multi-passage RAG contexts + 2-4 sentence responses where
    pos and neg share the EXACT SAME multi-passage premise (`group_id`) and differ in
    EXACTLY ONE hallucinated sentence (with exact char span `[b_start, b_end]`)."""
    # Filter to reasonably compact single/short claims so composed 3-passage docs stay <= 2,800 tok
    good_pos = [
        r for r in pos_items
        if 20 <= len(r["premise"]) <= 1800 and 18 <= len(r["hypothesis"]) <= 350
    ]
    with_neg = [r for r in good_pos if neg_by_gid.get(r["group_id"])]
    if len(good_pos) < 10 or len(with_neg) < 10:
        return []

    pos_by_lang: dict[str, list[dict[str, Any]]] = defaultdict(list)
    for r in good_pos:
        pos_by_lang[r["language"]].append(r)

    out: list[dict[str, Any]] = []
    seen_pairs: set[str] = set()
    attempts = 0
    max_attempts = target_pairs * 8

    while len(out) < target_pairs * 2 and attempts < max_attempts:
        attempts += 1
        k = rng.choice([2, 3, 3, 4])
        # Pick 1 anchor item that has a same-doc negative (or can be counterfactually mutated)
        anchor = rng.choice(with_neg)
        lang = anchor["language"]
        # Pick k-1 additional consistent items (preferring same language) in O(1)
        lang_pool = pos_by_lang[lang]
        pool = lang_pool if len(lang_pool) >= k + 2 else good_pos
        others = rng.sample(pool, k=min(k + 1, len(pool)))
        # Ensure distinct docs
        chosen = [anchor] + [o for o in others if o["group_id"] != anchor["group_id"]][: k - 1]
        if len(chosen) < 2:
            continue

        # Pick the bad sentence for anchor (prefer real same-doc neg with similar length!)
        cand_negs = [
            n for n in neg_by_gid[anchor["group_id"]]
            if 15 <= len(n["hypothesis"]) <= 420
            and abs(len(n["hypothesis"]) - len(anchor["hypothesis"])) <= max(120, int(0.9 * len(anchor["hypothesis"])))
        ]
        if cand_negs:
            bad_hyp = rng.choice(cand_negs)["hypothesis"]
        else:
            mut = _mutate_counterfactual(anchor["premise"], anchor["hypothesis"], rng)
            if mut is None:
                continue
            bad_hyp = mut[0]

        # Shuffle passage order independently from sentence order (real RAG behavior!)
        passages = [f"Passage {i + 1}:\n{c['premise']}" for i, c in enumerate(rng.sample(chosen, len(chosen)))]
        multi_prem = "\n\n".join(passages)
        mgid = _norm_md5(multi_prem)

        order = list(range(len(chosen)))
        rng.shuffle(order)
        pos_sents = [chosen[idx]["hypothesis"] for idx in order]
        neg_sents = []
        bad_idx_in_order = -1
        for pos_i, idx in enumerate(order):
            if idx == 0:
                neg_sents.append(bad_hyp)
                bad_idx_in_order = pos_i
            else:
                neg_sents.append(chosen[idx]["hypothesis"])

        pos_hyp = " ".join(pos_sents)
        neg_hyp = " ".join(neg_sents)

        # Exact char span of the single hallucinated sentence inside neg_hyp
        prefix = " ".join(neg_sents[:bad_idx_in_order])
        b_start = (len(prefix) + 1) if prefix else 0
        b_end = b_start + len(bad_hyp)
        if neg_hyp[b_start:b_end] != bad_hyp:
            continue

        hp = _norm_md5(multi_prem + " ||| " + pos_hyp)
        hn = _norm_md5(multi_prem + " ||| " + neg_hyp)
        if (
            hp in seen_pairs or hn in seen_pairs
            or _norm_md5(pos_hyp) in eval_claim_hashes or _norm_md5(neg_hyp) in eval_claim_hashes
            or hp in eval_pair_hashes or hn in eval_pair_hashes
        ):
            continue
        seen_pairs.add(hp)
        seen_pairs.add(hn)

        out.append(_make_rec(multi_prem, pos_hyp, 1, "multipassage_pos", lang, group_id=mgid, has_span=True))
        out.append(_make_rec(multi_prem, neg_hyp, 0, "multipassage_neg", lang, group_id=mgid, has_span=True, hal_spans=[[b_start, b_end]]))

    return out


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--out-dir", type=str, required=True)
    parser.add_argument("--seed", type=int, default=42)
    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)

    # ================= 1. BUILD FULL OFFICIAL 6 EVAL SUITES (100% IDENTICAL!) =================
    test_suites: dict[str, list[dict[str, Any]]] = {}
    eval_claim_hashes: set[str] = set()
    eval_pair_hashes: set[str] = set()

    # Eval 1: OOD RAGTruth_test
    rt_rows = []
    for sp_name in ("qa", "summarization", "data2txt"):
        for row in load_dataset("flowaicom/RAGTruth_test", split=sp_name):
            prem = _extract_ragtruth_context(row)
            resp = str(row.get("response") or "").strip()
            sc = row.get("score")
            if len(prem) < 15 or len(resp) < 5 or sc is None:
                continue
            rt_rows.append({"premise": prem, "hypothesis": resp, "label": 1 if int(sc) == 1 else 0, "source": f"ood_ragtruth_{sp_name}", "language": "en"})
            eval_claim_hashes.add(_norm_md5(resp))
            eval_pair_hashes.add(_norm_md5(prem + " ||| " + resp))
    random.Random(args.seed + 23).shuffle(rt_rows)
    test_suites["ood_ragtruth"] = rt_rows[:1500]

    # Eval 2: OOD SummEval
    se_rows = []
    for row in load_dataset("mteb/summeval", split="test"):
        txt = str(row.get("text") or "").strip()
        if len(txt) < 20:
            continue
        for s_t, c_v in zip(row.get("machine_summaries") or [], row.get("consistency") or []):
            s_clean = str(s_t or "").strip()
            if len(s_clean) < 10 or c_v is None:
                continue
            se_rows.append({"premise": txt, "hypothesis": s_clean, "label": 1 if float(c_v) >= 5.0 else 0, "source": "ood_summeval", "language": "en"})
            eval_claim_hashes.add(_norm_md5(s_clean))
            eval_pair_hashes.add(_norm_md5(txt + " ||| " + s_clean))
    random.Random(args.seed + 37).shuffle(se_rows)
    test_suites["ood_summeval"] = se_rows

    # Eval 3: OOD FRANK
    fr_rows = []
    for row in load_dataset("mtc/frank-test-set-with-faithfulness-annotation", split="test"):
        art = str(row.get("article") or "").strip()
        summ = str(row.get("summary") or "").strip()
        fac = row.get("Factual")
        if len(art) < 20 or len(summ) < 10 or fac is None:
            continue
        fr_rows.append({"premise": art, "hypothesis": summ, "label": 1 if bool(fac) else 0, "source": "ood_frank", "language": "en"})
        eval_claim_hashes.add(_norm_md5(summ))
        eval_pair_hashes.add(_norm_md5(art + " ||| " + summ))
    random.Random(args.seed + 53).shuffle(fr_rows)
    test_suites["ood_frank"] = fr_rows

    # Eval 4: OOD FinQA
    fin_rows = []
    for row in load_dataset("Cleanlab/FinQA-hallucination-detection", split="train"):
        ctx = str(row.get("context") or "").strip()
        q = str(row.get("query") or "").strip()
        resp = str(row.get("llm_response") or "").strip()
        ic = row.get("is_correct")
        if len(ctx) < 10 or not resp or ic is None:
            continue
        prem = f"{ctx}\n\nQuestion: {q}" if q else ctx
        fin_rows.append({"premise": prem, "hypothesis": resp, "label": 1 if int(ic) == 1 else 0, "source": "ood_finqa", "language": "en"})
        eval_claim_hashes.add(_norm_md5(resp))
        eval_pair_hashes.add(_norm_md5(prem + " ||| " + resp))
    random.Random(args.seed + 11).shuffle(fin_rows)
    test_suites["ood_finqa"] = fin_rows

    # Eval 5: PsiloQA test + LC 4-depth needle
    by_lg: dict[str, list[dict[str, Any]]] = defaultdict(list)
    lc_pos_seeds, lc_neg_seeds = [], []
    for row in load_dataset("s-nlp/PsiloQA", split="test"):
        ctx = str(row.get("wiki_passage") or "").strip()
        ans = str(row.get("llm_answer") or "").strip()
        lg = str(row.get("lang") or "en").strip().lower()
        spans = row.get("labels")
        if len(ctx) < 15 or len(ans) < 5 or spans is None:
            continue
        lbl = 1 if len(spans) == 0 else 0
        rec = {"premise": ctx, "hypothesis": ans, "label": lbl, "source": "psiloqa_test", "language": lg}
        by_lg[lg].append(rec)
        eval_claim_hashes.add(_norm_md5(ans))
        eval_pair_hashes.add(_norm_md5(ctx + " ||| " + ans))
        if lg == "en":
            if lbl == 1 and len(lc_pos_seeds) < 60:
                lc_pos_seeds.append((ctx, ans, 1))
            elif lbl == 0 and len(lc_neg_seeds) < 60:
                lc_neg_seeds.append((ctx, ans, 0))
    sampled_pq = []
    for lg, items in sorted(by_lg.items()):
        rlg = random.Random(args.seed + _hash_bucket(lg, 997))
        rlg.shuffle(items)
        sampled_pq.extend(items[:200])
    test_suites["psiloqa_test"] = sampled_pq

    if (len(lc_pos_seeds) < 60 or len(lc_neg_seeds) < 60) and test_suites.get("ood_ragtruth"):
        for r in test_suites["ood_ragtruth"]:
            if r["label"] == 1 and len(lc_pos_seeds) < 60 and len(r["premise"]) < 1500:
                lc_pos_seeds.append((r["premise"], r["hypothesis"], 1))
            elif r["label"] == 0 and len(lc_neg_seeds) < 60 and len(r["premise"]) < 1500:
                lc_neg_seeds.append((r["premise"], r["hypothesis"], 0))
    lc_rng = random.Random(args.seed + 79)
    lc_rows = []
    for d in (1000, 3200, 6400, 12800):
        for prem, hyp, lbl in lc_pos_seeds + lc_neg_seeds:
            lc_rows.append({
                "premise": _embed_in_rag_haystack(prem, d, lc_rng),
                "hypothesis": hyp,
                "label": lbl,
                "source": "lc_rag_needle",
                "language": "en",
                "approx_token_depth": d // 4,
            })
    test_suites["lc_rag_needle"] = lc_rows
    print("[data] Official eval suites built:", {k: len(v) for k, v in test_suites.items()})

    # ================= 2. LOAD PERMISSIVE TRAINING CORPORA =================
    stage1_rows: list[dict[str, Any]] = []
    stage2_rows: list[dict[str, Any]] = []
    val_rows: list[dict[str, Any]] = []

    # A. MoritzLaurer/synthetic_zeroshot_mixtral_v0.1 (Apache-2.0 — deep semantic NLI!)
    mix_nli_all: list[dict[str, Any]] = []
    for cfg_name, cap in [("mixtral_refinedweb_nli", 22000), ("mixtral_written_texts_for_tasks", 8000)]:
        try:
            ds_m = load_dataset("MoritzLaurer/synthetic_zeroshot_mixtral_v0.1", cfg_name, split="train", streaming=True)
            pos_c = neg_c = 0
            half = cap // 2
            for row in ds_m:
                p = str(row.get("text") or "").strip()
                h = str(row.get("hypothesis") or "").strip()
                raw_l = row.get("labels")
                if len(p) < 15 or len(h) < 8 or raw_l not in (0, 1):
                    continue
                if _norm_md5(h) in eval_claim_hashes or _norm_md5(p + " ||| " + h) in eval_pair_hashes:
                    continue
                # Mixtral NLI uses 0=entailment -> 1=consistent, 1=not_entailment -> 0=hallucinated!
                lbl = 1 if int(raw_l) == 0 else 0
                if lbl == 1 and pos_c >= half:
                    continue
                if lbl == 0 and neg_c >= half:
                    continue
                rec = _make_rec(p, h, lbl, f"mixtral_{cfg_name}", "en")
                if _hash_bucket(p) < 96:
                    mix_nli_all.append(rec)
                    if lbl == 1:
                        pos_c += 1
                    else:
                        neg_c += 1
                elif len(val_rows) < 400:
                    val_rows.append(rec)
                if pos_c >= half and neg_c >= half:
                    break
            print(f"[data] Mixtral {cfg_name}: pos={pos_c:,} neg={neg_c:,}")
        except Exception as e:
            print(f"[warn] Mixtral {cfg_name} skipped: {e}")

    rng.shuffle(mix_nli_all)
    stage1_rows.extend(mix_nli_all[:26000])
    stage2_rows.extend(mix_nli_all[:12000])

    # B. alisawuffles/WANLI (CC-BY-4.0 — adversarial semantic NLI!)
    wanli_all: list[dict[str, Any]] = []
    try:
        ds_w = list(load_dataset("alisawuffles/WANLI", split="train"))
        random.Random(args.seed + 101).shuffle(ds_w)
        w_pos, w_neg = [], []
        for row in ds_w:
            p = str(row.get("premise") or "").strip()
            h = str(row.get("hypothesis") or "").strip()
            g = str(row.get("gold") or "").strip().lower()
            if len(p) < 10 or len(h) < 5 or g not in ("entailment", "contradiction", "neutral"):
                continue
            if _norm_md5(h) in eval_claim_hashes:
                continue
            lbl = 1 if g == "entailment" else 0
            rec = _make_rec(p, h, lbl, "wanli", "en")
            if lbl == 1 and len(w_pos) < 10000:
                w_pos.append(rec)
            elif lbl == 0 and len(w_neg) < 10000:
                w_neg.append(rec)
            if len(w_pos) >= 10000 and len(w_neg) >= 10000:
                break
        wanli_all = w_pos + w_neg
        rng.shuffle(wanli_all)
        stage1_rows.extend(wanli_all[:18000])
        stage2_rows.extend(wanli_all[:10000])
        print(f"[data] WANLI: {len(wanli_all):,}")
    except Exception as e:
        print(f"[warn] WANLI skipped: {e}")

    # C. nyu-mll/multi_nli permissive OANC genres
    mnli_all: list[dict[str, Any]] = []
    try:
        m_pos, m_neg = [], []
        for row in load_dataset("nyu-mll/multi_nli", split="train", streaming=True):
            if len(m_pos) >= 8000 and len(m_neg) >= 8000:
                break
            if str(row.get("genre") or "").strip().lower() not in MNLI_PERMISSIVE_GENRES:
                continue
            p = str(row.get("premise") or "").strip()
            h = str(row.get("hypothesis") or "").strip()
            l_raw = row.get("label")
            if len(p) < 15 or len(h) < 5 or l_raw not in (0, 1, 2):
                continue
            if _norm_md5(h) in eval_claim_hashes:
                continue
            lbl = 1 if int(l_raw) == 0 else 0
            rec = _make_rec(p, h, lbl, "mnli_oanc", "en")
            if lbl == 1 and len(m_pos) < 8000:
                m_pos.append(rec)
            elif lbl == 0 and len(m_neg) < 8000:
                m_neg.append(rec)
        mnli_all = m_pos + m_neg
        rng.shuffle(mnli_all)
        stage1_rows.extend(mnli_all)
        stage2_rows.extend(mnli_all[:8000])
        print(f"[data] MultiNLI OANC: {len(mnli_all):,}")
    except Exception as e:
        print(f"[warn] MultiNLI skipped: {e}")

    # D. lytang/C2D-and-D2C-MiniCheck (MIT — ALL c2d + d2c!)
    mc_train: list[dict[str, Any]] = []
    for sp in ("c2d", "d2c"):
        ds_mc = list(load_dataset("lytang/C2D-and-D2C-MiniCheck", split=sp))
        random.Random(args.seed + _hash_bucket(sp, 997)).shuffle(ds_mc)
        for row in ds_mc:
            doc = str(row.get("doc") or "").strip()
            clm = str(row.get("claim") or "").strip()
            lbl = row.get("label")
            if len(doc) < 15 or len(clm) < 5 or lbl is None:
                continue
            if _norm_md5(clm) in eval_claim_hashes or _norm_md5(doc + " ||| " + clm) in eval_pair_hashes:
                continue
            li = 1 if int(lbl) == 1 else 0
            rec = _make_rec(doc, clm, li, f"minicheck_{sp}", "en")
            if _hash_bucket(doc) < 93:
                mc_train.append(rec)
            elif len(val_rows) < 1100:
                val_rows.append(rec)
    stage2_rows.extend(mc_train)
    print(f"[data] MiniCheck base: {len(mc_train):,}")

    # E. Salesforce/summedits (CC-BY-4.0 — multi-sentence minimal-edit LLM summaries + difflib exact spans!)
    se_train: list[dict[str, Any]] = []
    se_span_c = 0
    for row in load_dataset("Salesforce/summedits", split="train"):
        doc = str(row.get("doc") or "").strip()
        summ = str(row.get("summary") or "").strip()
        seed_s = str(row.get("seed_summary") or "").strip()
        lbl = row.get("label")
        if len(doc) < 25 or len(summ) < 12 or lbl is None:
            continue
        if _norm_md5(summ) in eval_claim_hashes or _norm_md5(doc + " ||| " + summ) in eval_pair_hashes:
            continue
        li = 1 if int(lbl) == 1 else 0
        has_sp, sp_list = (False, [])
        if li == 0 and seed_s:
            has_sp, sp_list = _extract_difflib_spans(seed_s, summ)
            if has_sp:
                se_span_c += 1
        rec = _make_rec(doc, summ, li, "summedits", "en", has_span=has_sp, hal_spans=sp_list)
        if _hash_bucket(doc) < 90:
            se_train.append(rec)
        else:
            val_rows.append(rec)
    # 2x weight SummEdits in Stage 2 (cleanest real multi-sentence LLM summary faithfulness!)
    stage2_rows.extend(se_train)
    stage2_rows.extend(se_train)
    print(f"[data] SummEdits: {len(se_train):,} unique (2x in stage2, exact diff spans={se_span_c:,})")

    # F. tasksource/doc-nli (TRIMMED to 8,000 clean rows so extractive shortcut doesn't poison SummEval!)
    dn_pos, dn_neg = [], []
    for sp_name, is_val in [("train", False), ("validation", True)]:
        v_cnt = 0
        for row in load_dataset("tasksource/doc-nli", split=sp_name, streaming=True):
            if not is_val and len(dn_pos) >= 4000 and len(dn_neg) >= 4000:
                break
            if is_val and v_cnt >= 500:
                break
            p = str(row.get("premise") or "").strip()
            h = str(row.get("hypothesis") or "").strip()
            l_s = str(row.get("label") or "").strip().lower()
            if len(p) < 25 or len(p) > 8000 or len(h) < 15 or len(h) > 2000 or l_s not in ("entailment", "not_entailment"):
                continue
            if _norm_md5(h) in eval_claim_hashes or _norm_md5(p + " ||| " + h) in eval_pair_hashes:
                continue
            lbl = 1 if l_s == "entailment" else 0
            rec = _make_rec(p, h, lbl, "docnli", "en")
            if is_val:
                val_rows.append(rec)
                v_cnt += 1
            else:
                if lbl == 1 and len(dn_pos) < 4000:
                    dn_pos.append(rec)
                elif lbl == 0 and len(dn_neg) < 4000:
                    dn_neg.append(rec)
    stage2_rows.extend(dn_pos + dn_neg)
    print(f"[data] DocNLI (trimmed): {len(dn_pos) + len(dn_neg):,}")

    # G. s-nlp/PsiloQA (14 languages, real llm_answer only + gold char spans + noise fix!)
    pq_train: list[dict[str, Any]] = []
    pq_dropped = 0
    for sp_name, tgt_list, per_l_cap in [("train", pq_train, 1500), ("validation", val_rows, 100)]:
        by_l_cls: dict[str, dict[int, list[dict[str, Any]]]] = defaultdict(lambda: {0: [], 1: []})
        for row in load_dataset("s-nlp/PsiloQA", split=sp_name):
            lg = str(row.get("lang") or "en").strip().lower()
            if lg not in PSILOQA_LANGS:
                continue
            ctx = str(row.get("wiki_passage") or "").strip()
            ans = str(row.get("llm_answer") or "").strip()
            spans = row.get("labels")
            ann = str(row.get("annotated_span") or "")
            if len(ctx) < 15 or len(ans) < 5 or spans is None:
                continue
            if _norm_md5(ans) in eval_claim_hashes or _norm_md5(ctx + " ||| " + ans) in eval_pair_hashes:
                continue
            if sp_name == "train" and len(spans) == 0 and "[HAL]" in ann:
                pq_dropped += 1
                continue
            lbl = 1 if len(spans) == 0 else 0
            clean_spans = []
            if lbl == 0:
                for pair in spans:
                    if isinstance(pair, (list, tuple)) and len(pair) == 2:
                        s0, e0 = int(pair[0]), int(pair[1])
                        if 0 <= s0 < e0 <= len(ans):
                            clean_spans.append([s0, e0])
            rec = _make_rec(ctx, ans, lbl, "psiloqa", lg, has_span=(lbl == 1 or bool(clean_spans)), hal_spans=clean_spans)
            by_l_cls[lg][lbl].append(rec)

        for lg, cls_map in sorted(by_l_cls.items()):
            rlg = random.Random(args.seed + _hash_bucket(lg + sp_name, 997))
            rlg.shuffle(cls_map[0])
            rlg.shuffle(cls_map[1])
            pos_items = cls_map[1][: per_l_cap // 2]
            n_neg = min(len(cls_map[0]), max(len(pos_items), int(len(pos_items) * 2.0)), per_l_cap - len(pos_items))
            if not pos_items:
                continue
            if sp_name == "train" and len(pos_items) < n_neg:
                extra = (pos_items * 2)[: n_neg - len(pos_items)]
                chosen = pos_items + extra + cls_map[0][:n_neg]
            else:
                chosen = pos_items + cls_map[0][:n_neg]
            tgt_list.extend(chosen)
    stage2_rows.extend(pq_train)
    print(f"[data] PsiloQA: {len(pq_train):,} (dropped noisy={pq_dropped})")

    # H. Synthetic Minimal-Edit Counterfactual Hard Negatives (5,000 exact-span same-doc pairs!)
    cf_pool = [
        r for r in stage2_rows
        if r["label"] == 1 and r["source"] in ("minicheck_c2d", "minicheck_d2c", "summedits", "psiloqa", "docnli", "mixtral_mixtral_refinedweb_nli")
    ]
    rng.shuffle(cf_pool)
    cf_rows: list[dict[str, Any]] = []
    for r in cf_pool:
        if len(cf_rows) >= 5000:
            break
        res = _mutate_counterfactual(r["premise"], r["hypothesis"], rng)
        if res is None:
            continue
        new_hyp, spans = res
        if _norm_md5(new_hyp) in eval_claim_hashes or _norm_md5(r["premise"] + " ||| " + new_hyp) in eval_pair_hashes:
            continue
        cf_rows.append(_make_rec(r["premise"], new_hyp, 0, "synth_minimal_cf", r["language"], group_id=r["group_id"], has_span=True, hal_spans=spans))
    stage2_rows.extend(cf_rows)
    print(f"[data] Synthetic Minimal-Edit CFs: {len(cf_rows):,}")

    # I. LENGTH-MATCHED Multi-Passage Partial-Hallucination Composer (5,000 pairs = 10,000 rows + 300 val pairs!)
    neg_by_gid: dict[str, list[dict[str, Any]]] = defaultdict(list)
    pos_for_comp: list[dict[str, Any]] = []
    for r in stage2_rows:
        if r["source"] in ("minicheck_c2d", "minicheck_d2c", "psiloqa", "mixtral_mixtral_refinedweb_nli", "wanli", "docnli"):
            if r["label"] == 1:
                pos_for_comp.append(r)
            else:
                neg_by_gid[r["group_id"]].append(r)
    mp_train = _compose_multipassage_pairs(pos_for_comp, neg_by_gid, target_pairs=5000, rng=rng, eval_claim_hashes=eval_claim_hashes, eval_pair_hashes=eval_pair_hashes)
    stage2_rows.extend(mp_train)
    print(f"[data] Length-Matched Multi-Passage Composed Pairs: {len(mp_train):,} ({len(mp_train)//2:,} pairs)")

    # Add small held-out multi-passage validation pairs from val_rows so val measures multi-sentence faithfulness!
    val_neg_by_gid: dict[str, list[dict[str, Any]]] = defaultdict(list)
    val_pos_comp = []
    for r in val_rows:
        if r["label"] == 1:
            val_pos_comp.append(r)
        else:
            val_neg_by_gid[r["group_id"]].append(r)
    mp_val = _compose_multipassage_pairs(val_pos_comp, val_neg_by_gid, target_pairs=250, rng=random.Random(args.seed + 911), eval_claim_hashes=eval_claim_hashes, eval_pair_hashes=eval_pair_hashes)
    val_rows.extend(mp_val)

    # J. Counterfactual anchors
    for _ in range(6):
        for prem, hyp, lbl in COUNTERFACTUAL_ANCHORS:
            stage2_rows.append(_make_rec(prem, hyp, lbl, "counterfactual_anchor", "en"))

    # K. Same-Haystack Paired Long-Context RAG Haystacks (6,000 rows)
    by_g_cls: dict[str, dict[int, list[dict[str, Any]]]] = defaultdict(lambda: {0: [], 1: []})
    for r in stage2_rows:
        if len(r["premise"]) <= 2200 and not r["source"].startswith("long_ctx"):
            by_g_cls[r["group_id"]][r["label"]].append(r)
    paired_gids = [g for g, m in by_g_cls.items() if m[1] and m[0]]
    rng.shuffle(paired_gids)
    buckets = [600, 1400, 3000, 6200, 11200]
    lc_train: list[dict[str, Any]] = []
    for i in range(3000):
        if not paired_gids:
            break
        d = max(350, buckets[i % len(buckets)] + rng.randint(-150, 250))
        g = paired_gids[i % len(paired_gids)]
        ex_p = rng.choice(by_g_cls[g][1])
        ex_n = rng.choice(by_g_cls[g][0])
        haystack = _embed_in_rag_haystack(ex_p["premise"], d, rng)
        hgid = _norm_md5(haystack)
        lc_train.append(_make_rec(haystack, ex_p["hypothesis"], 1, "long_ctx_pos", ex_p["language"], group_id=hgid, has_span=True))
        lc_train.append(_make_rec(haystack, ex_n["hypothesis"], 0, "long_ctx_neg", ex_n["language"], group_id=hgid, has_span=ex_n["has_span"], hal_spans=ex_n["hal_spans"]))
    stage2_rows.extend(lc_train)
    print(f"[data] Same-Haystack Paired Long-Context: {len(lc_train):,}")

    # ================= 3. STRICT DEDUP HYGIENE =================
    val_clean, vseen = [], set()
    for r in val_rows:
        ph = _norm_md5(r["premise"] + " ||| " + r["hypothesis"])
        if ph in eval_pair_hashes or ph in vseen:
            continue
        vseen.add(ph)
        val_clean.append(r)
    rng.shuffle(val_clean)
    val_rows = val_clean[:3500]
    val_pair_hashes = {_norm_md5(r["premise"] + " ||| " + r["hypothesis"]) for r in val_rows}
    blocked = eval_pair_hashes | val_pair_hashes

    def _clean_split(rows: list[dict[str, Any]], allow_dup_sources: set[str]) -> list[dict[str, Any]]:
        out, seen = [], set()
        for r in rows:
            ph = _norm_md5(r["premise"] + " ||| " + r["hypothesis"])
            if ph in blocked:
                continue
            if ph in seen and r["source"] not in allow_dup_sources:
                continue
            seen.add(ph)
            out.append(r)
        rng.shuffle(out)
        return out

    stage1_rows = _clean_split(stage1_rows, allow_dup_sources=set())
    stage2_rows = _clean_split(stage2_rows, allow_dup_sources={"psiloqa", "summedits"})

    _write_jsonl(out_dir / "stage1_nli.jsonl", stage1_rows)
    _write_jsonl(out_dir / "stage2_grounded.jsonl", stage2_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 = {
        "stage1": _summarize(stage1_rows),
        "stage2": _summarize(stage2_rows),
        "val": _summarize(val_rows),
        "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] R2 Build Complete:", json.dumps(stats, indent=2))


if __name__ == "__main__":
    main()