File size: 24,190 Bytes
e5f3768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Round-3 Dataset Builder (Informed by Round-2 Findings):
  - Drops noisy DocNLI extractive shortcut completely (0 rows).
  - Doubles Stage-1 Clean Semantic NLI foundation (~110K: Mixtral-NLI 44K + WANLI 36K + MultiNLI-OANC 30K)
    so the encoder develops full deep abstractive entailment before Stage 2!
  - Enriches Stage-2 (~105K-115K) with:
      * Higher multilingual PsiloQA coverage (up to 2,400/lang across 14 langs in multilingual mode; EN-only in en mode)
      * 14,000 Length-Matched Multi-Passage Composed Pairs (7,000 pos + 7,000 same-premise neg with exact bad-sentence spans!)
      * 6,000 Enhanced Synthetic Minimal-Edit Counterfactuals (years, numbers, percentages, scale/unit/month/day swaps,
        same-premise entity swaps, polarity flips — exact char spans + same-doc group_id!)
      * Full SummEdits (exact difflib spans, 1.5x weight to avoid Epoch-2 overfitting)
      * Full MiniCheck (c2d + d2c)
      * 30K Stage-1 NLI Replay (prevents catastrophic forgetting of deep semantic entailment!)
      * 8,000 Same-Haystack Paired Long-Context RAG examples (250 -> 3,584 tok!)
  - Identical FULL official 6 evaluation suites (100% comparable across all runs & 5 public baselines!).
"""

from __future__ import annotations

import argparse
import json
import os
import random
import re
from collections import 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 data_builder_r2 import _compose_multipassage_pairs
from schema import COUNTERFACTUAL_ANCHORS, PSILOQA_LANGS

UNIT_AND_CAL_SWAPS: list[tuple[str, str]] = [
    ("million", "billion"),
    ("billion", "million"),
    ("thousand", "million"),
    ("January", "March"),
    ("February", "April"),
    ("March", "June"),
    ("April", "July"),
    ("May", "August"),
    ("June", "September"),
    ("July", "October"),
    ("August", "November"),
    ("September", "December"),
    ("October", "January"),
    ("November", "February"),
    ("December", "May"),
    ("Monday", "Thursday"),
    ("Tuesday", "Friday"),
    ("Wednesday", "Saturday"),
    ("Thursday", "Monday"),
    ("Friday", "Tuesday"),
    ("north", "south"),
    ("south", "north"),
    ("east", "west"),
    ("west", "east"),
]


def _mutate_counterfactual_v2(premise: str, hyp: str, rng: random.Random) -> tuple[str, list[list[int]]] | None:
    """Enhanced minimal-edit counterfactual mutator adding scale/unit/month/day/direction swaps."""
    if rng.random() < 0.30:
        swaps = list(UNIT_AND_CAL_SWAPS)
        rng.shuffle(swaps)
        for src, tgt in swaps:
            m = re.search(rf"\b{re.escape(src)}\b", hyp)
            if m and tgt.lower() not in premise.lower():
                new_hyp = hyp[: m.start()] + tgt + hyp[m.end() :]
                return new_hyp, [[m.start(), m.start() + len(tgt)]]
    return _mutate_counterfactual(premise, hyp, rng)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--out-dir", type=str, required=True)
    parser.add_argument("--mode", choices=["en", "multilingual"], default="multilingual")
    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()

    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]

    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

    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

    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

    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

    # ================= 2. STAGE-1 DEEP SEMANTIC NLI (~110K) + STAGE-2 GROUNDEDNESS (~110K) =================
    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 — 44K!)
    mix_all: list[dict[str, Any]] = []
    for cfg_name, cap in [
        ("mixtral_refinedweb_nli", 30000),
        ("mixtral_written_texts_for_tasks", 10000),
        ("mixtral_refinedweb_characteristics", 6000),
    ]:
        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
                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_all.append(rec)
                    if lbl == 1:
                        pos_c += 1
                    else:
                        neg_c += 1
                elif len(val_rows) < 450:
                    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_all)
    stage1_rows.extend(mix_all)
    stage2_rows.extend(mix_all[:14000])

    # B. alisawuffles/WANLI (CC-BY-4.0 — 36K!)
    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) < 18000:
                w_pos.append(rec)
            elif lbl == 0 and len(w_neg) < 18000:
                w_neg.append(rec)
            if len(w_pos) >= 18000 and len(w_neg) >= 18000:
                break
        wanli_all = w_pos + w_neg
        rng.shuffle(wanli_all)
        stage1_rows.extend(wanli_all)
        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 (30K!)
    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) >= 15000 and len(m_neg) >= 15000:
                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) < 15000:
                m_pos.append(rec)
            elif lbl == 0 and len(m_neg) < 15000:
                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) < 1200:
                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)
    stage2_rows.extend(se_train)
    # 1.5x SummEdits (gentler than 2x to prevent Epoch-2 overfitting)
    stage2_rows.extend(rng.sample(se_train, k=len(se_train) // 2))
    print(f"[data] SummEdits: {len(se_train):,} unique (1.5x in stage2, exact diff spans={se_span_c:,})")

    # F. s-nlp/PsiloQA (up to 2,400/lang in multilingual mode; EN-only in en mode + noise fix!)
    pq_train: list[dict[str, Any]] = []
    pq_dropped = 0
    per_l_tr = 3500 if args.mode == "en" else 2400
    for sp_name, tgt_list, per_l_cap in [("train", pq_train, per_l_tr), ("validation", val_rows, 140)]:
        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 args.mode == "en" and lg != "en":
                continue
            if args.mode == "multilingual" and 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 ({args.mode}): {len(pq_train):,} (dropped noisy={pq_dropped})")

    # G. Enhanced Synthetic Minimal-Edit Counterfactual Hard Negatives (6,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", "mixtral_mixtral_refinedweb_nli")
    ]
    rng.shuffle(cf_pool)
    cf_rows: list[dict[str, Any]] = []
    for r in cf_pool:
        if len(cf_rows) >= 6000:
            break
        res = _mutate_counterfactual_v2(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] Enhanced Synthetic Minimal-Edit CFs: {len(cf_rows):,}")

    # H. LENGTH-MATCHED Multi-Passage Partial-Hallucination Composer (7,000 pairs = 14,000 rows!)
    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"):
            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=7000, 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)")

    val_neg_by_gid: dict[str, list[dict[str, Any]]] = defaultdict(list)
    val_pos_comp = [r for r in val_rows if r["label"] == 1]
    for r in val_rows:
        if r["label"] == 0:
            val_neg_by_gid[r["group_id"]].append(r)
    mp_val = _compose_multipassage_pairs(val_pos_comp, val_neg_by_gid, target_pairs=300, rng=random.Random(args.seed + 911), eval_claim_hashes=eval_claim_hashes, eval_pair_hashes=eval_pair_hashes)
    val_rows.extend(mp_val)

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

    # J. Same-Haystack Paired Long-Context RAG Haystacks (8,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(4000):
        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 = {
        "mode": args.mode,
        "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] R3 Build Complete:", json.dumps(stats, indent=2))


if __name__ == "__main__":
    main()