#!/usr/bin/env python3 """Train a Polish byte-level BPE (32k) on a domain-balanced sample of the corpus, then report fertility vs GPT-2 BPE. Runs where the parquet shards live (slayer).""" import glob, sys, time import pyarrow.parquet as pq from tokenizers import Tokenizer, models, trainers, pre_tokenizers, decoders DATA = "/home/ubuntu/dynaword/data" OUT = "/home/ubuntu/dynaword/polish_bpe_32k.json" CAP = 220 * 1024 * 1024 # ~220 MB text per source -> balances away the 71% legal skew VOCAB = 32768 def files(): return sorted(glob.glob(f"{DATA}/*/*.parquet")) def balanced_texts(): for f in files(): src = f.split("/")[-2]; got = 0; done = False for batch in pq.ParquetFile(f).iter_batches(columns=["text"], batch_size=1000): for x in batch.column("text"): s = x.as_py() if not s: continue yield s got += len(s) if got >= CAP: done = True; break if done: break print(f" sampled {src}: ~{got/1e6:.0f} MB", file=sys.stderr, flush=True) t0 = time.time() tok = Tokenizer(models.BPE(unk_token=None)) tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) tok.decoder = decoders.ByteLevel() trainer = trainers.BpeTrainer( vocab_size=VOCAB, min_frequency=2, special_tokens=["<|endoftext|>"], initial_alphabet=pre_tokenizers.ByteLevel.alphabet()) print("training BPE...", file=sys.stderr, flush=True) tok.train_from_iterator(balanced_texts(), trainer=trainer) tok.save(OUT) print(f"trained in {time.time()-t0:.0f}s | vocab={tok.get_vocab_size()} | saved {OUT}") # fertility vs GPT-2 on a held-out-ish sample (later docs of wikipedia, general domain) import tiktoken gpt2 = tiktoken.get_encoding("gpt2") sample = [] for b in pq.ParquetFile(f"{DATA}/wikipedia/wikipedia.parquet").iter_batches(columns=["text"], batch_size=1000): for x in b.column("text"): sample.append(x.as_py()) if len(sample) >= 6000: break sample = sample[4000:6000] # avoid the head used in training words = sum(len(s.split()) for s in sample) chars = sum(len(s) for s in sample) ours = sum(len(e.ids) for e in tok.encode_batch(sample)) g2 = sum(len(x) for x in gpt2.encode_ordinary_batch(sample)) print(f"\nFertility on {len(sample)} held-out PL docs ({words:,} words):") print(f" polish-32k : {ours/words:.3f} tok/word | {ours/chars:.3f} tok/char") print(f" gpt2-50k : {g2/words:.3f} tok/word | {g2/chars:.3f} tok/char") print(f" -> {g2/ours:.2f}x fewer tokens with the Polish BPE")