File size: 31,500 Bytes
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6c876
 
 
c02657c
 
 
 
fb6c876
c02657c
 
fb6c876
c02657c
fb6c876
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73f7e6f
 
 
 
 
 
 
 
 
 
 
 
 
 
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329c0a1
 
 
 
 
 
 
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6c876
 
 
 
 
 
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6c876
c02657c
 
 
fb6c876
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6c876
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6c876
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6c876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6c876
 
 
 
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73f7e6f
 
 
c02657c
 
 
 
 
73f7e6f
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73f7e6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6c876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c02657c
 
 
 
 
 
 
 
 
fb6c876
 
 
73f7e6f
c02657c
 
 
 
 
 
 
 
 
73f7e6f
 
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
"""Generate the Hugging Face dataset card (README.md) from the build statistics."""
import json
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from opusdb.sources import SOURCES  # noqa: E402

OUT = os.environ.get("OPUSDB_OUT", "out")
REPO = os.environ.get("OPUSDB_REPO", "KeremTT/OPUS-5.5-DATABASE")
ST = os.path.join(OUT, "stats")


def load(name, default=None):
    p = os.path.join(ST, name + ".json")
    return json.load(open(p)) if os.path.exists(p) else default


def h(n):
    for unit, k in (("B", 1e9), ("M", 1e6), ("K", 1e3)):
        if n >= k:
            return f"{n / k:.2f}{unit}" if n / k < 10 else f"{n / k:.1f}{unit}"
    return f"{n:,}"


