File size: 17,099 Bytes
fbe8d49 9cd89ed fbe8d49 f0c12b0 fbe8d49 f0c12b0 fbe8d49 f0c12b0 fbe8d49 f0c12b0 fbe8d49 9cd89ed fbe8d49 9cd89ed fbe8d49 9cd89ed fbe8d49 9cd89ed fbe8d49 f4a9952 fbe8d49 f0c12b0 fbe8d49 9cd89ed fbe8d49 f0c12b0 fbe8d49 9cd89ed fbe8d49 9cd89ed fbe8d49 9cd89ed fbe8d49 f0c12b0 fbe8d49 9cd89ed fbe8d49 9cd89ed fbe8d49 9cd89ed fbe8d49 9cd89ed fbe8d49 | 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 | """Build the Hugging Face release folder (card + parquet + code) and optionally upload it.
python publish.py # stage only: out/hf/
python publish.py --upload # stage and push to a PRIVATE dataset repo (flip to public in the HF UI)
"""
import json
import os
import shutil
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
REPO = "jncarlo/tinymix"
SIZES = ["1M", "10M", "100M", "1000M"]
GENRES = ["narrative", "dialogue", "expository", "books", "poetry", "news"]
# Sanity-check results: every tinymix row is retrained on the current builds (charset filter included).
INCLUDE_RESULTS = True
# source key -> (display name, link, license, role)
SOURCES = {
"tinystories": ("TinyStories V2 (GPT-4 split)", "https://huggingface.co/datasets/roneneldan/TinyStories", "CDLA-Sharing-1.0", "child-level stories"),
"simplestories": ("SimpleStories", "https://huggingface.co/datasets/SimpleStories/SimpleStories", "MIT", "varied simple stories"),
"cosmo_stories": ("Cosmopedia v0.1, `stories`", "https://huggingface.co/datasets/HuggingFaceTB/cosmopedia", "Apache-2.0", "everyday stories"),
"tinydialogues": ("TinyDialogues", "https://huggingface.co/datasets/styfeng/TinyDialogues", "MIT", "child-directed dialogue"),
"soda": ("SODA", "https://huggingface.co/datasets/allenai/soda", "CC-BY-4.0", "social dialogue"),
"ultrachat": ("UltraChat 200k", "https://huggingface.co/datasets/HuggingFaceH4/ultrachat_200k", "MIT", "user/assistant chat"),
"smoltalk": ("SmolTalk (everyday-conversations, smol-summarize, smol-rewrite)", "https://huggingface.co/datasets/HuggingFaceTB/smoltalk", "Apache-2.0", "chat, summaries, rewrites"),
"tinyhelen": ("TinyHelen Leaner-Pretrain (book, conversation, textbook, web, wiki)", "https://huggingface.co/datasets/EmpathYang/TinyHelen", "MIT", "simplified real text"),
"simplewiki": ("Simple English Wikipedia (20231101.simple)", "https://huggingface.co/datasets/wikimedia/wikipedia", "CC-BY-SA-3.0 / GFDL", "encyclopedic, simple"),
"enwiki_intro": ("English Wikipedia, lead paragraphs", "https://huggingface.co/datasets/wikimedia/wikipedia", "CC-BY-SA-3.0 / GFDL", "encyclopedic"),
"cosmo_v2": ("Cosmopedia v2 (SmolLM-Corpus)", "https://huggingface.co/datasets/HuggingFaceTB/smollm-corpus", "Apache-2.0 (corpus: ODC-By)", "synthetic textbooks, blogs, stories"),
"cosmo_v01": ("Cosmopedia v0.1 (wikihow, khanacademy, openstax)", "https://huggingface.co/datasets/HuggingFaceTB/cosmopedia", "Apache-2.0", "procedural and didactic"),
"tiny_textbooks": ("tiny-textbooks (`textbook` column)", "https://huggingface.co/datasets/nampdn-ai/tiny-textbooks", "Apache-2.0", "short synthetic lessons"),
"fineweb_edu": ("FineWeb-Edu (sample-10BT, score >= 4)", "https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu", "ODC-By-1.0", "educational web"),
"gutenberg_books": ("Project Gutenberg (English books)", "https://huggingface.co/datasets/manu/project_gutenberg", "Project Gutenberg License (public domain in the US)", "classic books"),
"poetry": ("Gutenberg Poetry Corpus", "https://huggingface.co/datasets/biglam/gutenberg-poetry-corpus", "CC0-1.0", "poetry stanzas"),
"cnn": ("CNN/DailyMail 3.0.0", "https://huggingface.co/datasets/abisee/cnn_dailymail", "Apache-2.0 (articles are (c) CNN / Daily Mail)", "news"),
}
def load(size):
return json.loads((ROOT / "out" / size / "summary.json").read_text())
def tables():
sums = {s: load(s) for s in SIZES if (ROOT / "out" / s / "summary.json").exists()}
sizes = list(sums)
head = "| Subset | Train words | Train docs | ~Tokens (BPE) |\n|---|---|---|---|\n"
rows = "".join(f"| `{s}` | {v['train_words_M']}M | {v['train_docs']:,} | ~{v['train_words_M']*1.3:.1f}M |\n"
for s, v in sums.items())
g = "| Genre | " + " | ".join(sizes) + " |\n|---|" + "---|" * len(sizes) + "\n"
for gen in GENRES:
vals = [sums[s]["genre_share_%"].get(gen) for s in sizes]
if any(vals):
g += f"| {gen} | " + " | ".join(f"{v or 0}%" for v in vals) + " |\n"
used = sorted({k for v in sums.values() for k in v["source_words_M"]}, key=lambda k: list(SOURCES).index(k))
s = "| Source | " + " | ".join(f"{x} (M words)" for x in sizes) + " |\n|---|" + "---|" * len(sizes) + "\n"
for k in used:
s += f"| {SOURCES[k][0]} | " + " | ".join(str(sums[x]["source_words_M"].get(k, 0)) for x in sizes) + " |\n"
lic = "| Source | License | Role |\n|---|---|---|\n" + "".join(
f"| [{SOURCES[k][0]}]({SOURCES[k][1]}) | {SOURCES[k][2]} | {SOURCES[k][3]} |\n" for k in used)
return sizes, head + rows, g, s, lic
def results_section():
runs = ROOT / "runs"
names = [("1M", "tinymix 1M"), ("10M", "tinymix 10M"), ("base_tinystories_10M", "TinyStories only, 10M words"),
("base_fineweb_edu_10M", "FineWeb-Edu only, 10M words"),
("100M", "tinymix 100M"), ("base_fineweb_edu_100M", "FineWeb-Edu only, 100M words")]
rows = []
for key, label in names:
p = runs / key / "results.json"
if p.exists():
r = json.loads(p.read_text())
b = r["valid_bits_per_byte"]
rows.append(f"| {label} | {r['params_M']}M | {r['tokens_M']}M | " +
" | ".join(f"{b[g]:.3f}" if g in b else "n/a"
for g in ("narrative", "dialogue", "expository", "books", "news", "poetry")) + " |\n")
if not rows:
return ""
return ("## Sanity-check training runs\n\n"
"Small GPTs (nanoGPT-style, own byte-level BPE trained on each training set). Each row shows its own "
"parameter count and training tokens, so model sizes differ between rows. 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. Rows of different sizes are not comparable with each other. "
"The 1M and 10M sets have no books, news or poetry split, hence n/a.\n\n"
"| Training data | Params | Train tokens | narrative | dialogue | expository | books | news | poetry |\n|---|---|---|---|---|---|---|---|---|\n"
+ "".join(rows) + "\n")
def card():
sizes, size_t, genre_t, src_t, lic_t = tables()
configs = ""
for s in sizes:
configs += f"- config_name: {s}\n data_files:\n - split: train\n path: data/{s}/train*.parquet\n"
for p in sorted((ROOT / "out" / s / "parquet").glob("validation_*.parquet")):
configs += f" - split: {p.stem}\n path: data/{s}/{p.name}\n"
return f"""---
language:
- en
license: other
license_name: mixed-per-source
license_link: https://huggingface.co/datasets/{REPO}#sources-and-licensing
pretty_name: tinymix
size_categories:
- 1M<n<10M
task_categories:
- text-generation
tags:
- small-language-models
- synthetic-data
- curriculum
- tinystories
- babylm
configs:
{configs}---
# tinymix
Small, **genre-balanced English pretraining corpora** in four sizes (about 1M, 10M, 100M and 1000M words), built for training
very small language models. The mix combines synthetic child-level stories and dialogue, simplified real text,
encyclopedic and didactic text, books, poetry and news, all filtered toward clear, self-contained documents. It is
inspired by TinyStories, SimpleStories, TinyHelen and the BabyLM challenge.
What is different from using those datasets directly:
- **Several kinds of text in one mix** (narrative, dialogue and chat, expository, books, poetry, news), not only stories or only conversations.
- **Four sizes built with the same recipe**, with complexity limits that grow with size.
- **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.
- **Provenance per document** (`source`, `genre`) and **validation splits per genre**, to see which kind of text a model is weak at.
- The whole pipeline is included (`code/`) and every filter decision is documented below.
## Subsets
{size_t}
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
(at least one document per genre; the `1M` validation splits are therefore tiny, 4 to 8 documents each, and noisy).
```python
from datasets import load_dataset
ds = load_dataset("{REPO}", "10M") # splits: train, validation_narrative, validation_dialogue, ...
print(ds["train"][0]) # {{'text': ..., 'source': 'tinystories', 'genre': 'narrative'}}
```
Columns: `text` (str), `source` (key of the table below), `genre` (`narrative`, `dialogue`, `expository`, `books`, `poetry`, `news`).
Documents are independent; join them with an end-of-text token when training. Dialogues are formatted one turn per line
(`Mia: ...`, or `User:` / `Assistant:` for assistant chats).
## Composition
Share of training words by genre:
{genre_t}
Million words per source:
{src_t}
The 10M and 100M subsets are within about 1% of their targets (train plus validation splits). In the 10M build,
sources that could not fill their quota with the filters (Simple English Wikipedia, Cosmopedia v0.1) were topped up by
same-genre substitute sources (tiny-textbooks, Cosmopedia v2), capped per source; that is why `tiny-textbooks` appears
there. The 1M subset keeps the 10M proportions except that Cosmopedia stories (not in the 10M mix) were replaced by TinyStories and SimpleStories.
The 1000M subset is also within about 1% of its target. Five sources ran out under the filters before their quota and were
topped up by same-genre substitutes (million words): TinyDialogues by SODA (9.3), SmolTalk by UltraChat (12.3), TinyHelen by
tiny-textbooks (15.9), Simple English Wikipedia by tiny-textbooks (8.7) and English Wikipedia lead paragraphs by Cosmopedia v2 (17.0).
## How it was built
1. **Normalisation**: `ftfy`, NFKC, ASCII quotes and dashes, whitespace; URLs, e-mails, phone numbers, code, LaTeX and HTML removed. Documents with any character outside ASCII, Latin-1 and Latin Extended-A letters, common punctuation and a few math symbols are rejected whole (reason `charset` in the build stats).
2. **Language**: fastText `lid.176`, English with confidence >= 0.9 (skipped for TinyDialogues, whose one-word toddler turns confuse it).
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.
4. **Anti-template**: no 4-word opening may exceed 0.5% of a source's documents.
5. **Deduplication across all sources**: exact hash and MinHash LSH (5-word shingles, Jaccard >= 0.8).
6. **Complexity control by size** (vocabulary coverage = share of lowercase tokens inside the top-N English words of `wordfreq`):
| | 10M | 100M | 1000M |
|---|---|---|---|
| Reference vocabulary | top 8k | top 15k | top 30k |
| Min vocabulary coverage | 90% | 90% | 90% |
| Max Flesch-Kincaid grade (narrative, news, books) | 5 | 8 | 12 |
| Max Flesch-Kincaid grade (expository) | 9 | 10 | 12 |
| Document length | 80 to 600 words | 80 to 1200 words | 80 to 2000 words |
| Dialogue: mean words per turn | <= 25 | <= 40 | <= 80 |
Assistant chats (`User:` / `Assistant:`) may average up to 4 times the per-turn cap and need at least 2 turns (named dialogues need 4),
because summarisation and rewrite tasks have 2 turns and assistant answers are long.
Documents longer than the maximum are split at paragraph borders. The 1M subset is a prefix slice of the 10M build; 10M, 100M and 1000M 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).
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.
Thresholds were calibrated on real data: the first values (95% coverage in the top 5k words, Flesch-Kincaid <= 5 for everything)
accepted only 3% of SimpleStories and 0.6% of Cosmopedia v2, so they were relaxed as described above.
## Sources and licensing
{lic_t}
**Licensing and attribution.** This repository is a derivative compilation of the datasets above; each document keeps the
license of its `source`. Obligations that matter when redistributing or reusing it:
- Attribution is required for CC-BY / ODC-By / CDLA sources (listed above).
- The Wikipedia parts (`simplewiki`, `enwiki_intro`) are **CC-BY-SA-3.0 / GFDL (share-alike)**. If you need a share-alike-free corpus, filter out those two sources.
- 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.
- 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.
- Project Gutenberg texts had the Project Gutenberg header and footer removed; they are public domain in the United States, check your jurisdiction.
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.
{results_section() if INCLUDE_RESULTS else ''}## Limitations
- **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.
- Some `tinyhelen` chunks start mid-thought, because the simplified web and book documents are chunks of longer texts.
- Synthetic sources share model-specific style and topics (names, morals, classroom settings). The anti-template cap reduces this but does not remove it.
- The toxicity filter is a short word list, not a classifier. Chat and web sources can still contain mildly sensitive content.
- English only, mostly simple modern language; it is a poor fit for models meant to handle technical, legal or archaic text.
- Word counts are whitespace words; token counts depend on your tokenizer.
## Reproduce
`code/` contains the build scripts (`mix.py` quotas and tiers, `sources.py` adapters, `build.py` pipeline, `build_pool.py` for
1000M, `assemble.py`, `publish.py`, `train.py` for the sanity-check runs) and `requirements.txt`. Building a subset:
`python build.py 10M` (or `python build_pool.py 1000M`), then `python assemble.py 10M`. The build streams the source datasets from the Hub.
## Acknowledgements
Built on the work behind TinyStories, SimpleStories, TinyDialogues, SODA, UltraChat, SmolTalk and SmolLM-Corpus
(Cosmopedia, FineWeb-Edu), TinyHelen, tiny-textbooks, Project Gutenberg, the Gutenberg Poetry Corpus, Wikipedia and
CNN/DailyMail. Please cite the original datasets when you use this one.
"""
def stage():
out = ROOT / "out" / "hf"
if out.exists():
shutil.rmtree(out)
(out / "code").mkdir(parents=True)
sizes = [s for s in SIZES if any((ROOT / "out" / s / "parquet").glob("train*.parquet"))]
for s in sizes:
shutil.copytree(ROOT / "out" / s / "parquet", out / "data" / s, copy_function=os.link) # no second copy on disk
for f in ("mix.py", "sources.py", "build.py", "build_pool.py", "assemble.py", "baselines.py", "train.py", "publish.py"):
shutil.copy(ROOT / "scripts" / f, out / "code" / f)
shutil.copy(ROOT / "requirements.txt", out / "code" / "requirements.txt")
(out / "README.md").write_text(card(), encoding="utf-8")
print("staged", sizes, "->", out)
return out
def main():
out = stage()
if "--upload" in sys.argv:
for l in (ROOT / ".env").read_text(encoding="utf-8").splitlines():
if "=" in l and not l.lstrip().startswith("#"):
k, v = l.split("=", 1)
os.environ.setdefault(k.strip(), v.strip().strip("'\""))
from huggingface_hub import HfApi
api = HfApi(token=os.environ["HF_TOKEN"])
api.create_repo(REPO, repo_type="dataset", private=True, exist_ok=True)
api.upload_folder(folder_path=str(out), repo_id=REPO, repo_type="dataset",
commit_message="tinymix: " + ", ".join(p.name for p in (out / "data").iterdir()))
print(f"uploaded to https://huggingface.co/datasets/{REPO}")
if __name__ == "__main__":
main()
|