"""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` 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()