pocket-storyteller / code /tokenizer.py
Redhanuman's picture
Pocket Storyteller: 4.6 MB story model, browser demo, weights and training code
ebf8f81 verified
Raw History Blame Contribute Delete
4.31 kB
"""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