jncarlo commited on
Commit
fbe8d49
·
verified ·
1 Parent(s): 998e038

tinymix: 100M, 10M, 1M

Browse files
README.md ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license: other
5
+ license_name: mixed-per-source
6
+ license_link: https://huggingface.co/datasets/jncarlo/tinymix#sources-and-licensing
7
+ pretty_name: tinymix
8
+ size_categories:
9
+ - 100K<n<1M
10
+ task_categories:
11
+ - text-generation
12
+ tags:
13
+ - small-language-models
14
+ - synthetic-data
15
+ - curriculum
16
+ - tinystories
17
+ - babylm
18
+ configs:
19
+ - config_name: 1M
20
+ data_files:
21
+ - split: train
22
+ path: data/1M/train.parquet
23
+ - split: validation_dialogue
24
+ path: data/1M/validation_dialogue.parquet
25
+ - split: validation_expository
26
+ path: data/1M/validation_expository.parquet
27
+ - split: validation_narrative
28
+ path: data/1M/validation_narrative.parquet
29
+ - config_name: 10M
30
+ data_files:
31
+ - split: train
32
+ path: data/10M/train.parquet
33
+ - split: validation_dialogue
34
+ path: data/10M/validation_dialogue.parquet
35
+ - split: validation_expository
36
+ path: data/10M/validation_expository.parquet
37
+ - split: validation_narrative
38
+ path: data/10M/validation_narrative.parquet
39
+ - config_name: 100M
40
+ data_files:
41
+ - split: train
42
+ path: data/100M/train.parquet
43
+ - split: validation_books
44
+ path: data/100M/validation_books.parquet
45
+ - split: validation_dialogue
46
+ path: data/100M/validation_dialogue.parquet
47
+ - split: validation_expository
48
+ path: data/100M/validation_expository.parquet
49
+ - split: validation_narrative
50
+ path: data/100M/validation_narrative.parquet
51
+ - split: validation_news
52
+ path: data/100M/validation_news.parquet
53
+ - split: validation_poetry
54
+ path: data/100M/validation_poetry.parquet
55
+ ---
56
+
57
+ # tinymix
58
+
59
+ Small, **genre-balanced English pretraining corpora** in three sizes (about 1M, 10M and 100M words), built for training
60
+ very small language models. The mix combines synthetic child-level stories and dialogue, simplified real text,
61
+ encyclopedic and didactic text, books, poetry and news, all filtered toward clear, self-contained documents. It is
62
+ inspired by TinyStories, SimpleStories, TinyHelen and the BabyLM challenge.
63
+
64
+ What is different from using those datasets directly:
65
+
66
+ - **Several kinds of text in one mix** (narrative, dialogue and chat, expository, books, poetry, news), not only stories or only conversations.
67
+ - **Three sizes built with the same recipe**, with complexity limits that grow with size.
68
+ - **No non-commercial sources.** TinyChat (CC-BY-NC) and the BabyLM corpus (no clear license, includes subtitle and child-speech data) were left out on purpose.
69
+ - **Provenance per document** (`source`, `genre`) and **validation splits per genre**, to see which kind of text a model is weak at.
70
+ - The whole pipeline is included (`code/`) and every filter decision is documented below.
71
+
72
+ ## Subsets
73
+
74
+ | Subset | Train words | Train docs | ~Tokens (BPE) |
75
+ |---|---|---|---|
76
+ | `1M` | 1.0M | 4,199 | ~1.3M |
77
+ | `10M` | 9.95M | 42,742 | ~12.9M |
78
+ | `100M` | 99.51M | 336,124 | ~129.4M |
79
+
80
+ Words are whitespace-separated words in `train`. Each subset also has about 0.5% of the documents per genre held out as `validation_<genre>` splits
81
+ (at least one document per genre; the `1M` validation splits are therefore tiny, a few dozen documents, and noisy).
82
+
83
+ ```python
84
+ from datasets import load_dataset
85
+ ds = load_dataset("jncarlo/tinymix", "10M") # splits: train, validation_narrative, validation_dialogue, ...
86
+ print(ds["train"][0]) # {'text': ..., 'source': 'tinystories', 'genre': 'narrative'}
87
+ ```
88
+
89
+ Columns: `text` (str), `source` (key of the table below), `genre` (`narrative`, `dialogue`, `expository`, `books`, `poetry`, `news`).
90
+ Documents are independent; join them with an end-of-text token when training. Dialogues are formatted one turn per line
91
+ (`Mia: ...`, or `User:` / `Assistant:` for assistant chats).
92
+
93
+ ## Composition
94
+
95
+ Share of training words by genre:
96
+
97
+ | Genre | 1M | 10M | 100M |
98
+ |---|---|---|---|
99
+ | narrative | 37.9% | 35.0% | 21.0% |
100
+ | dialogue | 22.0% | 25.0% | 21.0% |
101
+ | expository | 40.1% | 40.0% | 48.0% |
102
+ | books | 0% | 0% | 8.0% |
103
+ | poetry | 0% | 0% | 1.0% |
104
+ | news | 0% | 0% | 1.0% |
105
+
106
+ Million words per source:
107
+
108
+ | Source | 1M (M words) | 10M (M words) | 100M (M words) |
109
+ |---|---|---|---|
110
+ | TinyStories V2 (GPT-4 split) | 0.189 | 1.492 | 7.963 |
111
+ | SimpleStories | 0.189 | 1.99 | 7.959 |
112
+ | Cosmopedia v0.1, `stories` | 0 | 0 | 4.974 |
113
+ | TinyDialogues | 0.12 | 1.493 | 6.969 |
114
+ | SODA | 0.1 | 0.994 | 8.952 |
115
+ | UltraChat 200k | 0 | 0 | 3.984 |
116
+ | SmolTalk (everyday-conversations, smol-summarize, smol-rewrite) | 0 | 0 | 0.995 |
117
+ | TinyHelen Leaner-Pretrain (book, conversation, textbook, web, wiki) | 0.15 | 1.491 | 9.948 |
118
+ | Simple English Wikipedia (20231101.simple) | 0.1 | 0.516 | 9.949 |
119
+ | Cosmopedia v2 (SmolLM-Corpus) | 0.1 | 1.113 | 11.952 |
120
+ | Cosmopedia v0.1 (wikihow, khanacademy, openstax) | 0.051 | 0.383 | 2.985 |
121
+ | tiny-textbooks (`textbook` column) | 0 | 0.479 | 3.98 |
122
+ | FineWeb-Edu (sample-10BT, score >= 4) | 0 | 0 | 8.952 |
123
+ | Project Gutenberg (English books) | 0 | 0 | 7.961 |
124
+ | Gutenberg Poetry Corpus | 0 | 0 | 0.995 |
125
+ | CNN/DailyMail 3.0.0 | 0 | 0 | 0.995 |
126
+
127
+ The 10M and 100M subsets reached their targets (10.0M and 100.0M words including the validation splits). In the 10M build,
128
+ sources that could not fill their quota with the filters (Simple English Wikipedia, Cosmopedia v0.1) were topped up by
129
+ same-genre substitute sources (tiny-textbooks, Cosmopedia v2), capped per source; that is why `tiny-textbooks` appears
130
+ there. The 1M subset keeps the 10M proportions except that Cosmopedia stories (not in the 10M mix) were replaced by TinyStories and SimpleStories.
131
+
132
+ ## How it was built
133
+
134
+ 1. **Normalisation**: `ftfy`, NFKC, ASCII quotes and dashes, whitespace; URLs, e-mails, phone numbers, code, LaTeX and HTML removed.
135
+ 2. **Language**: fastText `lid.176`, English with confidence >= 0.9 (skipped for TinyDialogues, whose one-word toddler turns confuse it).
136
+ 3. **Quality heuristics**: Gopher-style rules (mean word length, symbol and digit ratio, repeated lines, repeated bigrams, stop words), minimum length, complete ending (drops truncated generations), a short list of LLM tics (`delve`, `tapestry`, ...) and an explicit-content word list.
137
+ 4. **Anti-template**: no 4-word opening may exceed 0.5% of a source's documents.
138
+ 5. **Deduplication across all sources**: exact hash and MinHash LSH (5-word shingles, Jaccard >= 0.8).
139
+ 6. **Complexity control by size** (vocabulary coverage = share of lowercase tokens inside the top-N English words of `wordfreq`):
140
+
141
+ | | 10M | 100M |
142
+ |---|---|---|
143
+ | Reference vocabulary | top 8k | top 15k |
144
+ | Min vocabulary coverage | 90% | 90% |
145
+ | Max Flesch-Kincaid grade (narrative, news, books) | 5 | 8 |
146
+ | Max Flesch-Kincaid grade (expository) | 9 | 10 |
147
+ | Document length | 80 to 600 words | 80 to 1200 words |
148
+ | Dialogue: mean words per turn | <= 25 | <= 40 |
149
+
150
+ Assistant chats (`User:` / `Assistant:`) may average up to 4 times the per-turn cap and need at least 2 turns (named dialogues need 4),
151
+ because summarisation and rewrite tasks have 2 turns and assistant answers are long.
152
+
153
+ Documents longer than the maximum are split at paragraph borders. The 1M subset is a prefix slice of the 10M build; 10M and 100M were built separately with the same recipe, so they are **not** guaranteed to be subsets of each other (a later fix to the end-of-document check, which wrongly rejected Wikipedia articles that end in a heading, was only applied to sources rebuilt for the 100M run).
154
+ 7. **Run safety nets** (used to build the larger subsets without manual tuning): a probe per source picks a starting filter strictness, strictness relaxes in up to three logged steps when yield is too low, and shortfalls go to substitute sources.
155
+
156
+ Thresholds were calibrated on real data: the first values (95% coverage in the top 5k words, Flesch-Kincaid <= 5 for everything)
157
+ accepted only 3% of SimpleStories and 0.6% of Cosmopedia v2, so they were relaxed as described above.
158
+
159
+ ## Sources and licensing
160
+
161
+ | Source | License | Role |
162
+ |---|---|---|
163
+ | [TinyStories V2 (GPT-4 split)](https://huggingface.co/datasets/roneneldan/TinyStories) | CDLA-Sharing-1.0 | child-level stories |
164
+ | [SimpleStories](https://huggingface.co/datasets/SimpleStories/SimpleStories) | MIT | varied simple stories |
165
+ | [Cosmopedia v0.1, `stories`](https://huggingface.co/datasets/HuggingFaceTB/cosmopedia) | Apache-2.0 | everyday stories |
166
+ | [TinyDialogues](https://huggingface.co/datasets/styfeng/TinyDialogues) | MIT | child-directed dialogue |
167
+ | [SODA](https://huggingface.co/datasets/allenai/soda) | CC-BY-4.0 | social dialogue |
168
+ | [UltraChat 200k](https://huggingface.co/datasets/HuggingFaceH4/ultrachat_200k) | MIT | user/assistant chat |
169
+ | [SmolTalk (everyday-conversations, smol-summarize, smol-rewrite)](https://huggingface.co/datasets/HuggingFaceTB/smoltalk) | Apache-2.0 | chat, summaries, rewrites |
170
+ | [TinyHelen Leaner-Pretrain (book, conversation, textbook, web, wiki)](https://huggingface.co/datasets/EmpathYang/TinyHelen) | MIT | simplified real text |
171
+ | [Simple English Wikipedia (20231101.simple)](https://huggingface.co/datasets/wikimedia/wikipedia) | CC-BY-SA-3.0 / GFDL | encyclopedic, simple |
172
+ | [Cosmopedia v2 (SmolLM-Corpus)](https://huggingface.co/datasets/HuggingFaceTB/smollm-corpus) | Apache-2.0 (corpus: ODC-By) | synthetic textbooks, blogs, stories |
173
+ | [Cosmopedia v0.1 (wikihow, khanacademy, openstax)](https://huggingface.co/datasets/HuggingFaceTB/cosmopedia) | Apache-2.0 | procedural and didactic |
174
+ | [tiny-textbooks (`textbook` column)](https://huggingface.co/datasets/nampdn-ai/tiny-textbooks) | Apache-2.0 | short synthetic lessons |
175
+ | [FineWeb-Edu (sample-10BT, score >= 4)](https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu) | ODC-By-1.0 | educational web |
176
+ | [Project Gutenberg (English books)](https://huggingface.co/datasets/manu/project_gutenberg) | Project Gutenberg License (public domain in the US) | classic books |
177
+ | [Gutenberg Poetry Corpus](https://huggingface.co/datasets/biglam/gutenberg-poetry-corpus) | CC0-1.0 | poetry stanzas |
178
+ | [CNN/DailyMail 3.0.0](https://huggingface.co/datasets/abisee/cnn_dailymail) | Apache-2.0 (articles are (c) CNN / Daily Mail) | news |
179
+
180
+ **Licensing and attribution.** This repository is a derivative compilation of the datasets above; each document keeps the
181
+ license of its `source`. Obligations that matter when redistributing or reusing it:
182
+
183
+ - Attribution is required for CC-BY / ODC-By / CDLA sources (listed above).
184
+ - The Wikipedia part (`simplewiki`) is **CC-BY-SA-3.0 / GFDL (share-alike)**. If you need a share-alike-free corpus, filter out `source == "simplewiki"`.
185
+ - Cosmopedia, SmolTalk, UltraChat, TinyStories, SimpleStories, TinyHelen and tiny-textbooks contain **model-generated text**; check the terms of the generating model (GPT-4, GPT-4o-mini, Mixtral and others) for your use case.
186
+ - CNN/DailyMail articles and FineWeb-Edu web pages are third-party content; they are included under the dataset licenses above, which do not transfer rights from the original publishers.
187
+ - Project Gutenberg texts had the Project Gutenberg header and footer removed; they are public domain in the United States, check your jurisdiction.
188
+
189
+ No personal data was added; e-mails, phone numbers and URLs were removed, but residual personal information in web-derived sources cannot be ruled out.
190
+
191
+ ## Sanity-check training runs
192
+
193
+ Small GPTs (nanoGPT-style, own byte-level BPE trained on each training set) trained for the same number of steps within each size (17M parameters for 10M words, 46M for 100M words), scored in **bits per byte** (lower is better, comparable across tokenizers) on the held-out validation splits of **this** dataset. Baselines take the first 10M / 100M words of a single source with only `ftfy` cleaning. They are out of distribution on the genres they do not cover, so the table shows how much genre coverage matters, not a leaderboard. One seed, no tuning; the 10M and 100M rows are not comparable with each other.
194
+
195
+ | Training data | Params | Train tokens | narrative | dialogue | expository | books | news | poetry |
196
+ |---|---|---|---|---|---|---|---|---|
197
+ | tinymix 10M | 17.41M | 14.11M | 0.833 | 0.792 | 1.278 | n/a | n/a | n/a |
198
+ | TinyStories only, 10M words | 17.41M | 12.05M | 1.111 | 2.512 | 2.708 | n/a | n/a | n/a |
199
+ | FineWeb-Edu only, 10M words | 17.41M | 15.71M | 1.639 | 1.769 | 1.565 | n/a | n/a | n/a |
200
+ | tinymix 100M | 46.29M | 137.02M | 0.731 | 0.721 | 1.043 | 1.401 | 1.456 | 1.843 |
201
+
202
+ ## Limitations
203
+
204
+ - **Not done**: perplexity filtering with an n-gram LM, LLM-judge coherence scoring, semantic deduplication, cluster caps and benchmark decontamination. Expect some residual near-duplicates and some low-quality documents.
205
+ - Some `tinyhelen` chunks start mid-thought, because the simplified web and book documents are chunks of longer texts.
206
+ - Synthetic sources share model-specific style and topics (names, morals, classroom settings). The anti-template cap reduces this but does not remove it.
207
+ - The toxicity filter is a short word list, not a classifier. Chat and web sources can still contain mildly sensitive content.
208
+ - English only, mostly simple modern language; it is a poor fit for models meant to handle technical, legal or archaic text.
209
+ - Word counts are whitespace words; token counts depend on your tokenizer.
210
+
211
+ ## Reproduce
212
+
213
+ `code/` contains the build scripts (`mix.py` quotas and tiers, `sources.py` adapters, `build.py` pipeline, `assemble.py`,
214
+ `publish.py`, `train.py` for the sanity-check runs) and `requirements.txt`. Building a subset: `python build.py 10M`,
215
+ then `python assemble.py 10M`. The build streams the source datasets from the Hub.
216
+
217
+ ## Acknowledgements
218
+
219
+ Built on the work behind TinyStories, SimpleStories, TinyDialogues, SODA, UltraChat, SmolTalk and SmolLM-Corpus
220
+ (Cosmopedia, FineWeb-Edu), TinyHelen, tiny-textbooks, Project Gutenberg, the Gutenberg Poetry Corpus, Wikipedia and
221
+ CNN/DailyMail. Please cite the original datasets when you use this one.
code/assemble.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Assemble a size: python assemble.py 10M
2
+
3
+ Shuffles documents with a fixed seed, holds out 0.5% per genre as validation,
4
+ writes out/<size>/train.txt (docs separated by <|endoftext|>) and valid_<genre>.txt.
5
+ """
6
+ import json
7
+ import random
8
+ import sys
9
+ from collections import defaultdict
10
+ from pathlib import Path
11
+
12
+ ROOT = Path(__file__).resolve().parent.parent
13
+ EOT = "<|endoftext|>"
14
+
15
+
16
+ # 1M is a prefix slice of the 10M build (million words per source)
17
+ QUOTAS_1M = {"tinystories": 0.19, "simplestories": 0.19, "tinydialogues": 0.12, "soda": 0.10,
18
+ "tinyhelen": 0.15, "simplewiki": 0.10, "cosmo_v2": 0.10, "cosmo_v01": 0.05}
19
+
20
+
21
+ def load(size):
22
+ docs = []
23
+ if size == "1M":
24
+ for name, q in QUOTAS_1M.items():
25
+ n = 0
26
+ for l in (ROOT / "work" / "10M" / f"{name}.jsonl").open(encoding="utf-8"):
27
+ d = json.loads(l)
28
+ if n >= q * 1e6:
29
+ break
30
+ n += len(d["text"].split())
31
+ docs.append(d)
32
+ return docs
33
+ for p in sorted((ROOT / "work" / size).glob("*.jsonl")):
34
+ docs += [json.loads(l) for l in p.open(encoding="utf-8")]
35
+ return docs
36
+
37
+
38
+ def main():
39
+ size = sys.argv[1]
40
+ docs = load(size)
41
+ random.Random(0).shuffle(docs)
42
+ out = ROOT / "out" / size
43
+ out.mkdir(parents=True, exist_ok=True)
44
+ valid, held = defaultdict(list), defaultdict(int)
45
+ n_genre = defaultdict(int)
46
+ for d in docs:
47
+ n_genre[d["genre"]] += 1
48
+ train, words, by_genre, by_source = [], 0, defaultdict(int), defaultdict(int)
49
+ valid_docs = defaultdict(list)
50
+ for d in docs:
51
+ g = d["genre"]
52
+ if held[g] < max(1, n_genre[g] // 200):
53
+ held[g] += 1
54
+ valid[g].append(d["text"])
55
+ valid_docs[g].append(d)
56
+ else:
57
+ train.append(d)
58
+ n = len(d["text"].split())
59
+ by_genre[g] += n
60
+ by_source[d["src"].split(".")[0]] += n
61
+ words += n
62
+ sep = f"\n{EOT}\n"
63
+ (out / "train.txt").write_text(sep.join(d["text"] for d in train) + sep, encoding="utf-8")
64
+ for g, ts in valid.items():
65
+ (out / f"valid_{g}.txt").write_text(sep.join(ts) + sep, encoding="utf-8")
66
+ # parquet with provenance, for the Hugging Face release
67
+ import pyarrow as pa
68
+ import pyarrow.parquet as pq
69
+ pq_dir = out / "parquet"
70
+ pq_dir.mkdir(exist_ok=True)
71
+
72
+ def write(name, ds):
73
+ pq.write_table(pa.table({"text": [d["text"] for d in ds], "source": [d["src"].split(".")[0] for d in ds],
74
+ "genre": [d["genre"] for d in ds]}), pq_dir / f"{name}.parquet", compression="zstd")
75
+
76
+ write("train", train)
77
+ for g, ds in valid_docs.items():
78
+ write(f"validation_{g}", ds)
79
+ summary = {"size": size, "train_docs": len(train), "train_words_M": round(words / 1e6, 2),
80
+ "genre_share_%": {g: round(100 * w / words, 1) for g, w in by_genre.items()},
81
+ "source_words_M": {s: round(w / 1e6, 3) for s, w in sorted(by_source.items())}}
82
+ (out / "summary.json").write_text(json.dumps(summary, indent=1))
83
+ print(json.dumps(summary, indent=1))
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
code/baselines.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Single-source baselines of the same size, for comparison with the mix.
2
+
3
+ python baselines.py 10M -> out/base_tinystories_10M, out/base_fineweb_edu_10M
4
+ Light cleaning only (ftfy + whitespace), no mix, no complexity or dedup filters:
5
+ this is what someone would get by just taking the dataset.
6
+ """
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ ROOT = Path(__file__).resolve().parent.parent
12
+ _env = ROOT / ".env"
13
+ if _env.exists():
14
+ for _l in _env.read_text(encoding="utf-8").splitlines():
15
+ if "=" in _l and not _l.lstrip().startswith("#"):
16
+ _k, _v = _l.split("=", 1)
17
+ os.environ.setdefault(_k.strip(), _v.strip().strip("'\""))
18
+
19
+ import ftfy
20
+ from datasets import load_dataset
21
+ from huggingface_hub import HfFileSystem
22
+
23
+ EOT = "<|endoftext|>"
24
+
25
+
26
+ def tinystories():
27
+ buf = []
28
+ with HfFileSystem().open("datasets/roneneldan/TinyStories/TinyStoriesV2-GPT4-train.txt", "r",
29
+ encoding="utf-8", errors="replace") as f:
30
+ for line in f:
31
+ if EOT in line:
32
+ if buf:
33
+ yield " ".join(buf)
34
+ buf = []
35
+ else:
36
+ buf.append(line.strip())
37
+
38
+
39
+ def fineweb_edu():
40
+ for r in load_dataset("HuggingFaceFW/fineweb-edu", "sample-10BT", split="train", streaming=True):
41
+ if r["int_score"] >= 4:
42
+ yield r["text"]
43
+
44
+
45
+ SOURCES = {"tinystories": tinystories, "fineweb_edu": fineweb_edu}
46
+
47
+
48
+ def main():
49
+ size = sys.argv[1]
50
+ target = {"10M": 10e6, "100M": 100e6}[size]
51
+ for name, gen in SOURCES.items():
52
+ if len(sys.argv) > 2 and name not in sys.argv[2:]:
53
+ continue
54
+ out = ROOT / "out" / f"base_{name}_{size}"
55
+ out.mkdir(parents=True, exist_ok=True)
56
+ words, n = 0, 0
57
+ with (out / "train.txt").open("w", encoding="utf-8") as f:
58
+ for text in gen():
59
+ text = ftfy.fix_text(text).strip()
60
+ if not text:
61
+ continue
62
+ f.write(text + f"\n{EOT}\n")
63
+ words += len(text.split())
64
+ n += 1
65
+ if words >= target:
66
+ break
67
+ print(f"{name} {size}: {words/1e6:.2f}M words, {n} docs", flush=True)
68
+
69
+
70
+ if __name__ == "__main__":
71
+ main()
code/build.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build one size of the dataset: python build.py 10M [source ...]
2
+
3
+ Per source: stream -> clean -> filter -> dedup until the word quota is met.
4
+ Output: work/<size>/<source>.jsonl, then assemble.py slices train/valid.
5
+ """
6
+ import hashlib
7
+ import itertools
8
+ import json
9
+ import os
10
+ import re
11
+ import sys
12
+ import time
13
+ import unicodedata
14
+ from collections import Counter
15
+ from pathlib import Path
16
+
17
+ ROOT = Path(__file__).resolve().parent.parent
18
+ # HF_TOKEN lives in ../.env (never printed); must be set before importing datasets
19
+ _env = ROOT / ".env"
20
+ if _env.exists():
21
+ for _l in _env.read_text(encoding="utf-8").splitlines():
22
+ if "=" in _l and not _l.lstrip().startswith("#"):
23
+ _k, _v = _l.split("=", 1)
24
+ os.environ.setdefault(_k.strip(), _v.strip().strip("'\""))
25
+
26
+ import fasttext
27
+ import ftfy
28
+ from datasketch import MinHash, MinHashLSH
29
+ from wordfreq import top_n_list
30
+
31
+ import mix
32
+ import sources
33
+
34
+ QUOTES = str.maketrans({"‘": "'", "’": "'", "“": '"', "”": '"',
35
+ "–": "-", "—": " - ", "…": "...", " ": " "})
36
+ RE_URL = re.compile(r"https?://\S+|www\.\S+")
37
+ RE_EMAIL = re.compile(r"\S+@\S+\.\S+")
38
+ RE_PHONE = re.compile(r"\+?\d[\d\s().-]{8,}\d")
39
+ RE_HTML = re.compile(r"<[^>]{1,100}>")
40
+ RE_CODE = re.compile(r"```.*?```", re.S)
41
+ RE_HEAD = re.compile(r"^#{1,6}\s*", re.M)
42
+ RE_LATEX = re.compile(r"\$\$.*?\$\$|\\\(.*?\\\)|\\\[.*?\\\]", re.S)
43
+ LLM_TICS = re.compile(r"\bas an ai\b|\bdelve\b|\btapestry\b|\bcertainly!|\bin conclusion,|"
44
+ r"\bit'?s important to note\b|\bbustling\b|\bas a language model\b", re.I)
45
+ # deliberately small: only terms that are unambiguous in any context
46
+ BAD = re.compile(r"\b(fuck\w*|shit\w*|bitch\w*|cunt|porn\w*|nigg\w+|rape[sd]?|raping|"
47
+ r"cock|dick|pussy|slut|whore|orgasm\w*|erotic\w*|blowjob|masturbat\w*)\b", re.I)
48
+ STOP = {"the", "and", "to", "of", "a", "in", "that", "is", "it", "for"}
49
+ END_OK = ('.', '!', '?', '"', "'", ")")
50
+
51
+ lid = fasttext.load_model(str(ROOT / "work" / "lid.176.ftz"))
52
+
53
+
54
+ def normalize(t):
55
+ t = ftfy.fix_text(t).translate(QUOTES)
56
+ t = unicodedata.normalize("NFKC", t)
57
+ for rx in (RE_CODE, RE_LATEX, RE_URL, RE_EMAIL, RE_HTML):
58
+ t = rx.sub(" ", t)
59
+ t = RE_PHONE.sub(" ", t)
60
+ t = RE_HEAD.sub("", t)
61
+ t = re.sub(r"[ \t]+", " ", t)
62
+ t = re.sub(r" ?\n ?", "\n", t)
63
+ t = re.sub(r"\n{3,}", "\n\n", t)
64
+ return t.strip()
65
+
66
+
67
+ def syllables(w):
68
+ n = len(re.findall(r"[aeiouy]+", w))
69
+ if w.endswith("e") and n > 1 and not w.endswith("le"):
70
+ n -= 1
71
+ return max(n, 1)
72
+
73
+
74
+ def fk_grade(text):
75
+ words = re.findall(r"[A-Za-z']+", text)
76
+ sents = max(len(re.findall(r"[.!?]+(?:\s|$)", text)), 1)
77
+ if not words:
78
+ return 99
79
+ syl = sum(syllables(w.lower()) for w in words)
80
+ return 0.39 * len(words) / sents + 11.8 * syl / len(words) - 15.59
81
+
82
+
83
+ def vocab_coverage(text, vocab):
84
+ # capitalised words (names, sentence starts) never match, so they are ignored
85
+ toks = re.findall(r"\b[a-z']+\b", text)
86
+ return sum(t in vocab for t in toks) / len(toks) if toks else 0
87
+
88
+
89
+ def gopher_ok(text):
90
+ words = text.split()
91
+ if not words:
92
+ return False
93
+ if not 3 <= sum(map(len, words)) / len(words) <= 10:
94
+ return False
95
+ if sum(not c.isalnum() and not c.isspace() and c not in ".,;:!?'\"()-" for c in text) / len(text) > 0.1:
96
+ return False
97
+ if sum(c.isdigit() for c in text) / len(text) > 0.1:
98
+ return False
99
+ lines = [l for l in text.split("\n") if l.strip()]
100
+ if len(lines) > 3 and 1 - len(set(lines)) / len(lines) > 0.3:
101
+ return False
102
+ if sum(w.lower().strip(".,!?\"'") in STOP for w in words) < 2:
103
+ return False
104
+ bi = Counter(zip(words, words[1:]))
105
+ return not bi or bi.most_common(1)[0][1] / max(len(words) - 1, 1) <= 0.2
106
+
107
+
108
+ def is_english(text):
109
+ # lid.f.predict avoids fasttext's numpy-1 only wrapper; returns [(prob, label)]
110
+ pred = lid.f.predict(text[:1000].replace("\n", " ") + "\n", 1, 0.0, "strict")
111
+ return bool(pred) and pred[0][1] == "__label__en" and pred[0][0] >= 0.9
112
+
113
+
114
+ def split_long(text, title, doc_max):
115
+ """Split at paragraph borders; the title is repeated so each chunk stays self-contained."""
116
+ paras, chunks, cur, n = text.split("\n"), [], [], 0
117
+ for p in paras:
118
+ w = len(p.split())
119
+ if cur and n + w > doc_max:
120
+ chunks.append("\n".join(cur))
121
+ cur, n = [], 0
122
+ cur.append(p)
123
+ n += w
124
+ if cur:
125
+ chunks.append("\n".join(cur))
126
+ return [(f"{title}\n{c}" if title else c) for c in chunks if len(c.split()) >= mix.DOC_MIN]
127
+
128
+
129
+ class Dedup:
130
+ def __init__(self):
131
+ self.exact, self.lsh, self.n = set(), MinHashLSH(threshold=0.8, num_perm=64), 0
132
+
133
+ def seen(self, text):
134
+ h = hashlib.md5(re.sub(r"\W+", "", text.lower()).encode()).hexdigest()
135
+ if h in self.exact:
136
+ return True
137
+ self.exact.add(h)
138
+ w = text.lower().split()
139
+ mh = MinHash(num_perm=64)
140
+ mh.update_batch([" ".join(w[i:i + 5]).encode() for i in range(max(len(w) - 4, 1))])
141
+ if self.lsh.query(mh):
142
+ return True
143
+ self.lsh.insert(str(self.n), mh)
144
+ self.n += 1
145
+ return False
146
+
147
+
148
+ def trim_tail(text):
149
+ """Drop trailing headings and list stubs ("Other websites", "References") so a complete
150
+ article is not rejected as truncated; real truncation leaves a long unfinished last line."""
151
+ lines = text.split("\n")
152
+ while len(lines) > 1 and (not lines[-1].strip() or
153
+ (len(lines[-1].split()) < 12 and not lines[-1].rstrip().endswith(END_OK))):
154
+ lines.pop()
155
+ return "\n".join(lines).strip()
156
+
157
+
158
+ def process(doc, genre, tier, vocab, src_name, cov):
159
+ """Return (clean documents, None) or ([], rejection reason)."""
160
+ if "turns" in doc:
161
+ turns = [(s.strip(), normalize(t)) for s, t in doc["turns"]]
162
+ turns = [(s, t.replace("\n", " ")) for s, t in turns if t]
163
+ # assistant chats (User/Assistant) include 2-turn tasks (summarise, rewrite) and long answers,
164
+ # so they get a lower turn minimum and a looser per-turn cap than named dialogues
165
+ chat = all(s in ("User", "Assistant") for s, _ in turns)
166
+ if len(turns) < (2 if chat else 4) or any(len(s) > 20 for s, _ in turns):
167
+ return [], "dialogue_shape"
168
+ if sum(len(t.split()) for _, t in turns) / len(turns) > tier["turn"] * (mix.CHAT_TURN_MULT if chat else 1):
169
+ return [], "turn_length"
170
+ text = "\n".join(f"{s}: {t}" for s, t in turns)
171
+ title = None
172
+ else:
173
+ text, title = normalize(doc["text"]), doc.get("title")
174
+ if "�" in text:
175
+ return [], "mojibake"
176
+ if genre != "poetry":
177
+ text = trim_tail(text)
178
+ nw = len(text.split())
179
+ if genre == "poetry":
180
+ if nw < 20:
181
+ return [], "short"
182
+ return ([text], None) if is_english(text) else ([], "lang")
183
+ if nw < mix.DOC_MIN:
184
+ return [], "short"
185
+ if len(LLM_TICS.findall(text)) > 2:
186
+ return [], "llm_tics"
187
+ if BAD.search(text):
188
+ return [], "explicit"
189
+ if src_name not in mix.LID_SKIP and not is_english(text):
190
+ return [], "lang"
191
+ if not text.rstrip().endswith(END_OK):
192
+ return [], "truncated"
193
+ if not gopher_ok(text):
194
+ return [], "gopher"
195
+ if genre != "dialogue":
196
+ cap = tier["fk_exp"] if genre == "expository" else tier["fk"]
197
+ if fk_grade(text) > cap and src_name not in ("simplewiki",):
198
+ return [], "fk"
199
+ if vocab_coverage(text, vocab) < cov:
200
+ return [], "vocab"
201
+ docs = split_long(text, title, tier["doc_max"]) if nw > tier["doc_max"] else [f"{title}\n{text}" if title else text]
202
+ return docs, (None if docs else "short")
203
+
204
+
205
+ def doc_words(doc):
206
+ return len(doc["text"].split()) if "text" in doc else sum(len(t.split()) for _, t in doc["turns"])
207
+
208
+
209
+ def at_step(tier, step):
210
+ """Tier and vocabulary-coverage threshold at a relaxation-ladder step."""
211
+ dfk, dcov = mix.LADDER[step]
212
+ return dict(tier, fk=tier["fk"] + dfk, fk_exp=tier["fk_exp"] + dfk), mix.VOCAB_COVERAGE + dcov
213
+
214
+
215
+ def probe(name, size, genre, tier, vocab, quota):
216
+ """Mechanism 1: sample the first docs and pick the first ladder step whose projected
217
+ scan fits comfortably in the budget (yield >= 2/MAX_SCAN). Returns (step, report)."""
218
+ docs = list(itertools.islice(sources.REGISTRY[name](size), mix.PROBE_DOCS))
219
+ scanned = sum(doc_words(d) for d in docs) or 1
220
+ report = []
221
+ for step in range(len(mix.LADDER)):
222
+ t, cov = at_step(tier, step)
223
+ rej, kept = Counter(), 0
224
+ for d in docs:
225
+ out, why = process(d, genre, t, vocab, name, cov)
226
+ kept += sum(len(x.split()) for x in out)
227
+ if why:
228
+ rej[why] += 1
229
+ yield_ = kept / scanned
230
+ report.append(dict(step=step, yield_pct=round(100 * yield_, 1), top_rejections=rej.most_common(3)))
231
+ if yield_ >= 2 / mix.MAX_SCAN:
232
+ return step, report
233
+ return len(mix.LADDER) - 1, report
234
+
235
+
236
+ def build_source(name, size, dedup, quota=None, tag=""):
237
+ """Fill one source's quota. `tag=".topup"` writes an extra file for fallback top-ups."""
238
+ genre, quotas = mix.MIX[name]
239
+ if quota is None:
240
+ quota = quotas[mix.SIZES[size]] * 1_000_000
241
+ if quota <= 0:
242
+ return None
243
+ out = ROOT / "work" / size / f"{name}{tag}.jsonl"
244
+ done = out.with_suffix(".done")
245
+ if done.exists():
246
+ stats = json.loads(done.read_text())
247
+ if abs(stats["target_M"] - quota / 1e6) < 1e-6:
248
+ for l in out.open(encoding="utf-8"): # reload so global dedup stays consistent
249
+ dedup.seen(json.loads(l)["text"])
250
+ return stats
251
+ base = mix.TIERS[size]
252
+ vocab = set(top_n_list("en", base["vocab"]))
253
+ t0 = time.time()
254
+ step, probe_report = probe(name, size, genre, base, vocab, quota)
255
+ print(f" probe {name}{tag}: start at ladder step {step}; {probe_report[-1]}", flush=True)
256
+ tier, cov = at_step(base, step)
257
+ got = scanned = kept = seen_docs = 0
258
+ openers, rej = Counter(), Counter()
259
+ win_scanned = win_kept = win_docs = 0
260
+ relaxed, abort = [dict(step=step, at_words=0)], None
261
+ with out.open("w", encoding="utf-8") as f:
262
+ for doc in sources.REGISTRY[name](size):
263
+ seen_docs += 1
264
+ win_docs += 1
265
+ w = doc_words(doc)
266
+ scanned += w
267
+ win_scanned += w
268
+ if scanned > quota * mix.MAX_SCAN:
269
+ abort = "scan_cap"
270
+ break
271
+ docs, why = process(doc, genre, tier, vocab, name, cov)
272
+ if why:
273
+ rej[why] += 1
274
+ for text in docs:
275
+ # anti-template: no 4-word opening may exceed 0.5% of the accepted docs
276
+ op = " ".join(text.lower().split()[:4])
277
+ if genre != "poetry" and openers[op] >= max(5, 0.005 * kept):
278
+ rej["opener_cap"] += 1
279
+ continue
280
+ if dedup.seen(text):
281
+ rej["duplicate"] += 1
282
+ continue
283
+ openers[op] += 1
284
+ kept += 1
285
+ n = len(text.split())
286
+ got += n
287
+ win_kept += n
288
+ f.write(json.dumps({"text": text, "genre": genre, "src": name}) + "\n")
289
+ if got >= quota:
290
+ break
291
+ if seen_docs % 2000 == 0:
292
+ print(f" {name}{tag}: {seen_docs} docs, kept {kept}, {got/1e6:.2f}M/{quota/1e6:.2f}M words, "
293
+ f"{time.time()-t0:.0f}s, top rejections {rej.most_common(3)}", flush=True)
294
+ if win_docs >= mix.WINDOW:
295
+ # mechanisms 2+4: if the recent yield cannot finish within the scan budget,
296
+ # climb one ladder step; at the top of the ladder give up on this source
297
+ recent = win_kept / win_scanned if win_scanned else 0
298
+ need = (quota - got) / recent if recent else float("inf")
299
+ if need > quota * mix.MAX_SCAN - scanned:
300
+ if step + 1 < len(mix.LADDER):
301
+ step += 1
302
+ tier, cov = at_step(base, step)
303
+ relaxed.append(dict(step=step, at_words=got))
304
+ print(f" {name}{tag}: yield {100*recent:.1f}% too low, relaxing to step {step}", flush=True)
305
+ else:
306
+ abort = "projected_shortfall"
307
+ break
308
+ win_scanned = win_kept = win_docs = 0
309
+ stats = dict(source=name + tag, genre=genre, target_M=quota / 1e6, words_M=round(got / 1e6, 3),
310
+ docs=kept, scanned_docs=seen_docs, scanned_words_M=round(scanned / 1e6, 1),
311
+ seconds=round(time.time() - t0), stopped="quota" if got >= quota else (abort or "source_exhausted"),
312
+ relaxation=relaxed, probe=probe_report, rejections=dict(rej.most_common()))
313
+ done.write_text(json.dumps(stats))
314
+ return stats
315
+
316
+
317
+ def plan_fallbacks(size, results):
318
+ """Mechanism 3: spread each source's shortfall over same-genre substitutes, capped."""
319
+ idx = mix.SIZES[size]
320
+ quota = {n: q[idx] * 1e6 for n, (_, q) in mix.MIX.items()}
321
+ target = sum(quota.values())
322
+ got = {r["source"]: r["words_M"] * 1e6 for r in results if "words_M" in r}
323
+ extra, plan, log = Counter(), Counter(), []
324
+ for src, q in quota.items():
325
+ gap = q - got.get(src, 0) if q > 0 else 0
326
+ if gap < 0.01 * q:
327
+ continue
328
+ for sub in mix.FALLBACKS.get(src, []):
329
+ if gap <= 0:
330
+ break
331
+ room = max(mix.EXTRA_FRAC * quota[sub], mix.EXTRA_FLOOR * target) - extra[sub]
332
+ room = min(room, mix.SHARE_CAP * target - got.get(sub, 0) - extra[sub])
333
+ amt = min(gap, room)
334
+ if amt < 0.005 * target:
335
+ continue
336
+ extra[sub] += amt
337
+ plan[sub] += amt
338
+ gap -= amt
339
+ log.append(dict(missing_from=src, filled_by=sub, words_M=round(amt / 1e6, 3)))
340
+ if gap > 0:
341
+ log.append(dict(missing_from=src, unfilled_M=round(gap / 1e6, 3)))
342
+ return plan, log
343
+
344
+
345
+ def main():
346
+ size = sys.argv[1]
347
+ only = sys.argv[2:]
348
+ (ROOT / "work" / size).mkdir(parents=True, exist_ok=True)
349
+ dedup, results = Dedup(), []
350
+
351
+ def run(name, **kw):
352
+ print(f"== {name}{kw.get('tag', '')}", flush=True)
353
+ try:
354
+ r = build_source(name, size, dedup, **kw)
355
+ except Exception as e: # keep going; a failed source is reported, not hidden
356
+ print(f" FAILED {name}: {e!r}", flush=True)
357
+ r = dict(source=name + kw.get("tag", ""), error=repr(e))
358
+ if r:
359
+ print(" ", {k: v for k, v in r.items() if k not in ("probe", "relaxation")}, flush=True)
360
+ results.append(r)
361
+
362
+ for name in mix.MIX:
363
+ if not only or name in only:
364
+ run(name)
365
+ fallback_log = []
366
+ if not only:
367
+ plan, fallback_log = plan_fallbacks(size, [r for r in results if "tag" not in r])
368
+ print("== fallback plan", fallback_log, flush=True)
369
+ for sub, words in plan.items():
370
+ run(sub, quota=words, tag=".topup")
371
+ total = sum(r.get("words_M", 0) for r in results)
372
+ print(f"== total {total:.2f}M words", flush=True)
373
+ (ROOT / "work" / size / "stats.json").write_text(
374
+ json.dumps(dict(total_M=round(total, 3), fallbacks=fallback_log, sources=results), indent=1))
375
+
376
+
377
+ if __name__ == "__main__":
378
+ main()
code/mix.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mix definition: million words per source for the 10M / 100M / 1000M versions."""
2
+
3
+ SIZES = {"10M": 0, "100M": 1, "1000M": 2}
4
+
5
+ # key: (genre, (10M, 100M, 1000M) quota in million words)
6
+ MIX = {
7
+ "tinystories": ("narrative", (1.5, 8, 40)),
8
+ "simplestories": ("narrative", (2.0, 8, 60)),
9
+ "cosmo_stories": ("narrative", (0, 5, 50)),
10
+ "tinydialogues": ("dialogue", (1.5, 7, 29)),
11
+ "soda": ("dialogue", (1, 9, 75)),
12
+ "ultrachat": ("dialogue", (0, 4, 61)),
13
+ "smoltalk": ("dialogue", (0, 1, 25)),
14
+ "tinyhelen": ("expository", (1.5, 10, 50)),
15
+ "simplewiki": ("expository", (1, 10, 30)),
16
+ "enwiki_intro": ("expository", (0, 0, 50)),
17
+ "cosmo_v2": ("expository", (1, 12, 180)),
18
+ "tiny_textbooks": ("expository", (0, 4, 40)), # uses the synthetic `textbook` column
19
+ "cosmo_v01": ("expository", (0.5, 3, 30)),
20
+ "fineweb_edu": ("expository", (0, 9, 180)),
21
+ "gutenberg_books": ("books", (0, 8, 70)),
22
+ "poetry": ("poetry", (0, 1, 10)),
23
+ "cnn": ("news", (0, 1, 20)),
24
+ }
25
+
26
+ # Complexity tiers per size: reference vocab size, max Flesch-Kincaid grade,
27
+ # document length range (words), max average words per dialogue turn.
28
+ TIERS = {
29
+ "10M": dict(vocab=8000, fk=5, fk_exp=9, doc_max=600, turn=25),
30
+ "100M": dict(vocab=15000, fk=8, fk_exp=10, doc_max=1200, turn=40),
31
+ "1000M": dict(vocab=30000, fk=12, fk_exp=12, doc_max=2000, turn=80),
32
+ }
33
+ # fk_exp: expository text (Cosmopedia textbooks) has median grade ~11 even for school
34
+ # audiences, so fk=5 passed 0.2% of it. Vocabulary coverage still guards simplicity.
35
+ # Assistant chats may average this many times the per-turn word cap of a named dialogue.
36
+ CHAT_TURN_MULT = 4
37
+
38
+ # --- run safety nets (see build.py) ---
39
+ # Relaxation ladder: (extra Flesch-Kincaid grades, change to vocabulary coverage).
40
+ LADDER = [(0, 0.0), (1, -0.02), (2, -0.04), (3, -0.06)]
41
+ PROBE_DOCS = 1000 # docs sampled before a source starts, to pick the starting ladder step
42
+ WINDOW = 5000 # docs per yield check while a source runs
43
+ MAX_SCAN = 40 # hard cap: raw words scanned per source = MAX_SCAN x its quota
44
+ # When a source falls short, same-genre substitutes make up the difference in order.
45
+ # A substitute may add at most max(EXTRA_FRAC x its quota, EXTRA_FLOOR x total target)
46
+ # and never end above SHARE_CAP x total target.
47
+ EXTRA_FRAC, EXTRA_FLOOR, SHARE_CAP = 0.5, 0.05, 0.35
48
+ FALLBACKS = {
49
+ "tinystories": ["simplestories", "cosmo_stories"],
50
+ "simplestories": ["tinystories", "cosmo_stories"],
51
+ "cosmo_stories": ["simplestories", "tinystories"],
52
+ "tinydialogues": ["soda", "smoltalk"],
53
+ "soda": ["tinydialogues", "ultrachat", "smoltalk"],
54
+ "ultrachat": ["smoltalk", "soda"],
55
+ "smoltalk": ["ultrachat", "soda"],
56
+ "tinyhelen": ["tiny_textbooks", "cosmo_v2", "fineweb_edu"],
57
+ "simplewiki": ["tiny_textbooks", "tinyhelen", "cosmo_v2"],
58
+ "enwiki_intro": ["cosmo_v2", "tiny_textbooks", "fineweb_edu"],
59
+ "cosmo_v2": ["tiny_textbooks", "tinyhelen", "fineweb_edu"],
60
+ "cosmo_v01": ["tiny_textbooks", "cosmo_v2", "tinyhelen"],
61
+ "fineweb_edu": ["cosmo_v2", "tiny_textbooks", "tinyhelen"],
62
+ "gutenberg_books": ["tinyhelen", "fineweb_edu"],
63
+ "poetry": [],
64
+ "cnn": ["fineweb_edu", "cosmo_v2"],
65
+ }
66
+
67
+ # min share of (lowercase) tokens inside the reference vocab. The original 95% @ top-5k
68
+ # passed only 3% of SimpleStories and 35% of TinyStories, so it is 90% with larger vocabs.
69
+ VOCAB_COVERAGE = 0.90
70
+ # English-only by construction and made of one-word toddler turns, which fastText misreads
71
+ LID_SKIP = {"tinydialogues"}
72
+ DOC_MIN = 80
code/publish.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the Hugging Face release folder (card + parquet + code) and optionally upload it.
2
+
3
+ python publish.py # stage only: out/hf/
4
+ python publish.py --upload # stage and push to a PRIVATE dataset repo (flip to public in the HF UI)
5
+ """
6
+ import json
7
+ import os
8
+ import shutil
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ ROOT = Path(__file__).resolve().parent.parent
13
+ REPO = "jncarlo/tinymix"
14
+ SIZES = ["1M", "10M", "100M"]
15
+ GENRES = ["narrative", "dialogue", "expository", "books", "poetry", "news"]
16
+
17
+ # source key -> (display name, link, license, role)
18
+ SOURCES = {
19
+ "tinystories": ("TinyStories V2 (GPT-4 split)", "https://huggingface.co/datasets/roneneldan/TinyStories", "CDLA-Sharing-1.0", "child-level stories"),
20
+ "simplestories": ("SimpleStories", "https://huggingface.co/datasets/SimpleStories/SimpleStories", "MIT", "varied simple stories"),
21
+ "cosmo_stories": ("Cosmopedia v0.1, `stories`", "https://huggingface.co/datasets/HuggingFaceTB/cosmopedia", "Apache-2.0", "everyday stories"),
22
+ "tinydialogues": ("TinyDialogues", "https://huggingface.co/datasets/styfeng/TinyDialogues", "MIT", "child-directed dialogue"),
23
+ "soda": ("SODA", "https://huggingface.co/datasets/allenai/soda", "CC-BY-4.0", "social dialogue"),
24
+ "ultrachat": ("UltraChat 200k", "https://huggingface.co/datasets/HuggingFaceH4/ultrachat_200k", "MIT", "user/assistant chat"),
25
+ "smoltalk": ("SmolTalk (everyday-conversations, smol-summarize, smol-rewrite)", "https://huggingface.co/datasets/HuggingFaceTB/smoltalk", "Apache-2.0", "chat, summaries, rewrites"),
26
+ "tinyhelen": ("TinyHelen Leaner-Pretrain (book, conversation, textbook, web, wiki)", "https://huggingface.co/datasets/EmpathYang/TinyHelen", "MIT", "simplified real text"),
27
+ "simplewiki": ("Simple English Wikipedia (20231101.simple)", "https://huggingface.co/datasets/wikimedia/wikipedia", "CC-BY-SA-3.0 / GFDL", "encyclopedic, simple"),
28
+ "enwiki_intro": ("English Wikipedia, lead paragraphs", "https://huggingface.co/datasets/wikimedia/wikipedia", "CC-BY-SA-3.0 / GFDL", "encyclopedic"),
29
+ "cosmo_v2": ("Cosmopedia v2 (SmolLM-Corpus)", "https://huggingface.co/datasets/HuggingFaceTB/smollm-corpus", "Apache-2.0 (corpus: ODC-By)", "synthetic textbooks, blogs, stories"),
30
+ "cosmo_v01": ("Cosmopedia v0.1 (wikihow, khanacademy, openstax)", "https://huggingface.co/datasets/HuggingFaceTB/cosmopedia", "Apache-2.0", "procedural and didactic"),
31
+ "tiny_textbooks": ("tiny-textbooks (`textbook` column)", "https://huggingface.co/datasets/nampdn-ai/tiny-textbooks", "Apache-2.0", "short synthetic lessons"),
32
+ "fineweb_edu": ("FineWeb-Edu (sample-10BT, score >= 4)", "https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu", "ODC-By-1.0", "educational web"),
33
+ "gutenberg_books": ("Project Gutenberg (English books)", "https://huggingface.co/datasets/manu/project_gutenberg", "Project Gutenberg License (public domain in the US)", "classic books"),
34
+ "poetry": ("Gutenberg Poetry Corpus", "https://huggingface.co/datasets/biglam/gutenberg-poetry-corpus", "CC0-1.0", "poetry stanzas"),
35
+ "cnn": ("CNN/DailyMail 3.0.0", "https://huggingface.co/datasets/abisee/cnn_dailymail", "Apache-2.0 (articles are (c) CNN / Daily Mail)", "news"),
36
+ }
37
+
38
+
39
+ def load(size):
40
+ return json.loads((ROOT / "out" / size / "summary.json").read_text())
41
+
42
+
43
+ def tables():
44
+ sums = {s: load(s) for s in SIZES if (ROOT / "out" / s / "summary.json").exists()}
45
+ sizes = list(sums)
46
+ head = "| Subset | Train words | Train docs | ~Tokens (BPE) |\n|---|---|---|---|\n"
47
+ rows = "".join(f"| `{s}` | {v['train_words_M']}M | {v['train_docs']:,} | ~{v['train_words_M']*1.3:.1f}M |\n"
48
+ for s, v in sums.items())
49
+ g = "| Genre | " + " | ".join(sizes) + " |\n|---|" + "---|" * len(sizes) + "\n"
50
+ for gen in GENRES:
51
+ vals = [sums[s]["genre_share_%"].get(gen) for s in sizes]
52
+ if any(vals):
53
+ g += f"| {gen} | " + " | ".join(f"{v or 0}%" for v in vals) + " |\n"
54
+ used = sorted({k for v in sums.values() for k in v["source_words_M"]}, key=lambda k: list(SOURCES).index(k))
55
+ s = "| Source | " + " | ".join(f"{x} (M words)" for x in sizes) + " |\n|---|" + "---|" * len(sizes) + "\n"
56
+ for k in used:
57
+ s += f"| {SOURCES[k][0]} | " + " | ".join(str(sums[x]["source_words_M"].get(k, 0)) for x in sizes) + " |\n"
58
+ lic = "| Source | License | Role |\n|---|---|---|\n" + "".join(
59
+ f"| [{SOURCES[k][0]}]({SOURCES[k][1]}) | {SOURCES[k][2]} | {SOURCES[k][3]} |\n" for k in used)
60
+ return sizes, head + rows, g, s, lic
61
+
62
+
63
+ def results_section():
64
+ runs = ROOT / "runs"
65
+ names = [("10M", "tinymix 10M"), ("base_tinystories_10M", "TinyStories only, 10M words"),
66
+ ("base_fineweb_edu_10M", "FineWeb-Edu only, 10M words"),
67
+ ("100M", "tinymix 100M"), ("base_fineweb_edu_100M", "FineWeb-Edu only, 100M words")]
68
+ rows = []
69
+ for key, label in names:
70
+ p = runs / key / "results.json"
71
+ if p.exists():
72
+ r = json.loads(p.read_text())
73
+ b = r["valid_bits_per_byte"]
74
+ rows.append(f"| {label} | {r['params_M']}M | {r['tokens_M']}M | " +
75
+ " | ".join(f"{b[g]:.3f}" if g in b else "n/a"
76
+ for g in ("narrative", "dialogue", "expository", "books", "news", "poetry")) + " |\n")
77
+ if not rows:
78
+ return ""
79
+ return ("## Sanity-check training runs\n\n"
80
+ "Small GPTs (nanoGPT-style, own byte-level BPE trained on each training set) trained for the same number of "
81
+ "steps within each size (17M parameters for 10M words, 46M for 100M words), scored in **bits per byte** "
82
+ "(lower is better, comparable across tokenizers) on the held-out validation splits of **this** dataset. "
83
+ "Baselines take the first 10M / 100M words of a single source with only `ftfy` cleaning. They are "
84
+ "out of distribution on the genres they do not cover, so the table shows how much genre coverage matters, "
85
+ "not a leaderboard. One seed, no tuning; the 10M and 100M rows are not comparable with each other.\n\n"
86
+ "| Training data | Params | Train tokens | narrative | dialogue | expository | books | news | poetry |\n|---|---|---|---|---|---|---|---|---|\n"
87
+ + "".join(rows) + "\n")
88
+
89
+
90
+ def card():
91
+ sizes, size_t, genre_t, src_t, lic_t = tables()
92
+ configs = ""
93
+ for s in sizes:
94
+ configs += f"- config_name: {s}\n data_files:\n - split: train\n path: data/{s}/train.parquet\n"
95
+ for p in sorted((ROOT / "out" / s / "parquet").glob("validation_*.parquet")):
96
+ configs += f" - split: {p.stem}\n path: data/{s}/{p.name}\n"
97
+ return f"""---
98
+ language:
99
+ - en
100
+ license: other
101
+ license_name: mixed-per-source
102
+ license_link: https://huggingface.co/datasets/{REPO}#sources-and-licensing
103
+ pretty_name: tinymix
104
+ size_categories:
105
+ - 100K<n<1M
106
+ task_categories:
107
+ - text-generation
108
+ tags:
109
+ - small-language-models
110
+ - synthetic-data
111
+ - curriculum
112
+ - tinystories
113
+ - babylm
114
+ configs:
115
+ {configs}---
116
+
117
+ # tinymix
118
+
119
+ Small, **genre-balanced English pretraining corpora** in three sizes (about 1M, 10M and 100M words), built for training
120
+ very small language models. The mix combines synthetic child-level stories and dialogue, simplified real text,
121
+ encyclopedic and didactic text, books, poetry and news, all filtered toward clear, self-contained documents. It is
122
+ inspired by TinyStories, SimpleStories, TinyHelen and the BabyLM challenge.
123
+
124
+ What is different from using those datasets directly:
125
+
126
+ - **Several kinds of text in one mix** (narrative, dialogue and chat, expository, books, poetry, news), not only stories or only conversations.
127
+ - **Three sizes built with the same recipe**, with complexity limits that grow with size.
128
+ - **No non-commercial sources.** TinyChat (CC-BY-NC) and the BabyLM corpus (no clear license, includes subtitle and child-speech data) were left out on purpose.
129
+ - **Provenance per document** (`source`, `genre`) and **validation splits per genre**, to see which kind of text a model is weak at.
130
+ - The whole pipeline is included (`code/`) and every filter decision is documented below.
131
+
132
+ ## Subsets
133
+
134
+ {size_t}
135
+ Words are whitespace-separated words in `train`. Each subset also has about 0.5% of the documents per genre held out as `validation_<genre>` splits
136
+ (at least one document per genre; the `1M` validation splits are therefore tiny, a few dozen documents, and noisy).
137
+
138
+ ```python
139
+ from datasets import load_dataset
140
+ ds = load_dataset("{REPO}", "10M") # splits: train, validation_narrative, validation_dialogue, ...
141
+ print(ds["train"][0]) # {{'text': ..., 'source': 'tinystories', 'genre': 'narrative'}}
142
+ ```
143
+
144
+ Columns: `text` (str), `source` (key of the table below), `genre` (`narrative`, `dialogue`, `expository`, `books`, `poetry`, `news`).
145
+ Documents are independent; join them with an end-of-text token when training. Dialogues are formatted one turn per line
146
+ (`Mia: ...`, or `User:` / `Assistant:` for assistant chats).
147
+
148
+ ## Composition
149
+
150
+ Share of training words by genre:
151
+
152
+ {genre_t}
153
+ Million words per source:
154
+
155
+ {src_t}
156
+ The 10M and 100M subsets reached their targets (10.0M and 100.0M words including the validation splits). In the 10M build,
157
+ sources that could not fill their quota with the filters (Simple English Wikipedia, Cosmopedia v0.1) were topped up by
158
+ same-genre substitute sources (tiny-textbooks, Cosmopedia v2), capped per source; that is why `tiny-textbooks` appears
159
+ there. The 1M subset keeps the 10M proportions except that Cosmopedia stories (not in the 10M mix) were replaced by TinyStories and SimpleStories.
160
+
161
+ ## How it was built
162
+
163
+ 1. **Normalisation**: `ftfy`, NFKC, ASCII quotes and dashes, whitespace; URLs, e-mails, phone numbers, code, LaTeX and HTML removed.
164
+ 2. **Language**: fastText `lid.176`, English with confidence >= 0.9 (skipped for TinyDialogues, whose one-word toddler turns confuse it).
165
+ 3. **Quality heuristics**: Gopher-style rules (mean word length, symbol and digit ratio, repeated lines, repeated bigrams, stop words), minimum length, complete ending (drops truncated generations), a short list of LLM tics (`delve`, `tapestry`, ...) and an explicit-content word list.
166
+ 4. **Anti-template**: no 4-word opening may exceed 0.5% of a source's documents.
167
+ 5. **Deduplication across all sources**: exact hash and MinHash LSH (5-word shingles, Jaccard >= 0.8).
168
+ 6. **Complexity control by size** (vocabulary coverage = share of lowercase tokens inside the top-N English words of `wordfreq`):
169
+
170
+ | | 10M | 100M |
171
+ |---|---|---|
172
+ | Reference vocabulary | top 8k | top 15k |
173
+ | Min vocabulary coverage | 90% | 90% |
174
+ | Max Flesch-Kincaid grade (narrative, news, books) | 5 | 8 |
175
+ | Max Flesch-Kincaid grade (expository) | 9 | 10 |
176
+ | Document length | 80 to 600 words | 80 to 1200 words |
177
+ | Dialogue: mean words per turn | <= 25 | <= 40 |
178
+
179
+ Assistant chats (`User:` / `Assistant:`) may average up to 4 times the per-turn cap and need at least 2 turns (named dialogues need 4),
180
+ because summarisation and rewrite tasks have 2 turns and assistant answers are long.
181
+
182
+ Documents longer than the maximum are split at paragraph borders. The 1M subset is a prefix slice of the 10M build; 10M and 100M were built separately with the same recipe, so they are **not** guaranteed to be subsets of each other (a later fix to the end-of-document check, which wrongly rejected Wikipedia articles that end in a heading, was only applied to sources rebuilt for the 100M run).
183
+ 7. **Run safety nets** (used to build the larger subsets without manual tuning): a probe per source picks a starting filter strictness, strictness relaxes in up to three logged steps when yield is too low, and shortfalls go to substitute sources.
184
+
185
+ Thresholds were calibrated on real data: the first values (95% coverage in the top 5k words, Flesch-Kincaid <= 5 for everything)
186
+ accepted only 3% of SimpleStories and 0.6% of Cosmopedia v2, so they were relaxed as described above.
187
+
188
+ ## Sources and licensing
189
+
190
+ {lic_t}
191
+ **Licensing and attribution.** This repository is a derivative compilation of the datasets above; each document keeps the
192
+ license of its `source`. Obligations that matter when redistributing or reusing it:
193
+
194
+ - Attribution is required for CC-BY / ODC-By / CDLA sources (listed above).
195
+ - The Wikipedia part (`simplewiki`) is **CC-BY-SA-3.0 / GFDL (share-alike)**. If you need a share-alike-free corpus, filter out `source == "simplewiki"`.
196
+ - Cosmopedia, SmolTalk, UltraChat, TinyStories, SimpleStories, TinyHelen and tiny-textbooks contain **model-generated text**; check the terms of the generating model (GPT-4, GPT-4o-mini, Mixtral and others) for your use case.
197
+ - CNN/DailyMail articles and FineWeb-Edu web pages are third-party content; they are included under the dataset licenses above, which do not transfer rights from the original publishers.
198
+ - Project Gutenberg texts had the Project Gutenberg header and footer removed; they are public domain in the United States, check your jurisdiction.
199
+
200
+ No personal data was added; e-mails, phone numbers and URLs were removed, but residual personal information in web-derived sources cannot be ruled out.
201
+
202
+ {results_section()}## Limitations
203
+
204
+ - **Not done**: perplexity filtering with an n-gram LM, LLM-judge coherence scoring, semantic deduplication, cluster caps and benchmark decontamination. Expect some residual near-duplicates and some low-quality documents.
205
+ - Some `tinyhelen` chunks start mid-thought, because the simplified web and book documents are chunks of longer texts.
206
+ - Synthetic sources share model-specific style and topics (names, morals, classroom settings). The anti-template cap reduces this but does not remove it.
207
+ - The toxicity filter is a short word list, not a classifier. Chat and web sources can still contain mildly sensitive content.
208
+ - English only, mostly simple modern language; it is a poor fit for models meant to handle technical, legal or archaic text.
209
+ - Word counts are whitespace words; token counts depend on your tokenizer.
210
+
211
+ ## Reproduce
212
+
213
+ `code/` contains the build scripts (`mix.py` quotas and tiers, `sources.py` adapters, `build.py` pipeline, `assemble.py`,
214
+ `publish.py`, `train.py` for the sanity-check runs) and `requirements.txt`. Building a subset: `python build.py 10M`,
215
+ then `python assemble.py 10M`. The build streams the source datasets from the Hub.
216
+
217
+ ## Acknowledgements
218
+
219
+ Built on the work behind TinyStories, SimpleStories, TinyDialogues, SODA, UltraChat, SmolTalk and SmolLM-Corpus
220
+ (Cosmopedia, FineWeb-Edu), TinyHelen, tiny-textbooks, Project Gutenberg, the Gutenberg Poetry Corpus, Wikipedia and
221
+ CNN/DailyMail. Please cite the original datasets when you use this one.
222
+ """
223
+
224
+
225
+ def stage():
226
+ out = ROOT / "out" / "hf"
227
+ if out.exists():
228
+ shutil.rmtree(out)
229
+ (out / "code").mkdir(parents=True)
230
+ sizes = [s for s in SIZES if (ROOT / "out" / s / "parquet" / "train.parquet").exists()]
231
+ for s in sizes:
232
+ shutil.copytree(ROOT / "out" / s / "parquet", out / "data" / s)
233
+ for f in ("mix.py", "sources.py", "build.py", "assemble.py", "baselines.py", "train.py", "publish.py"):
234
+ shutil.copy(ROOT / "scripts" / f, out / "code" / f)
235
+ shutil.copy(ROOT / "requirements.txt", out / "code" / "requirements.txt")
236
+ (out / "README.md").write_text(card(), encoding="utf-8")
237
+ print("staged", sizes, "->", out)
238
+ return out
239
+
240
+
241
+ def main():
242
+ out = stage()
243
+ if "--upload" in sys.argv:
244
+ for l in (ROOT / ".env").read_text(encoding="utf-8").splitlines():
245
+ if "=" in l and not l.lstrip().startswith("#"):
246
+ k, v = l.split("=", 1)
247
+ os.environ.setdefault(k.strip(), v.strip().strip("'\""))
248
+ from huggingface_hub import HfApi
249
+ api = HfApi(token=os.environ["HF_TOKEN"])
250
+ api.create_repo(REPO, repo_type="dataset", private=True, exist_ok=True)
251
+ api.upload_folder(folder_path=str(out), repo_id=REPO, repo_type="dataset",
252
+ commit_message="tinymix: " + ", ".join(p.name for p in (out / "data").iterdir()))
253
+ print(f"uploaded to https://huggingface.co/datasets/{REPO} (private)")
254
+
255
+
256
+ if __name__ == "__main__":
257
+ main()
code/requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ datasets==5.1.0
2
+ huggingface_hub>=1.5,<2
3
+ tokenizers==0.22.2
4
+ ftfy==6.3.1
5
+ datasketch==2.0.0
6
+ wordfreq==3.1.1
7
+ pyarrow
8
+ numpy==2.1.3
9
+ fasttext-wheel
10
+ vastai
code/sources.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Streaming adapters. Each yields dicts: {"text"} or {"turns": [(speaker, text)]}, optional "title"."""
2
+ import ast
3
+ import random
4
+ import re
5
+ import zlib
6
+
7
+ from datasets import load_dataset
8
+ from huggingface_hub import HfFileSystem
9
+
10
+ SEED = 0
11
+ EOT = "<|endoftext|>"
12
+
13
+
14
+ def _ds(*args, shuffle=False, buffer=20000, **kw):
15
+ ds = load_dataset(*args, streaming=True, **kw)
16
+ return ds.shuffle(seed=SEED, buffer_size=buffer) if shuffle else ds
17
+
18
+
19
+ def _lines(path):
20
+ with HfFileSystem().open(path, "r", encoding="utf-8", errors="replace") as f:
21
+ yield from f
22
+
23
+
24
+ def tinystories(size):
25
+ buf = []
26
+ for line in _lines("datasets/roneneldan/TinyStories/TinyStoriesV2-GPT4-train.txt"):
27
+ if EOT in line:
28
+ text = " ".join(buf).strip()
29
+ buf = []
30
+ if text:
31
+ # the source lost curly quotes as U+FFFD: between letters it was an apostrophe
32
+ text = re.sub(r"(?<=\w)�(?=\w)", "'", text).replace("�", '"')
33
+ yield {"text": text}
34
+ else:
35
+ buf.append(line.strip())
36
+
37
+
38
+ def simplestories(size):
39
+ for r in _ds("SimpleStories/SimpleStories", split="train", shuffle=True):
40
+ yield {"text": r["story"]}
41
+
42
+
43
+ def cosmo_stories(size):
44
+ for r in _ds("HuggingFaceTB/cosmopedia", "stories", split="train", shuffle=True):
45
+ yield {"text": r["text"], "audience": r.get("audience")}
46
+
47
+
48
+ def tinydialogues(size):
49
+ for line in _lines("datasets/styfeng/TinyDialogues/tinydialogue_train_ordered.txt"):
50
+ for doc in line.split(EOT):
51
+ turns = []
52
+ for t in doc.split("\\n\\n"):
53
+ m = re.match(r'\s*\*\*(.+?)\*\*\s*:\s*(.+)', t.strip(), re.S)
54
+ if m:
55
+ turns.append((m.group(1).strip(), m.group(2).strip().strip('"')))
56
+ if turns:
57
+ yield {"turns": turns}
58
+
59
+
60
+ def soda(size):
61
+ for r in _ds("allenai/soda", split="train", shuffle=True):
62
+ d, s = r["dialogue"], r["speakers"]
63
+ d = ast.literal_eval(d) if isinstance(d, str) else d
64
+ s = ast.literal_eval(s) if isinstance(s, str) else s
65
+ if d and len(d) == len(s) and 4 <= len(d) <= 12:
66
+ yield {"turns": list(zip(s, d))}
67
+
68
+
69
+ def _chat(msgs):
70
+ names = {"user": "User", "assistant": "Assistant"}
71
+ return [(names[m["role"]], m["content"]) for m in msgs if m["role"] in names]
72
+
73
+
74
+ def ultrachat(size):
75
+ for r in _ds("HuggingFaceH4/ultrachat_200k", split="train_sft", shuffle=True):
76
+ yield {"turns": _chat(r["messages"])}
77
+
78
+
79
+ def smoltalk(size):
80
+ # interleave the three configs so none is exhausted first
81
+ its = [iter(_ds("HuggingFaceTB/smoltalk", c, split="train", shuffle=True))
82
+ for c in ("everyday-conversations", "smol-summarize", "smol-rewrite")]
83
+ while its:
84
+ for it in list(its):
85
+ try:
86
+ yield {"turns": _chat(next(it)["messages"])}
87
+ except StopIteration:
88
+ its.remove(it)
89
+
90
+
91
+ def tinyhelen(size):
92
+ base = "hf://datasets/EmpathYang/TinyHelen/data/leaner/100M/train/"
93
+ fs = HfFileSystem()
94
+ files = sorted(p for p in fs.ls("datasets/EmpathYang/TinyHelen/data/leaner/100M/train", detail=False)
95
+ if any(k in p.split("/")[-1] for k in ("book", "conversation", "textbook", "web", "wiki")))
96
+ streams = [iter(load_dataset("json", data_files=base + p.split("/")[-1], split="train", streaming=True))
97
+ for p in files]
98
+ # round-robin over the genre files so the mix is balanced
99
+ while streams:
100
+ for it in list(streams):
101
+ try:
102
+ yield {"text": next(it)["text"]}
103
+ except StopIteration:
104
+ streams.remove(it)
105
+
106
+
107
+ def simplewiki(size):
108
+ for r in _ds("wikimedia/wikipedia", "20231101.simple", split="train", shuffle=True):
109
+ yield {"text": r["text"], "title": r["title"]}
110
+
111
+
112
+ def enwiki_intro(size):
113
+ for r in _ds("wikimedia/wikipedia", "20231101.en", split="train", shuffle=True):
114
+ intro = r["text"].split("\n\n")[0]
115
+ yield {"text": intro, "title": r["title"]}
116
+
117
+
118
+ def cosmo_v2(size):
119
+ kids = {"young_children", "middle_school_students", "grade_school_students", "children"}
120
+ for r in _ds("HuggingFaceTB/smollm-corpus", "cosmopedia-v2", split="train", shuffle=True):
121
+ if size == "10M" and r["audience"] not in kids:
122
+ continue
123
+ yield {"text": r["text"], "audience": r["audience"], "format": r["format"]}
124
+
125
+
126
+ def cosmo_v01(size):
127
+ its = [iter(_ds("HuggingFaceTB/cosmopedia", c, split="train", shuffle=True))
128
+ for c in ("wikihow", "khanacademy", "openstax")]
129
+ while its:
130
+ for it in list(its):
131
+ try:
132
+ yield {"text": next(it)["text"]}
133
+ except StopIteration:
134
+ its.remove(it)
135
+
136
+
137
+ def tiny_textbooks(size):
138
+ # `text` is raw web (RefinedWeb); `textbook` is the synthetic lesson we want
139
+ for r in _ds("nampdn-ai/tiny-textbooks", split="train", shuffle=True):
140
+ yield {"text": r["textbook"]}
141
+
142
+
143
+ def fineweb_edu(size):
144
+ for r in _ds("HuggingFaceFW/fineweb-edu", "sample-10BT", split="train"):
145
+ if r["int_score"] >= 4:
146
+ yield {"text": r["text"]}
147
+
148
+
149
+ def gutenberg_books(size):
150
+ # whole books per row: a 20k-row shuffle buffer overflows Arrow's 2 GB string offsets
151
+ for r in _ds("manu/project_gutenberg", split="en", shuffle=True, buffer=8):
152
+ t = r["text"]
153
+ a = re.search(r"\*\*\* ?START OF (THE|THIS) PROJECT GUTENBERG[^\n]*\n", t)
154
+ b = re.search(r"\*\*\* ?END OF (THE|THIS) PROJECT GUTENBERG", t)
155
+ if a:
156
+ t = t[a.end():]
157
+ if b:
158
+ t = t[:t.rfind("*** END")] if "*** END" in t else t[:b.start()]
159
+ paras = [re.sub(r"\s*\n\s*", " ", p).strip() for p in re.split(r"\n\s*\n", t)]
160
+ paras = [p for p in paras if p and not (p.isupper() and len(p) < 80)]
161
+ chunk, n = [], 0
162
+ for p in paras:
163
+ chunk.append(p)
164
+ n += len(p.split())
165
+ if n >= 300:
166
+ yield {"text": "\n\n".join(chunk)}
167
+ chunk, n = [], 0
168
+
169
+
170
+ def poetry(size):
171
+ rng = random.Random(SEED)
172
+ cur, lines, target = None, [], rng.randint(4, 20)
173
+ for r in _ds("biglam/gutenberg-poetry-corpus", split="train"):
174
+ if r["gutenberg_id"] != cur:
175
+ cur, lines = r["gutenberg_id"], []
176
+ lines.append(r["line"].strip())
177
+ if len(lines) >= target:
178
+ yield {"text": "\n".join(lines)}
179
+ lines, target = [], rng.randint(4, 20)
180
+
181
+
182
+ def cnn(size):
183
+ for r in _ds("abisee/cnn_dailymail", "3.0.0", split="train", shuffle=True):
184
+ text = r["article"]
185
+ if zlib.crc32(r["id"].encode()) % 10 < 3:
186
+ text += "\n\nIn short: " + " ".join(r["highlights"].split("\n"))
187
+ yield {"text": text}
188
+
189
+
190
+ REGISTRY = {f.__name__: f for f in (
191
+ tinystories, simplestories, cosmo_stories, tinydialogues, soda, ultrachat, smoltalk,
192
+ tinyhelen, simplewiki, enwiki_intro, cosmo_v2, cosmo_v01, tiny_textbooks, fineweb_edu,
193
+ gutenberg_books, poetry, cnn)}
code/train.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tiny GPT (nanoGPT-style) on one dataset size, with its own BPE.
2
+
3
+ python train.py 1M [--vocab 4096 --layers 6 --heads 6 --dim 192 --epochs 10]
4
+
5
+ Reports validation loss per genre as bits per byte, which is comparable across
6
+ datasets even though each one has its own tokenizer.
7
+ """
8
+ import argparse
9
+ import json
10
+ import math
11
+ import time
12
+ from pathlib import Path
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ from tokenizers import Tokenizer, models, pre_tokenizers, decoders, trainers
18
+
19
+ ROOT = Path(__file__).resolve().parent.parent
20
+ EOT = "<|endoftext|>"
21
+
22
+
23
+ def get_tokenizer(data, vocab, path):
24
+ if path.exists():
25
+ return Tokenizer.from_file(str(path))
26
+ tok = Tokenizer(models.BPE())
27
+ tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
28
+ tok.decoder = decoders.ByteLevel()
29
+ tr = trainers.BpeTrainer(vocab_size=vocab, special_tokens=[EOT],
30
+ initial_alphabet=pre_tokenizers.ByteLevel.alphabet())
31
+ tok.train_from_iterator((d for d in data.split(EOT) if d.strip()), tr)
32
+ tok.save(str(path))
33
+ return tok
34
+
35
+
36
+ def encode(tok, text):
37
+ ids = []
38
+ eot = tok.token_to_id(EOT)
39
+ for doc in text.split(EOT):
40
+ if doc.strip():
41
+ ids += tok.encode(doc.strip("\n")).ids + [eot]
42
+ return torch.tensor(ids, dtype=torch.long)
43
+
44
+
45
+ class Block(nn.Module):
46
+ def __init__(self, d, h):
47
+ super().__init__()
48
+ self.h = h
49
+ self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
50
+ self.qkv, self.proj = nn.Linear(d, 3 * d, bias=False), nn.Linear(d, d, bias=False)
51
+ self.fc, self.out = nn.Linear(d, 4 * d, bias=False), nn.Linear(4 * d, d, bias=False)
52
+
53
+ def forward(self, x):
54
+ B, T, C = x.shape
55
+ q, k, v = self.qkv(self.ln1(x)).view(B, T, 3, self.h, C // self.h).permute(2, 0, 3, 1, 4)
56
+ x = x + self.proj(F.scaled_dot_product_attention(q, k, v, is_causal=True)
57
+ .transpose(1, 2).reshape(B, T, C))
58
+ return x + self.out(F.gelu(self.fc(self.ln2(x))))
59
+
60
+
61
+ class GPT(nn.Module):
62
+ def __init__(self, vocab, block, layers, heads, dim):
63
+ super().__init__()
64
+ self.block = block
65
+ self.tok, self.pos = nn.Embedding(vocab, dim), nn.Embedding(block, dim)
66
+ self.blocks = nn.ModuleList(Block(dim, heads) for _ in range(layers))
67
+ self.ln = nn.LayerNorm(dim)
68
+ self.head = nn.Linear(dim, vocab, bias=False)
69
+ self.head.weight = self.tok.weight # tied embeddings
70
+ self.apply(self._init)
71
+
72
+ @staticmethod
73
+ def _init(m):
74
+ if isinstance(m, (nn.Linear, nn.Embedding)):
75
+ nn.init.normal_(m.weight, std=0.02)
76
+
77
+ def forward(self, idx, targets=None):
78
+ x = self.tok(idx) + self.pos(torch.arange(idx.size(1), device=idx.device))
79
+ for b in self.blocks:
80
+ x = b(x)
81
+ logits = self.head(self.ln(x))
82
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1)) if targets is not None else None
83
+ return logits, loss
84
+
85
+ @torch.no_grad()
86
+ def generate(self, idx, n, temp=0.8, top_k=40):
87
+ for _ in range(n):
88
+ logits, _ = self(idx[:, -self.block:])
89
+ logits = logits[:, -1] / temp
90
+ v, _ = torch.topk(logits, top_k)
91
+ logits[logits < v[:, [-1]]] = -float("inf")
92
+ idx = torch.cat([idx, torch.multinomial(F.softmax(logits, -1), 1)], 1)
93
+ return idx
94
+
95
+
96
+ @torch.no_grad()
97
+ def eval_bpb(model, tok, text, block, dev, amp):
98
+ """Bits per byte over a validation file (non-overlapping windows)."""
99
+ ids = encode(tok, text)
100
+ nbytes = len(text.replace(EOT, "").encode("utf-8"))
101
+ model.eval()
102
+ total, count = 0.0, 0
103
+ for i in range(0, len(ids) - 1, block):
104
+ x = ids[i:i + block].to(dev)[None]
105
+ y = ids[i + 1:i + block + 1].to(dev)[None]
106
+ x = x[:, :y.size(1)]
107
+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=amp):
108
+ _, loss = model(x, y)
109
+ total += loss.item() * y.numel()
110
+ count += y.numel()
111
+ model.train()
112
+ # summed nats over all tokens, divided by bytes: independent of the tokenizer
113
+ return total / math.log(2) / nbytes
114
+
115
+
116
+ def main():
117
+ ap = argparse.ArgumentParser()
118
+ ap.add_argument("size")
119
+ ap.add_argument("--vocab", type=int, default=4096)
120
+ ap.add_argument("--layers", type=int, default=6)
121
+ ap.add_argument("--heads", type=int, default=6)
122
+ ap.add_argument("--dim", type=int, default=192)
123
+ ap.add_argument("--block", type=int, default=256)
124
+ ap.add_argument("--batch", type=int, default=64)
125
+ ap.add_argument("--epochs", type=float, default=10)
126
+ ap.add_argument("--steps", type=int, default=0, help="fixed step count (overrides --epochs); used to match compute across datasets")
127
+ ap.add_argument("--lr", type=float, default=1e-3)
128
+ ap.add_argument("--tag", default="")
129
+ ap.add_argument("--data", default=None, help="folder with train.txt (default out/<size>)")
130
+ ap.add_argument("--valid", default=None, help="folder with valid_*.txt (default: --data); "
131
+ "baselines are scored on OUR validation sets")
132
+ a = ap.parse_args()
133
+
134
+ torch.manual_seed(0)
135
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
136
+ amp = dev == "cuda" and torch.cuda.is_bf16_supported()
137
+ data_dir = Path(a.data) if a.data else ROOT / "out" / a.size
138
+ run = ROOT / "runs" / f"{a.size}{a.tag}"
139
+ run.mkdir(parents=True, exist_ok=True)
140
+
141
+ train_text = (data_dir / "train.txt").read_text(encoding="utf-8")
142
+ tok = get_tokenizer(train_text, a.vocab, run / "tokenizer.json")
143
+ train = encode(tok, train_text)
144
+ valid_dir = Path(a.valid) if a.valid else data_dir
145
+ valids = {p.stem.replace("valid_", ""): p.read_text(encoding="utf-8") for p in sorted(valid_dir.glob("valid_*.txt"))}
146
+ model = GPT(tok.get_vocab_size(), a.block, a.layers, a.heads, a.dim).to(dev)
147
+ n_params = sum(p.numel() for p in model.parameters())
148
+ steps = a.steps or int(a.epochs * len(train) / (a.batch * a.block))
149
+ print(f"{a.size}: {len(train)/1e6:.2f}M tokens, {n_params/1e6:.2f}M params, {steps} steps, device {dev}, bf16 {amp}", flush=True)
150
+
151
+ opt = torch.optim.AdamW(model.parameters(), lr=a.lr, betas=(0.9, 0.95), weight_decay=0.1)
152
+ sched = lambda s: a.lr * min(1, (s + 1) / 100) * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * s / steps)))
153
+ t0 = time.time()
154
+ for s in range(steps):
155
+ for g in opt.param_groups:
156
+ g["lr"] = sched(s)
157
+ ix = torch.randint(len(train) - a.block - 1, (a.batch,))
158
+ x = torch.stack([train[i:i + a.block] for i in ix]).to(dev)
159
+ y = torch.stack([train[i + 1:i + a.block + 1] for i in ix]).to(dev)
160
+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=amp):
161
+ _, loss = model(x, y)
162
+ opt.zero_grad(set_to_none=True)
163
+ loss.backward()
164
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
165
+ opt.step()
166
+ if s % 100 == 0 or s == steps - 1:
167
+ print(f"step {s}/{steps} loss {loss.item():.3f} {time.time()-t0:.0f}s", flush=True)
168
+
169
+ res = {"size": a.size, "params_M": round(n_params / 1e6, 2), "tokens_M": round(len(train) / 1e6, 2),
170
+ "steps": steps, "seconds": round(time.time() - t0),
171
+ "valid_bits_per_byte": {g: round(eval_bpb(model, tok, t, a.block, dev, amp), 4) for g, t in valids.items()}}
172
+ prompt = torch.tensor([[tok.token_to_id(EOT)]], device=dev)
173
+ res["sample"] = tok.decode(model.generate(prompt, 150)[0].tolist())
174
+ (run / "results.json").write_text(json.dumps(res, indent=1), encoding="utf-8")
175
+ torch.save(model.state_dict(), run / "model.pt")
176
+ print(json.dumps(res, indent=1))
177
+
178
+
179
+ if __name__ == "__main__":
180
+ main()
data/100M/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a2a6e05e47b4109ff6dcf8532ffeb14fbe9481518954ba1f894549048301289
3
+ size 241518580
data/100M/validation_books.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17ea604e9a0673fb38a570edc5919a2e7112b65ddd1ff51ee75ad49eb05cd894
3
+ size 103933
data/100M/validation_dialogue.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bade9587417964ad14caf9538eafc53c425d4889b6c40aa4ad05efe3e7588831
3
+ size 216293
data/100M/validation_expository.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70ab0434691b010f2140d4792843975ba6065f617b6b661c2224ce0082cc35fa
3
+ size 596237
data/100M/validation_narrative.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a87e9ce6126904af3d3ff4faf50ebd43e8bc53835164df06461c639678a147bb
3
+ size 232296
data/100M/validation_news.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:844e4285c5fb536acbb6383a5614f4a7b22295cd7726bc907b8a4bbe5c1aea00
3
+ size 20266
data/100M/validation_poetry.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3d8605adec8b235dcf2c8d14161073b1ff270d1ba63669b3fea4b26b6358f4f2
3
+ size 16992
data/10M/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2288906074861a0d74a3240d6e7493838979cdbb7e0d1d38a7c9c39a749e952
3
+ size 22521290
data/10M/validation_dialogue.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e4ed00f76d5dd7ab7dcdad239414a91e5eb2615c61d09696368e1265f71b3194
3
+ size 30704
data/10M/validation_expository.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1aa892bbbddd49e23abbb66c6f5b142de188f4e1feb56fb1722aa89d72dc8dec
3
+ size 52271
data/10M/validation_narrative.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0e07ef77350053be742b174c8c14986775afe7321c885ad8f654c9107d05fad
3
+ size 43973
data/1M/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a128c794cebfe7de2cd6e1feb50e798b0fbea0db79e527c960634699ec66de95
3
+ size 2293603
data/1M/validation_dialogue.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a07005ab0813d76f3f649d3e9f118ddd6fc500631f8bc2c6ace815cac0d3b71
3
+ size 7082
data/1M/validation_expository.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:893a340e5d1271551e347b2265787b8849a7888011a26ae5296285e34f8488d0
3
+ size 12131
data/1M/validation_narrative.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1ec4dffab1b3e2117c8c06987ec396f50d5dc0392bfeed6fcc543705fb3cb2e
3
+ size 7624