def main():
    sft, pref = load("sft_sources", {}), load("preference_sources", {})
    pre, pref_f, sft_f = load("pretrain_tokens", {}), load("preference_funnel", {}), load("sft_funnel", {})
    pre_f = load("pretrain_funnel", {})
    proj, lad, evals = load("projections"), load("ladder"), load("evals", [])
    fam = load("synth_eval_families", {})
    tools_s, tools_f, tools_fam = load("tools_sources", {}), load("tools_funnel", {}), load("tools_families", {})
    tools_rows, tools_tok = sum(v["rows"] for v in tools_s.values()), sum(v["tokens"] for v in tools_s.values())
    tools_calls = sum(v["tool_calls"] for v in tools_s.values())
    sft_rows, sft_tok = sum(v["rows"] for v in sft.values()), sum(v["tokens"] for v in sft.values())
    pref_rows, pref_tok = sum(v["rows"] for v in pref.values()), sum(v["tokens"] for v in pref.values())
    pre_rows, pre_tok = sum(v.get("kept", 0) for v in pre_f.values()), sum(pre.values())
    eval_rows = sum(fam.values())
    total_tok = sft_tok + pref_tok + pre_tok + tools_tok
    pre_line = (f"{pre_rows:,} documents · {h(pre_tok)} tokens (English educational web, Turkish web, math web)" if pre_tok
                else "English educational web, Turkish web, math web — **processing, files are being uploaded**")
    contaminated = sum(c.get("benchmark_contaminated", 0) for f in (sft_f, pref_f, pre_f, tools_f) for c in f.values()
                       if isinstance(c, dict))
    dups = sum(c.get("exact_duplicate", 0) + c.get("near_duplicate", 0) for f in (sft_f, pref_f, pre_f, tools_f)
               for c in f.values() if isinstance(c, dict))
    lic = {s.name: s.license for s in SOURCES}
    repo_of = {s.name: s.repo for s in SOURCES}

    def src_table(stats, stage):
        lines = ["| source | upstream | license | rows | tokens |", "|---|---|---|---:|---:|"]
        for k, v in sorted(stats.items(), key=lambda kv: -kv[1]["tokens"]):
            up = f"[{repo_of[k]}](https://huggingface.co/datasets/{repo_of[k]})" if k in repo_of else "original (this repo)"
            lines.append(f"| `{k}` | {up} | {lic.get(k, 'apache-2.0')} | {v['rows']:,} | {h(v['tokens'])} |")
        return "\n".join(lines)

    pre_table = ["| source | upstream | license | documents | tokens |", "|---|---|---|---:|---:|"]
    for k, t in sorted(pre.items(), key=lambda kv: -kv[1]):
        pre_table.append(f"| `{k}` | [{repo_of[k]}](https://huggingface.co/datasets/{repo_of[k]}) | {lic[k]} | "
                         f"{pre_f.get(k, {}).get('kept', 0):,} | {h(t)} |")

    ladder_md = ""
    if lad and lad.get("runs"):
        rows = ["| model | layers × width | params | training tokens | tokens/param | CPU time | final val loss |",
                "|---|---|---:|---:|---:|---:|---:|"]
        for r in sorted(lad["runs"], key=lambda r: r["total_params"]):
            rows.append(f"| {r['name']} | {r['n_layer']} × {r['d_model']} | {h(r['total_params'])} | {h(r['tokens'])} | "
                        f"{r['tokens'] / r['total_params']:.1f} | {r['seconds'] / 60:.0f} min | {r['val_loss']:.3f} |")
        fit = lad.get("fit")
        fit_txt = (f"\nFitted power law on these points: **L(N) = {fit['E']:.2f} + {fit['A']:.3g} · N^-{fit['alpha']:.3f}** "
                   f"(nats/token, {lad['vocab']}-token BPE trained on the same data, context {lad['ctx']}).\n") if fit else ""
        ladder_md = "\n".join(rows) + "\n" + fit_txt

    ladder_note = ""
    if lad and lad.get("runs"):
        rs = sorted(lad["runs"], key=lambda r: r["total_params"])
        best = min(rs, key=lambda r: r["val_loss"])
        ladder_note = (f"**Reading the result.** With the same {h(rs[0]['tokens'])}-token budget, validation loss falls from "
                       f"{rs[0]['val_loss']:.2f} ({h(rs[0]['total_params'])} params) to {best['val_loss']:.2f} "
                       f"({h(best['total_params'])} params)"
                       + (f" and then stops improving at {h(rs[-1]['total_params'])} params ({rs[-1]['val_loss']:.2f}). "
                          "That plateau is the data-limited regime: at ~1 token per parameter a larger model cannot use its "
                          "extra capacity. This is exactly why the projections below scale data with model size "
                          "(≈20 tokens per parameter) — and why 4B-27B models should start from a pretrained base "
                          "rather than from the `pretrain` config alone." if rs[-1] is not best else ". ")
                       + " These are tiny CPU runs (minutes each), so absolute losses are high; the trend, not the level, "
                         "is the point.")
    proj_md = ""
    if proj:
        rows = ["| model size | Chinchilla-optimal tokens (20/param) | epochs over OPUS `pretrain` | projected loss, unlimited data | "
                "projected loss, OPUS `pretrain` only |", "|---:|---:|---:|---:|---:|"]
        for r in proj["rows"]:
            rows.append(f"| {r['params_b']:g}B | {r['chinchilla_optimal_tokens_b']:g}B | {r['epochs_needed_on_opus']:.1f} | "
                        f"{r['loss_unlimited']:.3f} | {r['loss_opus_repeated']:.3f} |")
        proj_md = "\n".join(rows)

    eval_md = ""
    if evals:
        rows = ["| model | params | overall | English | Turkish | notes |", "|---|---:|---:|---:|---:|---|"]
        for r in sorted(evals, key=lambda r: (r["params_b"], r["kind"] != "baseline")):
            note = "off-the-shelf" if r["kind"] == "baseline" else f"+ OPUS-SFT, {r['train_examples']:,} examples, {r['train_note']}"
            rows.append(f"| [{r['label']}](https://huggingface.co/{r['model']}) | {r['params_b']:g}B | **{100 * r['accuracy']:.1f}%** | "
                        f"{100 * r['by_language']['en']:.1f}% | {100 * r['by_language']['tr']:.1f}% | {note} |"
                        if r["kind"] == "baseline" else
                        f"| {r['label']} | {r['params_b']:g}B | **{100 * r['accuracy']:.1f}%** | "
                        f"{100 * r['by_language']['en']:.1f}% | {100 * r['by_language']['tr']:.1f}% | {note} |")
        eval_md = "\n".join(rows) + f"\n\nAll rows use the same {evals[0]['n']} randomly sampled `synth_eval` items, greedy decoding, the model's own chat template, and the exact-match scorer in `code/train/eval_synth.py`. With n = {evals[0]['n']} the 95% interval is roughly ±10-12 points, " \
                   "so read differences of a few points as noise.\n\n" \
                   "**Caveat:** `synth_eval` comes from the same generators as the `opus-synth` training rows (different seed, no " \
                   "shared prompts), so the fine-tuned row measures how well a model learns these procedures and answer " \
                   "formats — e.g. JSON extraction and recognising unanswerable questions go to 100% — not general " \
                   "intelligence. Off-the-shelf rows show how hard the set is for models that never saw it; note how much " \
                   "weaker they are on the Turkish items."

    card = f"""---
license:
- apache-2.0
- mit
- cc-by-4.0
- odc-by
language:
- en
- tr
- multilingual
pretty_name: OPUS-5.5-DATABASE
size_categories:
- 1M<n<10M
task_categories:
- text-generation
- question-answering
tags:
- pretraining
- sft
- instruction-tuning
- dpo
- preference
- math
- code
- reasoning
- turkish
- synthetic
- verified
- decontaminated
configs:
- config_name: sft
  default: true
  data_files:
  - split: train
    path: data/sft/train-*.parquet
  - split: test
    path: data/sft/test-*.parquet
- config_name: preference
  data_files:
  - split: train
    path: data/preference/train-*.parquet
  - split: test
    path: data/preference/test-*.parquet
- config_name: pretrain
  data_files:
  - split: train
    path: data/pretrain/train-*.parquet
- config_name: tools
  data_files:
  - split: train
    path: data/tools/train-*.parquet
  - split: test
    path: data/tools/test-*.parquet
- config_name: synth_eval
  data_files:
  - split: test
    path: data/synth_eval/test-*.parquet
---

# OPUS-5.5-DATABASE

**A complete, open, decontaminated training corpus for language models — pretraining text, supervised
fine-tuning conversations, preference pairs and a verifiable evaluation set — plus the full Python
library that builds it and the scripts that train on it.**

| | |
|---|---|
| **Total size** | **{h(total_tok)} tokens** across 5 configs |
| `pretrain` | {pre_line} |
| `sft` | {sft_rows:,} conversations · {h(sft_tok)} tokens (chat, instruction following, math, code, verified synthetic EN/TR) |
| `preference` | {pref_rows:,} chosen/rejected pairs · {h(pref_tok)} tokens (for DPO / ORPO / KTO / reward models) |
| `tools` | {tools_rows:,} tool-use conversations · {tools_calls:,} tool calls · {h(tools_tok)} tokens (calculator, Python, dates, units + 1000s of real-world APIs) |
| `synth_eval` | {eval_rows:,} held-out items with programmatically verified answers (EN + TR) |
| **Languages** | English (primary), Turkish (second), plus 30+ languages from OpenAssistant |
| **Removed** | {contaminated:,} benchmark-contaminated rows · {dups:,} duplicates |
| **Licenses** | only permissive sources: Apache-2.0, MIT, CC-BY-4.0, ODC-By (per-row `license` column) |

> **Name & affiliation.** "OPUS-5.5" is simply the name of this project. The dataset is **not affiliated with,
> endorsed by, or produced by Anthropic**, and it contains **no outputs of Anthropic's Claude models**.
> The OPUS-synth generators (Python code in `code/opusdb/synth.py`) were written with AI coding assistance; the
> examples themselves are produced deterministically by that code, not sampled from a language model.

![composition](assets/composition.png)

## Quick start

```python
from datasets import load_dataset

sft  = load_dataset("{REPO}", "sft", split="train")          # chat SFT (messages format)
pref = load_dataset("{REPO}", "preference", split="train")   # DPO pairs
pre  = load_dataset("{REPO}", "pretrain", split="train", streaming=True)  # raw text
tools = load_dataset("{REPO}", "tools", split="train")       # function calling / agents
ev   = load_dataset("{REPO}", "synth_eval", split="test")    # verifiable eval

# filter by capability / language / license with the metadata columns
math_tr = sft.filter(lambda r: r["domain"].endswith("math") or r["language"] == "tr")
```

Train with the included scripts (TRL):

```bash
pip install "trl>=0.20" "transformers>=4.45" peft datasets accelerate
huggingface-cli download {REPO} --repo-type dataset --include "code/*" --local-dir opus55
cd opus55/code
accelerate launch train/sft_trl.py --model Qwen/Qwen2.5-1.5B --epochs 2              # full SFT
accelerate launch train/sft_trl.py --model meta-llama/Llama-3.1-8B --lora --epochs 2 # LoRA SFT
accelerate launch train/dpo_trl.py --model ./opus55-sft --beta 0.1                   # preference tuning
python train/eval_synth.py --model ./opus55-dpo --limit 500                          # verifiable eval
```

## What a good training set needs — and how this one is built

A strong model is not trained on "a lot of text"; it is trained in **stages**, and each stage needs data with a
different shape. OPUS-5.5-DATABASE ships one config per stage and applies the same quality controls to all of them.

| stage | what the model learns | what the data must look like | config |
|---|---|---|---|
| 1. Pretraining | language, world knowledge, reasoning patterns | huge, diverse, clean, deduplicated plain text; high share of educational content, math and multilingual text | `pretrain` |
| 2. Supervised fine-tuning | following instructions, conversation format, step-by-step answers | high-quality prompt → response conversations covering many skills, correct answers, multi-turn | `sft` |
| 2b. Tool use / agents | when to call a tool, how to format the call, how to use the result, how to recover from errors | multi-turn conversations with tool definitions, calls, real tool outputs and final answers | `tools` |
| 3. Preference optimisation | which of two answers is better (helpfulness, correctness) | pairs of chosen vs. rejected responses with a real quality gap | `preference` |
| 4. Evaluation | — | held-out, decontaminated, automatically checkable | `synth_eval` |

The build pipeline (`code/scripts/build.py`) enforces the properties that research has repeatedly shown to matter:

1. **Quality over quantity** — educational web text (FineWeb-Edu classifier score ≥ 3), Gopher-style document
   rules (length, symbol ratio, word length, repeated lines, bullet/ellipsis lines), reward-model/quality labels kept
   only at "good"/"excellent" for synthetic chat, and an argilla-style quality recipe for preference pairs.
2. **Deduplication** — exact dedup on normalised text for every config, plus **MinHash-LSH near-duplicate
   removal** (word 5-gram shingles, 128 permutations, 16 bands) on SFT prompts across all sources.
3. **Benchmark decontamination** — every pretraining document, SFT prompt and preference prompt is checked for
   **13-gram overlap** (plus whole-phrase matches for 10-12-word items in chat data) against GSM8K-test, MATH-500,
   HumanEval and MMLU-test. {contaminated:,} rows were removed.
4. **Correctness you can trust** — the `opus-synth` subset is generated by code that also computes the answer;
   every arithmetic line in every response is re-evaluated, and every code answer is executed against unit tests
   before it is accepted.
5. **Capability balance** — general chat, instruction-following with constraints, rewriting, summarisation,
   human-written multilingual dialogue, math, code, logic, dates, string manipulation, structured JSON output and
   *knowing when a question cannot be answered*.
6. **Multilinguality** — Turkish is a first-class language: Turkish web text for pretraining, ~35% of `opus-synth`
   is in Turkish (with correct vowel-harmony suffixes and Turkish alphabetical order), plus OpenAssistant dialogues
   in 30+ languages.
7. **Safety & privacy** — e-mail addresses and IP addresses are replaced with `<EMAIL>` / `<IP_ADDRESS>`;
   responses that claim to be ChatGPT/OpenAI or contain "as an AI language model" boilerplate are removed.
8. **Licensing & provenance** — only permissively licensed sources; each row carries `source` and `license`.
9. **Reproducibility** — the complete library, source registry (with exact upstream files), seeds and statistics
   are in the `code/` folder of this repository.

![funnel](assets/funnel.png)

## Composition

### `sft` — {sft_rows:,} conversations, {h(sft_tok)} tokens

{src_table(sft, "sft")}

![sft mix](assets/sft_mix.png)

### `preference` — {pref_rows:,} pairs, {h(pref_tok)} tokens

{src_table(pref, "preference")}

`opus-synth-pref` pairs a verified step-by-step solution (chosen) with the same solution in which one intermediate
result was corrupted and the error propagated to a wrong final answer (rejected) — this teaches the model to prefer
*correct* reasoning, not just a nicer style.

### `tools` — {tools_rows:,} conversations, {tools_calls:,} tool calls, {h(tools_tok)} tokens

{src_table(tools_s, "tools") if tools_s else ""}

The `tools` config teaches a model to act as an **agent**: read the tool definitions, decide whether a tool is
needed, emit a correctly formatted call, read the result and answer — or explain an error.

**OPUS-synth-tools** (original, verified) ships with a real tool runtime, `code/opusdb/agent_tools.py`, so the
same tools the model was trained on can be executed at inference time:

| tool | what it does |
|---|---|
| `calculator` | exact arithmetic (fractions, powers, sqrt, log, trig, factorial, gcd) |
| `python` | runs a short Python program and returns stdout or the error |
| `date_calc` | days between dates, adding days, weekday |
| `unit_convert` | length, mass, volume, time, temperature |

Behaviours covered ({", ".join(f"{k.replace('tools-', '')}: {v:,}" for k, v in sorted(tools_fam.items(), key=lambda kv: -kv[1]))}):
single calls, chained calls (the output of one call feeds the next), **parallel calls** in one turn, writing and
running code, **repairing code after an error**, explaining tool errors, answering directly when no tool is needed,
and **declining** when no available tool can do the job. Every tool output in the data is the real output of the
runtime, and every final answer is computed from it. Hermes-FC, ToolACE (thousands of distinct real-world API
schemas) and Glaive-FC-v2 add breadth.

Rows store `tool_calls` and `tools` as JSON strings so heterogeneous argument types fit in Parquet. Decode them for
any chat template that supports tools (Qwen 2.5/3, Llama 3.1+, Mistral, Hermes, ...):

```python
import sys; sys.path.insert(0, "opus55/code")
from opusdb.tool_formats import to_chat_template
messages, tools = to_chat_template(row)
text = tokenizer.apply_chat_template(messages, tools=tools, tokenize=False)
```

Agent loop at inference time:

```python
from opusdb.agent_tools import TOOL_SPECS, call_tool, parse_tool_calls
conv = [{{"role": "user", "content": "How many primes are below 100000?"}}]
while True:
    out = generate(tokenizer.apply_chat_template(conv, tools=TOOL_SPECS, add_generation_prompt=True, tokenize=False))
    calls = parse_tool_calls(out)
    if not calls:
        print(out); break
    conv.append({{"role": "assistant", "content": "", "tool_calls": [{{"type": "function", "function": c}} for c in calls]}})
    conv += [{{"role": "tool", "name": c["name"], "content": str(call_tool(c["name"], c["arguments"]))}} for c in calls]
```

> The reference `python` tool runs code in a separate interpreter with a timeout; it is **not** a security sandbox.
> Run it inside a container without network access or credentials when serving untrusted users.

### `pretrain` — {pre_line}

{chr(10).join(pre_table) if pre_tok else "_The pretraining config is still being processed; this table is filled in automatically when it is uploaded._"}

![lengths](assets/lengths.png)

### `synth_eval` — {eval_rows:,} verifiable items

Families: {", ".join(f"{k} ({v})" for k, v in sorted(fam.items(), key=lambda kv: -kv[1]))}.
Prompts are generated with a separate seed and are guaranteed not to appear in `sft` or `preference`.

## Data fields

**`sft`**: `id`, `messages` (list of `{{role, content}}`, roles `system`/`user`/`assistant`), `source`, `domain`,
`language`, `license`, `num_turns`, `num_tokens`.

**`preference`**: `id`, `prompt`, `chosen` (messages), `rejected` (messages), `source`, `domain`, `language`,
`license`, `score_chosen`, `score_rejected`, `num_tokens`.

**`pretrain`**: `id`, `text`, `source`, `domain`, `language`, `license`, `url`, `num_tokens`.

**`tools`**: `id`, `messages` (list of `{{role, content, tool_calls, tool_call_id, name}}`; `tool_calls` is a JSON
string), `tools` (JSON string, OpenAI function schema), `source`, `domain`, `language`, `license`, `num_tool_calls`,
`num_tokens`.

**`synth_eval`**: `id`, `family`, `language`, `difficulty` (1-3), `prompt`, `answer` (ground truth; for code items
the unit tests), `reference_response`.

Token counts use the `HuggingFaceTB/SmolLM2-135M` tokenizer (49k BPE). Other tokenizers will differ by roughly
±15% for English and more for Turkish.

## How it performs at different model sizes

There are three kinds of numbers below, and they are labelled clearly:

* **MEASURED** — experiments actually run on this data; the scripts that produced them are in `code/train/`.
* **PROJECTION** — computed from published scaling laws (Hoffmann et al. 2022 "Chinchilla"; Muennighoff et al.
  2023 for repeated data). They show trends, not guarantees.
* **ESTIMATE** — arithmetic on token counts (6·N·D FLOPs), e.g. GPU-hours.

### MEASURED: off-the-shelf models on `synth_eval` and the effect of OPUS-SFT

{eval_md if eval_md else "_(pending)_"}

![evals](assets/evals.png)

### MEASURED: small-scale pretraining ladder on `pretrain`

GPT-style decoder models of increasing size trained from scratch on the same sample of the `pretrain` config
(same token stream, same hyper-parameters, **the same token budget for every model**, CPU only), evaluated on the
same held-out tokens:

{ladder_md if ladder_md else "_(pending)_"}

![ladder](assets/ladder.png)

{ladder_note}

### PROJECTION & ESTIMATE: 0.1B – 70B

![projections](assets/projections.png)

{proj_md if proj_md else "_(pending — computed after the pretrain config is finalised)_"}

**How to read this.** The `pretrain` config alone ({h(pre_tok) if pre_tok else "a few billion"} unique tokens) is compute-optimal only for small models
(≈ unique tokens ÷ 20 parameters, i.e. on the order of 100M parameters). Beyond that a model needs more data than the config contains; repeating it
up to ~4 epochs is almost as good as fresh data (Muennighoff et al. 2023), but larger models should use `pretrain`
as a high-quality **mid-training / annealing mix** next to a larger web corpus, not as the only source.
The `sft` and `preference` configs, in contrast, are useful at **every** size — post-training needs quality and
coverage, not trillions of tokens.

### Recommended recipe by model size

| model size | how to use OPUS-5.5-DATABASE | suggested settings |
|---|---|---|
| ≤ 150M (from scratch) | pretrain on `pretrain` (≈1-2 epochs), then full SFT on `sft`, then DPO | lr 3e-3 → 3e-4 pretrain; SFT lr 1e-4, 3 epochs |
| 0.3B – 1B | mix `pretrain` into the last 10-20% of pretraining (annealing), full SFT 2-3 epochs, DPO 1 epoch | SFT lr 5e-5 – 1e-4, DPO β = 0.1, lr 5e-7 |
| 1B – 8B | full SFT or LoRA (r = 64, all linear layers) 2 epochs, then DPO 1 epoch | SFT lr 2e-5 (full) / 2e-4 (LoRA), max length 4096 |
| 13B – 70B | LoRA / QLoRA SFT 1-2 epochs, DPO with LoRA | LoRA r = 16-64, lr 1e-4, β = 0.05-0.1 |

### Recommended recipe: fine-tuning a 4B model with tool use

The projection table above is about **pretraining from scratch**. If you fine-tune an existing 4B model, you do
not need 80B tokens — you need the right post-training stages:

| stage | data | settings (4B) | why |
|---|---|---|---|
| 0. (optional) Turkish continued pretraining | `pretrain` where `language == "tr"` (≈0.9B tokens) mixed ~50/50 with English | lr 1e-5 – 2e-5, 1 epoch | only if the base model is weak in Turkish |
| 1. SFT | `sft` + `tools` (tools upsampled ×2) | full FT: lr 2e-5, 2 epochs, max length 4096, assistant-only loss; LoRA: r 64, lr 2e-4 | instruction following, step-by-step answers, tool calling |
| 2. Preference (DPO) | `preference` | lr 5e-7 (full) / 5e-6 (LoRA), β 0.1, 1 epoch | prefers correct and helpful answers |
| 3. Evaluate | `synth_eval`, `tools` test | `eval_synth.py`, `eval_tools.py --format hermes` | before/after comparison |

Estimated cost for stage 1: ~15 H100-hours (full fine-tune, 2 epochs, 40% MFU) or roughly a third of that with
LoRA; a single 80 GB GPU is enough for full fine-tuning of 4B with gradient checkpointing, a 24 GB GPU with LoRA.
Everything is wired up in one script: `code/train/recipe_4b.sh` (`BASE=<your model> bash train/recipe_4b.sh`).

`sft_trl.py --with-tools` renders tool conversations in a **template-independent Hermes format** (tool schemas in
the system prompt, `<tool_call>` / `<tool_response>` blocks), so it works for Qwen, Llama, Gemma, Mistral or Phi
bases alike. After training, plug the model into the bundled tool library:

```python
import sys; sys.path.insert(0, "opus55/code")
from opusdb.agent import Agent
agent = Agent.from_pretrained("./opus55-4b-dpo")
agent.register({{"type": "function", "function": {{"name": "get_stock", "description": "Units in stock for a SKU",
                "parameters": {{"type": "object", "properties": {{"sku": {{"type": "string"}}}}, "required": ["sku"]}}}}}},
               lambda sku: {{"sku": sku, "units": 42}})          # your own tools work the same way
print(agent.run("What is 17.5% of 2,384,190? Then how many days until 2027-01-01 from 2026-11-10?", verbose=True))
```

### What to expect from a 4B, 8B, 14B or 27B model trained on it

At these sizes OPUS-5.5-DATABASE is a **post-training** dataset: start from an existing open base model
(e.g. a 4B/8B/14B/27B base checkpoint from the Qwen, Llama, Gemma or Mistral families) and run
`sft` + `tools` → `preference`. Pretraining a 4B+ model from scratch needs ~80B-540B tokens (20 tokens/parameter),
far more than the `pretrain` config; the base model's own pretraining determines most of its knowledge.
The table below is a qualitative expectation based on the data composition and on published results of
similarly-sized models after comparable post-training — **not a measured benchmark of this dataset**.

| capability | 4B | 8B | 14B | 27B |
|---|---|---|---|---|
| Multi-turn chat, instruction following, format constraints | good | good | very good | very good |
| Grade-school math word problems, step by step (GSM8K-style) | mostly correct | reliable | reliable | reliable |
| Competition math (MATH-style) | basic | partial | solid | strong |
| Python functions / small scripts | simple functions | everyday tasks | most tasks | strong |
| Tool calling: right tool, valid JSON arguments | good on known tools | reliable | reliable, parallel calls | reliable, multi-step plans |
| Multi-step agent loops, error recovery | short chains | 2-4 steps | longer chains | longest chains |
| Turkish | understands, simpler answers | fluent everyday Turkish | fluent | fluent, nuanced |
| Structured JSON output | good | reliable | reliable | reliable |
| Saying "I can't" / "not enough information" | learned | learned | learned | learned |
| World knowledge, up-to-date facts | limited to base model | limited to base model | limited to base model | limited to base model |

What the data specifically adds: an exact **step-by-step answer style** (every line checkable), **calling a
calculator or Python instead of guessing arithmetic**, recovering from tool errors, structured outputs, refusing
out-of-scope tool requests, and Turkish coverage. What it cannot add: new world knowledge beyond the base model,
long-context skills (> 8k tokens), vision, or frontier-level reasoning. Use `synth_eval` and
`code/train/eval_tools.py` to measure your model before and after training.

Filter by `domain` or `language` to specialise (e.g. a Turkish math tutor: `language == "tr"` plus all math sources).

## The library (`code/`)

```
code/
├── opusdb/
│   ├── sources.py     # registry: upstream repo, exact files, verified license, caps
│   ├── synth.py       # OPUS-synth: 11 families of verified EN/TR generators + preference corruption
│   ├── synth_tools.py # OPUS-synth-tools: 9 verified tool-use behaviours (EN/TR)
│   ├── agent_tools.py # tool runtime: calculator, python, date_calc, unit_convert + call parser
│   ├── tool_formats.py# Hermes / ToolACE / Glaive converters, chat-template helpers
│   ├── agent.py       # Agent loop: run a fine-tuned model with the tools (and your own)
│   ├── text.py        # normalisation, hashing, PII scrubbing, language id, Gopher quality rules
│   ├── dedup.py       # exact + MinHash-LSH near-duplicate detection (numpy)
│   └── decontam.py    # 13-gram benchmark decontamination (rolling hashes, numpy)
├── scripts/
│   ├── download.py    # fetch upstream files
│   ├── build.py       # full pipeline -> Parquet configs + statistics
│   ├── charts.py      # all figures in this card
│   └── make_card.py   # this README, generated from the statistics
└── train/
    ├── recipe_4b.sh       # end-to-end 4B recipe: SFT(+tools) -> DPO -> eval
    ├── sft_trl.py         # SFT with TRL (full or LoRA), --with-tools adds the tools config
    ├── dpo_trl.py         # DPO with TRL
    ├── eval_synth.py      # exact-match evaluation on synth_eval
    ├── eval_tools.py      # agent-loop evaluation on the tools test split
    ├── small_sft.py       # dependency-light SFT loop used for the measured experiment
    └── scaling_ladder.py  # from-scratch scaling ladder used for the measured experiment
```

Rebuild everything:

```bash
pip install datasets huggingface_hub pyarrow numpy tokenizers matplotlib
python scripts/download.py            # ~11 GB of upstream files
python scripts/build.py               # writes out/data/** and out/stats/**
python scripts/charts.py && python scripts/make_card.py
```

Generate more verified synthetic data:

```python
from opusdb import synth
for ex in synth.generate(10, seed=123, tr_ratio=0.5):
    print(ex["prompt"], "\\n->", ex["answer"])
```

## Limitations

* Synthetic chat sources (SmolTalk Magpie-Ultra, MetaMathQA, OpenMathInstruct-2, Magicoder, UltraFeedback) were
  produced by other open or proprietary models and inherit their biases and occasional errors; only `opus-synth`
  is verified by construction.
* `opus-synth` is template-based: it teaches procedures and format robustly but has less linguistic variety than
  human writing. Use it as a 5-15% ingredient, not alone.
* Language identification for English/Turkish uses a lightweight heuristic; `other` covers all remaining languages.
* Decontamination covers GSM8K, MATH-500, HumanEval and MMLU only. Check your own benchmarks before reporting results.
* Web text can contain offensive or incorrect content despite filtering.
* The scaling projections use constants fitted on other corpora and tokenizers; treat them as order-of-magnitude guides.

## Licensing and attribution

Each row keeps the license of its upstream source in the `license` column; when you redistribute a subset, keep
the attribution required by that license (CC-BY-4.0 and ODC-By require attribution). Original material in this
repository (`opus-synth`, `opus-synth-pref`, `synth_eval`, and all code) is released under **Apache-2.0**.
FineWeb-Edu, FineWeb-2 and OpenWebMath are made available under ODC-By 1.0 and are also subject to the
Common Crawl terms of use.

Upstream datasets: HuggingFaceFW/fineweb-edu, HuggingFaceFW/fineweb-2, open-web-math/open-web-math,
HuggingFaceTB/smoltalk, OpenAssistant/oasst2, meta-math/MetaMathQA, nvidia/OpenMathInstruct-2, openai/gsm8k,
ise-uiuc/Magicoder-OSS-Instruct-75K, sahil2801/CodeAlpaca-20k, HuggingFaceH4/ultrafeedback_binarized,
argilla/distilabel-intel-orca-dpo-pairs. Thank you to all their authors.

## Citation

```bibtex
@misc{{opus55database2026,
  title  = {{OPUS-5.5-DATABASE: an open, decontaminated, multi-stage training corpus with verified synthetic data}},
  author = {{KeremTT}},
  year   = {{2026}},
  url    = {{https://huggingface.co/datasets/{REPO}}}
}}
```
"""
    with open(os.path.join(OUT, "README.md"), "w") as f:
        f.write(card)
    print("README.md written", len(card), "chars")


if __name__ == "__main__":
    main()