#!/usr/bin/env python3 """Tokenize a text corpus into the training format (tokens.u16 + doc_starts.npy + texts.jsonl). Input: one or more files, each .parquet (a "text" column, e.g. nanochat's climbmix / FineWeb shards), .jsonl (one {"text": ...} per line, or a JSON string per line) or .txt (one document per blank-line-separated block). Stops after --max-tokens. python prepare_data.py --out data/climbmix_1b --max-tokens 1100000000 shard_00000.parquet shard_00001.parquet ... """ from __future__ import annotations import argparse import json import sys from pathlib import Path import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parent)) def read_docs(path): p = Path(path) if p.suffix == ".parquet": import pyarrow.parquet as pq pf = pq.ParquetFile(p) for rg in range(pf.num_row_groups): for t in pf.read_row_group(rg, columns=["text"]).column("text").to_pylist(): yield t elif p.suffix == ".jsonl": for line in open(p): r = json.loads(line) yield r if isinstance(r, str) else r["text"] else: for block in p.read_text().split("\n\n"): if block.strip(): yield block.strip() def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", required=True) ap.add_argument("--max-tokens", type=int, default=10 ** 12) ap.add_argument("files", nargs="+") a = ap.parse_args() from rlm_harness.data import Vocab V = Vocab() out = Path(a.out) out.mkdir(parents=True, exist_ok=True) starts, n = [0], 0 with open(out / "tokens.u16", "wb") as ft, open(out / "texts.jsonl", "w") as fx: batch = [] def flush(): nonlocal n for text, ids in zip(batch, V.encode_batch(batch, prepend_bos=True)): if n >= a.max_tokens: return True np.asarray(ids, dtype=np.uint16).tofile(ft) fx.write(json.dumps(text) + "\n") n += len(ids) starts.append(n) batch.clear() return False done = False for f in a.files: for t in read_docs(f): batch.append(t) if len(batch) >= 2048 and flush(): done = True break if done: break print(f"{f}: {n:,} tokens", file=sys.stderr) if not done: flush() np.save(out / "doc_starts.npy", np.asarray(starts, dtype=np.int64)) print(f"wrote {out}: {len(starts) - 1:,} documents, {n:,} tokens") if __name__ == "__main__": main()