File size: 4,306 Bytes
ebf8f81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
"""Tiny BPE tokenizer for the storyteller.

Deliberately simple so the exact same algorithm can run in the browser:
1. Clean text to plain ASCII.
2. Split into "pre-tokens" (words with their leading space, punctuation, newlines).
3. Inside each pre-token, apply learned merges in order of rank.
"""
import json, re, sys, collections

EOS = "<|endoftext|>"
PAT = re.compile(r"'(?:s|t|re|ve|m|ll|d)\b| ?[A-Za-z]+| ?[0-9]| ?[^\sA-Za-z0-9]|\n| +")
BASE = ["\n"] + [chr(i) for i in range(32, 127)]

_REPL = {"’": "'", "‘": "'", "“": '"', "”": '"', "—": " - ",
         "–": "-", "…": "...", " ": " ", "\r": ""}


def clean(text):
    for a, b in _REPL.items():
        text = text.replace(a, b)
    return "".join(c for c in text if c == "\n" or 32 <= ord(c) < 127)


def split_stories(raw):
    for s in raw.split(EOS):
        s = clean(s).strip()
        if len(s) > 50:
            yield s


class Tokenizer:
    def __init__(self, merges):
        self.merges = [tuple(m) for m in merges]
        self.vocab = [EOS] + BASE + [a + b for a, b in self.merges]
        self.ids = {t: i for i, t in enumerate(self.vocab)}
        self.rank = {m: i for i, m in enumerate(self.merges)}
        self.cache = {}

    @property
    def eos(self):
        return 0

    def _bpe(self, word):
        if word in self.cache:
            return self.cache[word]
        parts = list(word)
        while len(parts) > 1:
            best, bi = None, -1
            for i in range(len(parts) - 1):
                r = self.rank.get((parts[i], parts[i + 1]))
                if r is not None and (best is None or r < best):
                    best, bi = r, i
            if best is None:
                break
            parts[bi:bi + 2] = [parts[bi] + parts[bi + 1]]
        out = [self.ids[p] for p in parts]
        if len(self.cache) < 200000:
            self.cache[word] = out
        return out

    def encode(self, text):
        out = []
        for w in PAT.findall(clean(text)):
            out.extend(self._bpe(w))
        return out

    def decode(self, ids):
        return "".join(self.vocab[i] for i in ids if i != 0)

    def save(self, path):
        json.dump({"merges": self.merges}, open(path, "w"))

    @classmethod
    def load(cls, path):
        return cls(json.load(open(path))["merges"])


def train(text_path, vocab_size, out_path, max_bytes=60_000_000):
    raw = open(text_path, encoding="utf-8", errors="ignore").read(max_bytes)
    counts = collections.Counter()
    for s in split_stories(raw):
        counts.update(PAT.findall(s))
    words = [(list(w), c) for w, c in counts.items()]
    n_merges = vocab_size - 1 - len(BASE)
    merges = []
    # pair -> count, and pair -> set of word indices
    pair_counts = collections.Counter()
    where = collections.defaultdict(set)
    for wi, (sym, c) in enumerate(words):
        for a, b in zip(sym, sym[1:]):
            pair_counts[(a, b)] += c
            where[(a, b)].add(wi)
    for step in range(n_merges):
        if not pair_counts:
            break
        pair = max(pair_counts, key=pair_counts.get)
        merges.append(pair)
        a, b = pair
        new = a + b
        for wi in list(where[pair]):
            sym, c = words[wi]
            for x, y in zip(sym, sym[1:]):
                pair_counts[(x, y)] -= c
                if pair_counts[(x, y)] <= 0:
                    del pair_counts[(x, y)]
            i, out = 0, []
            while i < len(sym):
                if i < len(sym) - 1 and sym[i] == a and sym[i + 1] == b:
                    out.append(new); i += 2
                else:
                    out.append(sym[i]); i += 1
            words[wi] = (out, c)
            for x, y in zip(out, out[1:]):
                pair_counts[(x, y)] += c
                where[(x, y)].add(wi)
        where.pop(pair, None)
        if step % 500 == 0:
            print(f"merge {step}/{n_merges}: {new!r}", flush=True)
    tok = Tokenizer(merges)
    tok.save(out_path)
    return tok


if __name__ == "__main__":
    tok = train(sys.argv[1], int(sys.argv[2]), sys.argv[3])
    s = "Once upon a time, there was a little cat named Tom. He didn't like rain."
    ids = tok.encode(s)
    print(len(s), "chars ->", len(ids), "tokens:", [tok.vocab[i] for i in ids])
    assert tok.decode(ids) == s