File size: 27,094 Bytes
c02657c
 
 
 
 
 
 
 
 
fb6c876
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6c876
 
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6c876
 
 
 
 
 
 
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6c876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6c876
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6c876
 
c02657c
 
 
 
 
 
 
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
"""Build OPUS-5.5-DATABASE from the raw upstream files.

Usage:
    OPUSDB_RAW=raw OPUSDB_OUT=out python scripts/build.py [--stages sft,preference,synth_eval,pretrain]

Outputs (Hugging Face `datasets`-compatible Parquet):
    out/data/sft/{train,test}-*.parquet
    out/data/preference/{train,test}-*.parquet
    out/data/synth_eval/test-*.parquet
    out/data/tools/{train,test}-*.parquet
    out/data/pretrain/train-*.parquet
    out/stats/*.json  (filter funnels, token counts; used by scripts/charts.py)
"""
import argparse
import gzip
import json
import multiprocessing as mp
import os
import random
import sys
import time
from collections import Counter, defaultdict

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

import pyarrow as pa  # noqa: E402
import pyarrow.parquet as pq  # noqa: E402

from opusdb import synth, synth_tools  # noqa: E402
from opusdb import tool_formats as tf  # noqa: E402
from opusdb.decontam import Decontaminator  # noqa: E402
from opusdb.dedup import ExactDeduper, MinHashLSH  # noqa: E402
from opusdb.sources import SOURCES  # noqa: E402
from opusdb.text import gopher_quality, guess_language, key, scrub_pii, stable_id  # noqa: E402

RAW = os.environ.get("OPUSDB_RAW", "raw")
OUT = os.environ.get("OPUSDB_OUT", "out")
TOKENIZER = "HuggingFaceTB/SmolLM2-135M"  # Apache-2.0, 49k vocab; used only for counting tokens
SEED = 55
SRC = {s.name: s for s in SOURCES}


def raw(source_name, idx=0):
    s = SRC[source_name]
    return os.path.join(RAW, s.repo.replace("/", "__"), s.files[idx])


def log(*a):
    print(time.strftime("%H:%M:%S"), *a, flush=True)


# --------------------------------------------------------------------------- tokenizer

_TOK = None


def tok():
    global _TOK
    if _TOK is None:
        from tokenizers import Tokenizer
        _TOK = Tokenizer.from_pretrained(TOKENIZER)
    return _TOK


def count_tokens(texts):
    return [len(e.ids) for e in tok().encode_batch(texts, add_special_tokens=False)]


# --------------------------------------------------------------------------- writer

MSG = pa.list_(pa.struct([("role", pa.string()), ("content", pa.string())]))
SCHEMAS = {
    "sft": pa.schema([("id", pa.string()), ("messages", MSG), ("source", pa.string()), ("domain", pa.string()),
                      ("language", pa.string()), ("license", pa.string()), ("num_turns", pa.int32()),
                      ("num_tokens", pa.int32())]),
    "preference": pa.schema([("id", pa.string()), ("prompt", pa.string()), ("chosen", MSG), ("rejected", MSG),
                             ("source", pa.string()), ("domain", pa.string()), ("language", pa.string()),
                             ("license", pa.string()), ("score_chosen", pa.float32()),
                             ("score_rejected", pa.float32()), ("num_tokens", pa.int32())]),
    "pretrain": pa.schema([("id", pa.string()), ("text", pa.string()), ("source", pa.string()),
                           ("domain", pa.string()), ("language", pa.string()), ("license", pa.string()),
                           ("url", pa.string()), ("num_tokens", pa.int32())]),
    "tools": pa.schema([("id", pa.string()),
                        ("messages", pa.list_(pa.struct([("role", pa.string()), ("content", pa.string()),
                                                         ("tool_calls", pa.string()), ("tool_call_id", pa.string()),
                                                         ("name", pa.string())]))),
                        ("tools", pa.string()), ("source", pa.string()), ("domain", pa.string()),
                        ("language", pa.string()), ("license", pa.string()), ("num_tool_calls", pa.int32()),
                        ("num_tokens", pa.int32())]),
    "synth_eval": pa.schema([("id", pa.string()), ("family", pa.string()), ("language", pa.string()),
                             ("difficulty", pa.int32()), ("prompt", pa.string()), ("answer", pa.string()),
                             ("reference_response", pa.string())]),
}


