#!/usr/bin/env python3 """Tokenize the corpus with the Polish BPE into modded-nanogpt/llm.c shards. Single process: tokenizers' encode_batch parallelises across cores via Rust rayon natively — NO mp.Pool (nesting mp.Pool x rayon oversubscribes and is ~4x slower). Format: 256 int32 header [magic 20240520, version 1, ntok] + uint16 tokens. Docs joined with <|endoftext|>; ~1/200 docs held out for validation.""" import glob, os, time import numpy as np import pyarrow.parquet as pq from tokenizers import Tokenizer TOKJSON = "/home/ubuntu/dynaword/polish_bpe_32k.json" DATA = "/home/ubuntu/dynaword/data" OUT = "/home/ubuntu/dynaword/shards" SHARD = 100_000_000 VAL_EVERY = 200 CHUNK = 50_000 # docs per encode_batch call os.makedirs(OUT, exist_ok=True) def doc_stream(): for f in sorted(glob.glob(f"{DATA}/*/*.parquet")): for b in pq.ParquetFile(f).iter_batches(columns=["text"], batch_size=2000): for x in b.column("text"): s = x.as_py() if s: yield s def write_shard(path, arr): h = np.zeros(256, dtype=np.int32); h[0] = 20240520; h[1] = 1; h[2] = len(arr) with open(path, "wb") as f: f.write(h.tobytes()); f.write(arr.tobytes()) def main(): tok = Tokenizer.from_file(TOKJSON) EOT = tok.token_to_id("<|endoftext|>") print(f"EOT={EOT} | shard={SHARD:,} | val 1/{VAL_EVERY} | chunk={CHUNK}", flush=True) buf = np.empty(SHARD + 2_000_000, dtype=np.uint16); tn = 0; sidx = 0 val = [] di = 0; total = 0; t0 = time.time() chunk = [] def flush_chunk(): nonlocal tn, sidx, di, total if not chunk: return for e in tok.encode_batch(chunk): # rayon -> all cores, single process ids = e.ids # EOT PREFIX (BOS before each doc) -> matches modded-nanogpt align_to_bos if di % VAL_EVERY == 0: val.append(EOT); val.extend(ids) else: buf[tn] = EOT; tn += 1 m = len(ids) buf[tn:tn+m] = ids; tn += m if tn >= SHARD: write_shard(f"{OUT}/polish_train_{sidx:06d}.bin", buf[:tn]) total += tn; sidx += 1; tn = 0 di += 1 chunk.clear() print(f" {di:,} docs | {(total+tn)/1e9:.2f}B train tok | {len(val)/1e6:.1f}M val | {time.time()-t0:.0f}s", flush=True) for s in doc_stream(): chunk.append(s) if len(chunk) >= CHUNK: flush_chunk() flush_chunk() if tn: write_shard(f"{OUT}/polish_train_{sidx:06d}.bin", buf[:tn]); total += tn; sidx += 1 write_shard(f"{OUT}/polish_val_000000.bin", np.array(val, dtype=np.uint16)) print(f"\nDONE: {sidx} train shards, {total:,} train tok, {len(val):,} val tok | " f"{di:,} docs | {time.time()-t0:.0f}s", flush=True) if __name__ == "__main__": main()