File size: 2,627 Bytes
cfe406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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")