def write_split(config, split, rows, rows_per_shard):
    d = os.path.join(OUT, "data", config)
    os.makedirs(d, exist_ok=True)
    n = max(1, -(-len(rows) // rows_per_shard))
    for i in range(n):
        part = rows[i * rows_per_shard:(i + 1) * rows_per_shard]
        table = pa.Table.from_pylist(part, schema=SCHEMAS[config])
        pq.write_table(table, os.path.join(d, f"{split}-{i:05d}-of-{n:05d}.parquet"), compression="zstd",
                       row_group_size=10_000)
    log(f"wrote {config}/{split}: {len(rows):,} rows in {n} shard(s)")


def save_stats(name, obj):
    os.makedirs(os.path.join(OUT, "stats"), exist_ok=True)
    with open(os.path.join(OUT, "stats", name + ".json"), "w") as f:
        json.dump(obj, f, indent=2, ensure_ascii=False)


# --------------------------------------------------------------------------- benchmarks

def build_decontaminator():
    d = Decontaminator()
    for row in pq.read_table(raw("gsm8k-test")).to_pylist():
        d.add(row["question"])
    with open(raw("math500")) as f:
        for line in f:
            d.add(json.loads(line)["problem"])
    for row in pq.read_table(raw("humaneval")).to_pylist():
        d.add(row["prompt"])
    for row in pq.read_table(raw("mmlu"), columns=["question"]).to_pylist():
        d.add(row["question"])
    d.finalize()
    log(f"decontamination index: {len(d):,} benchmark n-grams")
    return d


# --------------------------------------------------------------------------- SFT readers

def m(role, content):
    return {"role": role, "content": content}


def read_smoltalk(name):
    s = SRC[name]
    for f in s.files:
        cols = pq.ParquetFile(os.path.join(RAW, s.repo.replace("/", "__"), f)).schema_arrow.names
        t = pq.read_table(os.path.join(RAW, s.repo.replace("/", "__"), f))
        for row in t.to_pylist():
            if "quality" in cols and row.get("quality") not in ("good", "excellent"):
                yield None, "low_quality_label"
                continue
            yield [m(x["role"], x["content"]) for x in row["messages"]], None


def read_oasst2():
    with gzip.open(raw("oasst2"), "rt") as f:
        for line in f:
            tree = json.loads(line)
            node, path = tree["prompt"], []
            while node is not None:
                path.append(m("user" if node["role"] == "prompter" else "assistant", node["text"]))
                replies = [r for r in node.get("replies", []) if not r.get("deleted")]
                if not replies:
                    break
                node = min(replies, key=lambda r: (r.get("rank") is None, r.get("rank") or 0))
            if path and path[-1]["role"] == "user":
                path = path[:-1]
            if len(path) < 2:
                yield None, "incomplete_tree"
                continue
            yield path, tree["prompt"].get("lang")


def read_metamath():
    with open(raw("metamathqa")) as f:
        data = json.load(f)
    for row in data:
        yield [m("user", row["query"]), m("assistant", row["response"])], None


def read_omi2():
    for row in pq.read_table(raw("openmathinstruct2"), columns=["problem", "generated_solution"]).to_pylist():
        yield [m("user", row["problem"]), m("assistant", row["generated_solution"])], None


def read_gsm8k():
    for row in pq.read_table(raw("gsm8k")).to_pylist():
        reasoning, ans = row["answer"].split("####")
        import re
        reasoning = re.sub(r"<<[^>]*>>", "", reasoning).strip()
        yield [m("user", row["question"]), m("assistant", f"{reasoning}\n\n**Answer:** {ans.strip()}")], None


def read_magicoder():
    with open(raw("magicoder-oss")) as f:
        for line in f:
            row = json.loads(line)
            yield [m("user", row["problem"]), m("assistant", row["solution"])], None


def read_codealpaca():
    with open(raw("codealpaca")) as f:
        for row in json.load(f):
            q = row["instruction"] + (f"\n\n{row['input']}" if row["input"].strip() else "")
            yield [m("user", q), m("assistant", row["output"])], None


SFT_READERS = {
    "smol-magpie-ultra": lambda: read_smoltalk("smol-magpie-ultra"),
    "smol-constraints": lambda: read_smoltalk("smol-constraints"),
    "smol-rewrite": lambda: read_smoltalk("smol-rewrite"),
    "smol-summarize": lambda: read_smoltalk("smol-summarize"),
    "oasst2": read_oasst2,
    "metamathqa": read_metamath,
    "openmathinstruct2": read_omi2,
    "gsm8k": read_gsm8k,
    "magicoder-oss": read_magicoder,
    "codealpaca": read_codealpaca,
}


def valid_conversation(msgs):
    roles = [x["role"] for x in msgs]
    body = [r for r in roles if r != "system"]
    if not body or body[0] != "user" or body[-1] != "assistant":
        return "bad_roles"
    if any(a == b for a, b in zip(body, body[1:])):
        return "bad_roles"
    if any(not x["content"] or not x["content"].strip() for x in msgs):
        return "empty_turn"
    last = msgs[-1]["content"]
    if len(last) < 2:
        return "empty_turn"
    low = last.lower()
    if any(p in low for p in ("as an ai language model", "i'm sorry, but i cannot", "openai", "chatgpt")):
        return "boilerplate_or_identity"
    return None


def build_sft(decon, synth_train):
    rng = random.Random(SEED)
    exact, near = ExactDeduper(), MinHashLSH()
    funnel, rows = {}, []
    for name, reader in SFT_READERS.items():
        s = SRC[name]
        c = Counter()
        kept = []
        for msgs, info in reader():
            c["read"] += 1
            if msgs is None:
                c[info] += 1
                continue
            reason = valid_conversation(msgs)
            if reason:
                c[reason] += 1
                continue
            first_user = next(x["content"] for x in msgs if x["role"] == "user")
            if decon.contaminated(first_user):
                c["benchmark_contaminated"] += 1
                continue
            kept.append((msgs, info, first_user))
        rng.shuffle(kept)  # random subsample when a cap applies
        for msgs, info, first_user in kept:
            if s.max_rows and c["kept"] >= s.max_rows:
                c["over_cap"] += 1
                continue
            if exact.is_dup(first_user):
                c["exact_duplicate"] += 1
                continue
            if near.is_dup(first_user):
                c["near_duplicate"] += 1
                continue
            msgs = [m(x["role"], scrub_pii(x["content"])) for x in msgs]
            lang = info if name == "oasst2" and info else guess_language(first_user)
            rows.append({"id": f"{name}-" + stable_id(name, json.dumps(msgs, ensure_ascii=False)), "messages": msgs,
                         "source": name, "domain": s.domain, "language": lang, "license": s.license,
                         "num_turns": sum(x["role"] == "user" for x in msgs)})
            c["kept"] += 1
        funnel[name] = dict(c)
        log(f"sft {name}: {dict(c)}")
    # OPUS-synth (original, verified)
    c = Counter()
    for ex in synth_train:
        c["read"] += 1
        if exact.is_dup(ex["prompt"]):
            c["exact_duplicate"] += 1
            continue
        msgs = [m("user", ex["prompt"]), m("assistant", ex["response"])]
        rows.append({"id": ex["id"], "messages": msgs, "source": "opus-synth",
                     "domain": "synthetic-" + ex["family"].split("/")[0], "language": ex["language"],
                     "license": "apache-2.0", "num_turns": 1})
        c["kept"] += 1
    funnel["opus-synth"] = dict(c)
    log(f"sft opus-synth: {dict(c)}")
    # token counts (full conversation, content only)
    B = 2000
    for i in range(0, len(rows), B):
        batch = rows[i:i + B]
        counts = count_tokens(["\n".join(x["content"] for x in r["messages"]) for r in batch])
        for r, n in zip(batch, counts):
            r["num_tokens"] = n
    before = len(rows)
    rows = [r for r in rows if r["num_tokens"] <= 8192]
    funnel["_too_long_removed"] = before - len(rows)
    rng.shuffle(rows)
    test, train = rows[:2000], rows[2000:]
    write_split("sft", "train", train, 100_000)
    write_split("sft", "test", test, 100_000)
    save_stats("sft_funnel", funnel)
    by = defaultdict(lambda: Counter())
    for r in train:
        b = by[r["source"]]
        b["rows"] += 1
        b["tokens"] += r["num_tokens"]
        b["lang_" + r["language"]] += 1
    save_stats("sft_sources", {k: dict(v) for k, v in by.items()})
    save_stats("sft_lengths", {"num_tokens": [r["num_tokens"] for r in train],
                               "source": [r["source"] for r in train]})
    return len(train)


# --------------------------------------------------------------------------- preference

def build_preference(decon, synth_pairs):
    rng = random.Random(SEED + 1)
    exact = ExactDeduper()
    rows, funnel = [], {}
    c = Counter()
    for row in pq.read_table(raw("ultrafeedback")).to_pylist():
        c["read"] += 1
        if row["score_chosen"] <= row["score_rejected"]:
            c["no_margin"] += 1
            continue
        if row["chosen"][-1]["content"].strip() == row["rejected"][-1]["content"].strip():
            c["identical"] += 1
            continue
        if decon.contaminated(row["prompt"]):
            c["benchmark_contaminated"] += 1
            continue
        if exact.is_dup(row["prompt"]):
            c["exact_duplicate"] += 1
            continue
        rows.append({"id": "ultrafeedback-" + row["prompt_id"][:24], "prompt": row["prompt"],
                     "chosen": [m(x["role"], x["content"]) for x in row["chosen"]],
                     "rejected": [m(x["role"], x["content"]) for x in row["rejected"]],
                     "source": "ultrafeedback", "domain": "general", "language": guess_language(row["prompt"]),
                     "license": "mit", "score_chosen": row["score_chosen"], "score_rejected": row["score_rejected"]})
        c["kept"] += 1
    funnel["ultrafeedback"] = dict(c)
    c = Counter()
    for row in pq.read_table(raw("orca-dpo")).to_pylist():
        c["read"] += 1
        if row["status"] == "tie" or (row["chosen_score"] or 0) < 8 or row["in_gsm8k_train"]:
            c["argilla_recipe_filter"] += 1
            continue
        if decon.contaminated(row["input"]):
            c["benchmark_contaminated"] += 1
            continue
        if exact.is_dup(row["input"]):
            c["exact_duplicate"] += 1
            continue
        sys_msg = [m("system", row["system"])] if row["system"] and row["system"].strip() else []
        user = [m("user", row["input"])]
        rows.append({"id": "orca-dpo-" + stable_id(row["input"]), "prompt": row["input"],
                     "chosen": sys_msg + user + [m("assistant", row["chosen"])],
                     "rejected": sys_msg + user + [m("assistant", row["rejected"])],
                     "source": "orca-dpo", "domain": "general", "language": "en", "license": "apache-2.0",
                     "score_chosen": float(row["chosen_score"]), "score_rejected": None})
        c["kept"] += 1
    funnel["orca-dpo"] = dict(c)
    c = Counter()
    for ex, bad in synth_pairs:
        c["read"] += 1
        rows.append({"id": ex["id"] + "-pref", "prompt": ex["prompt"],
                     "chosen": [m("user", ex["prompt"]), m("assistant", ex["response"])],
                     "rejected": [m("user", ex["prompt"]), m("assistant", bad)],
                     "source": "opus-synth-pref", "domain": "synthetic-" + ex["family"].split("/")[0],
                     "language": ex["language"], "license": "apache-2.0", "score_chosen": 1.0, "score_rejected": 0.0})
        c["kept"] += 1
    funnel["opus-synth-pref"] = dict(c)
    log("preference funnel", funnel)
    B = 2000
    for i in range(0, len(rows), B):
        batch = rows[i:i + B]
        counts = count_tokens([r["prompt"] + "\n" + r["chosen"][-1]["content"] + "\n" + r["rejected"][-1]["content"]
                               for r in batch])
        for r, n in zip(batch, counts):
            r["num_tokens"] = n
    rng.shuffle(rows)
    test, train = rows[:1000], rows[1000:]
    write_split("preference", "train", train, 50_000)
    write_split("preference", "test", test, 50_000)
    by = defaultdict(Counter)
    for r in train:
        by[r["source"]]["rows"] += 1
        by[r["source"]]["tokens"] += r["num_tokens"]
    save_stats("preference_funnel", funnel)
    save_stats("preference_sources", {k: dict(v) for k, v in by.items()})
    return len(train)


# --------------------------------------------------------------------------- tool use

def build_tools(decon, n_synth=30_000, n_test=1_000):
    rng = random.Random(SEED + 2)
    exact, near = ExactDeduper(), MinHashLSH()
    funnel, train, test = {}, [], []

    def row(src, msgs, tools, lang, license_, domain):
        enc = tf.encode_messages(msgs)
        return {"id": f"{src}-" + stable_id(src, json.dumps(enc, ensure_ascii=False)), "messages": enc,
                "tools": json.dumps(tools, ensure_ascii=False), "source": src, "domain": domain, "language": lang,
                "license": license_, "num_tool_calls": sum(len(m.get("tool_calls") or []) for m in msgs)}

    # verified synthetic: held-out test first (own seed), then train with disjoint prompts
    c = Counter()
    test_prompts = set()
    for ex in synth_tools.generate(n_test, seed=9002):
        test_prompts.add(ex["messages"][0]["content"])
        r = row("opus-synth-tools", ex["messages"], ex["tools"], ex["language"], "apache-2.0", "tools-" + ex["family"])
        r["id"] = ex["id"]
        test.append(r)
    for ex in synth_tools.generate(n_synth + 3000, seed=3):
        c["read"] += 1
        p = ex["messages"][0]["content"]
        if p in test_prompts or exact.is_dup(p):
            c["exact_duplicate"] += 1
            continue
        if c["kept"] >= n_synth:
            c["over_cap"] += 1
            continue
        r = row("opus-synth-tools", ex["messages"], ex["tools"], ex["language"], "apache-2.0", "tools-" + ex["family"])
        r["id"] = ex["id"]
        train.append(r)
        c["kept"] += 1
    funnel["opus-synth-tools"] = dict(c)

    readers = {"hermes-fc": tf.read_hermes, "toolace": tf.read_toolace, "glaive-fc-v2": tf.read_glaive}
    for name, fn in readers.items():
        s = SRC[name]
        c = Counter()
        items = []
        for f in s.files:
            with open(os.path.join(RAW, s.repo.replace("/", "__"), f)) as fh:
                items.extend(json.load(fh))
        rng.shuffle(items)
        for item in items:
            c["read"] += 1
            try:
                out = fn(item)
            except Exception:  # malformed upstream rows
                out = None
            if not out or not tf.valid(*out):
                c["parse_or_format_error"] += 1
                continue
            msgs, tools = out
            first = msgs[0]["content"]
            if decon.contaminated(first):
                c["benchmark_contaminated"] += 1
                continue
            if s.max_rows and c["kept"] >= s.max_rows:
                c["over_cap"] += 1
                continue
            if exact.is_dup(first):
                c["exact_duplicate"] += 1
                continue
            if near.is_dup(first + " " + " ".join(t["function"]["name"] for t in tools)):
                c["near_duplicate"] += 1
                continue
            msgs = [dict(m, content=scrub_pii(m.get("content") or "")) for m in msgs]
            train.append(row(name, msgs, tools, guess_language(first), s.license, "function-calling"))
            c["kept"] += 1
        funnel[name] = dict(c)
        log(f"tools {name}: {dict(c)}")
    for rows in (train, test):
        for i in range(0, len(rows), 2000):
            batch = rows[i:i + 2000]
            texts = [r["tools"] + "\n" + "\n".join(m["content"] + m["tool_calls"] for m in r["messages"]) for r in batch]
            for r, n in zip(batch, count_tokens(texts)):
                r["num_tokens"] = n
    train = [r for r in train if r["num_tokens"] <= 8192]
    rng.shuffle(train)
    write_split("tools", "train", train, 50_000)
    write_split("tools", "test", test, 50_000)
    by = defaultdict(Counter)
    for r in train:
        by[r["source"]]["rows"] += 1
        by[r["source"]]["tokens"] += r["num_tokens"]
        by[r["source"]]["tool_calls"] += r["num_tool_calls"]
    save_stats("tools_funnel", funnel)
    save_stats("tools_sources", {k: dict(v) for k, v in by.items()})
    save_stats("tools_families", dict(Counter(r["domain"] for r in train if r["source"] == "opus-synth-tools")))


# --------------------------------------------------------------------------- pretraining (parallel)

_DECON = None


def _init_worker(decon):
    global _DECON
    _DECON = decon


def _process_pretrain_batch(args):
    name, texts, urls, lang_default = args
    out, c = [], Counter()
    keep_texts = []
    for text, url in zip(texts, urls):
        c["read"] += 1
        fails = gopher_quality(text)
        if fails:
            c["quality:" + fails[0]] += 1
            continue
        if _DECON.contaminated(text, check_short=False):
            c["benchmark_contaminated"] += 1
            continue
        text = scrub_pii(text)
        keep_texts.append((text, url))
    counts = count_tokens([t for t, _ in keep_texts]) if keep_texts else []
    for (text, url), n in zip(keep_texts, counts):
        out.append((key(text), text, url, n))
    return name, out, c


def iter_pretrain_batches(name, batch_rows=2000):
    s = SRC[name]
    lang = "tr" if name == "fineweb2-tr" else "en"
    seen = 0
    for f in s.files:
        pf = pq.ParquetFile(os.path.join(RAW, s.repo.replace("/", "__"), f))
        cols = ["text", "url"] + (["language_score"] if name == "fineweb2-tr" else [])
        for batch in pf.iter_batches(batch_size=batch_rows, columns=cols):
            d = batch.to_pydict()
            texts, urls = d["text"], d["url"]
            if name == "fineweb2-tr":
                keep = [i for i, sc in enumerate(d["language_score"]) if sc >= 0.9]
                texts, urls = [texts[i] for i in keep], [urls[i] for i in keep]
            if s.max_rows and seen >= s.max_rows * 1.15:   # read a bit past the cap to absorb filtering
                return
            seen += len(texts)
            yield name, texts, urls, lang


def build_pretrain(decon):
    exact = ExactDeduper()
    funnel = defaultdict(Counter)
    tokens = Counter()
    d = os.path.join(OUT, "data", "pretrain")
    os.makedirs(d, exist_ok=True)
    shard_rows, shard_idx, buf = 60_000, 0, []
    lengths = defaultdict(list)

    def flush(final=False):
        nonlocal shard_idx, buf
        while len(buf) >= shard_rows or (final and buf):
            part, buf = buf[:shard_rows], buf[shard_rows:]
            pq.write_table(pa.Table.from_pylist(part, schema=SCHEMAS["pretrain"]),
                           os.path.join(d, f"train-{shard_idx:05d}.parquet"), compression="zstd",
                           row_group_size=5_000)
            shard_idx += 1

    def jobs():
        for name in ("fineweb-edu", "fineweb2-tr", "open-web-math"):
            yield from iter_pretrain_batches(name)

    ctx = mp.get_context("fork")
    with ctx.Pool(4, initializer=_init_worker, initargs=(decon,)) as pool:
        for name, out, c in pool.imap(_process_pretrain_batch, jobs(), chunksize=1):
            s = SRC[name]
            funnel[name].update(c)
            for k, text, url, n in out:
                if s.max_rows and funnel[name]["kept"] >= s.max_rows:
                    funnel[name]["over_cap"] += 1
                    continue
                if k in exact.seen:
                    funnel[name]["exact_duplicate"] += 1
                    continue
                exact.seen.add(k)
                funnel[name]["kept"] += 1
                tokens[name] += n
                if len(lengths[name]) < 50_000:
                    lengths[name].append(n)
                buf.append({"id": f"{name}-{k[:20]}", "text": text, "source": name, "domain": s.domain,
                            "language": "tr" if name == "fineweb2-tr" else "en", "license": s.license,
                            "url": url, "num_tokens": n})
            flush()
            if sum(f["read"] for f in funnel.values()) % 100_000 < 2000:
                log("pretrain progress", {k: v["kept"] for k, v in funnel.items()}, dict(tokens))
    flush(final=True)
    # rename shards with -of-N suffix so the HF loader shows the count
    files = sorted(x for x in os.listdir(d) if x.startswith("train-"))
    for i, f in enumerate(files):
        os.rename(os.path.join(d, f), os.path.join(d, f"train-{i:05d}-of-{len(files):05d}.parquet"))
    save_stats("pretrain_funnel", {k: dict(v) for k, v in funnel.items()})
    save_stats("pretrain_tokens", dict(tokens))
    save_stats("pretrain_lengths", dict(lengths))
    log("pretrain done", dict(tokens))


# --------------------------------------------------------------------------- main

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--stages", default="sft,preference,synth_eval,tools,pretrain")
    ap.add_argument("--synth-train", type=int, default=60_000)
    ap.add_argument("--synth-pref", type=int, default=10_000)
    ap.add_argument("--synth-eval", type=int, default=2_000)
    a = ap.parse_args()
    stages = a.stages.split(",")
    decon = build_decontaminator()

    # Disjoint synthetic sets: eval prompts are generated first with their own seed and
    # excluded from train/preference generation.
    eval_set = list(synth.generate(a.synth_eval, seed=9001))
    eval_prompts = {e["prompt"] for e in eval_set}
    train_set = [e for e in synth.generate(a.synth_train + 2000, seed=1) if e["prompt"] not in eval_prompts][:a.synth_train]
    used = eval_prompts | {e["prompt"] for e in train_set}
    rng = random.Random(7)
    pairs = []
    for e in synth.generate(a.synth_pref * 3, seed=2):
        if e["prompt"] in used or e["answer"] in ("UNANSWERABLE", "CODE_VERIFIED_BY_TESTS"):
            continue
        bad = synth.corrupt(e, rng)
        if bad:
            pairs.append((e, bad))
        if len(pairs) >= a.synth_pref:
            break

    if "synth_eval" in stages:
        write_split("synth_eval", "test", [{"id": e["id"], "family": e["family"], "language": e["language"],
                                            "difficulty": e["difficulty"], "prompt": e["prompt"],
                                            "answer": e.get("tests") or e["answer"],
                                            "reference_response": e["response"]}
                                           for e in eval_set], 10_000)
        save_stats("synth_eval_families", dict(Counter(e["family"].split("/")[0] for e in eval_set)))
    if "sft" in stages:
        build_sft(decon, train_set)
    if "preference" in stages:
        build_preference(decon, pairs)
    if "tools" in stages:
        build_tools(decon)
    if "pretrain" in stages:
        build_pretrain(decon)
    log("ALL DONE")


if __name__ == "__main__":
    main()