"""Byte-level BPE tokenizer.""" import heapq import json import re from collections import Counter, defaultdict # Split text into words first so merges never cross word boundaries. # Leading spaces stay attached to the word (" world"), like GPT-2. PAT = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?[^\W\d_]+| ?\d{1,3}| ?[^\s\w]+|\s+(?!\S)|\s+""") class BPETokenizer: def __init__(self, merges=None): self.merges = merges or [] # merge i creates token id 256 + i self.ranks = {pair: i for i, pair in enumerate(self.merges)} self.vocab = {i: bytes([i]) for i in range(256)} for i, (a, b) in enumerate(self.merges): self.vocab[256 + i] = self.vocab[a] + self.vocab[b] self.eot_id = 256 + len(self.merges) # end-of-text, last id self.vocab_size = self.eot_id + 1 self.cache = {} @classmethod def train(cls, texts, vocab_size, verbose=True): n_merges = vocab_size - 257 word_freq = Counter() for text in texts: word_freq.update(PAT.findall(text)) words = [list(w.encode("utf-8")) for w in word_freq] freqs = list(word_freq.values()) if verbose: print(f"{len(words):,} unique words, learning {n_merges:,} merges") # Work on unique words weighted by count. `where` tracks which words contain # each pair so a merge only touches those words. counts = defaultdict(int) where = defaultdict(set) for wi, w in enumerate(words): for p in zip(w, w[1:]): counts[p] += freqs[wi] where[p].add(wi) # Max-heap of (-count, pair). Entries go stale as counts change; we skip # stale ones when popping instead of deleting them. heap = [(-c, p) for p, c in counts.items()] heapq.heapify(heap) merges = [] for m in range(n_merges): best = None while heap: c, p = heapq.heappop(heap) if counts.get(p, 0) == -c > 0: best = p break if best is None or counts[best] < 2: break new_id = 256 + m merges.append(best) a, b = best changed = set() for wi in list(where[best]): w, f = words[wi], freqs[wi] for p in zip(w, w[1:]): changed.add(p) counts[p] -= f if counts[p] <= 0: del counts[p] where[p].discard(wi) out, i = [], 0 while i < len(w): if i < len(w) - 1 and w[i] == a and w[i + 1] == b: out.append(new_id) i += 2 else: out.append(w[i]) i += 1 words[wi] = out for p in zip(out, out[1:]): changed.add(p) counts[p] += f where[p].add(wi) counts.pop(best, None) where.pop(best, None) for p in changed: if counts.get(p, 0) > 0: heapq.heappush(heap, (-counts[p], p)) if verbose and (m + 1) % 1000 == 0: print(f" {m + 1}/{n_merges}") return cls(merges) def _encode_word(self, word): if word in self.cache: return self.cache[word] ids = list(word.encode("utf-8")) # Apply merges in the order they were learned (lowest rank first). while len(ids) > 1: best, best_rank = None, None for i in range(len(ids) - 1): r = self.ranks.get((ids[i], ids[i + 1])) if r is not None and (best_rank is None or r < best_rank): best, best_rank = i, r if best is None: break ids[best:best + 2] = [256 + best_rank] if len(self.cache) < 2_000_000: self.cache[word] = ids return ids def encode(self, text): out = [] for w in PAT.findall(text): out.extend(self._encode_word(w)) return out def decode(self, ids): b = b"".join(self.vocab[i] for i in ids if i != self.eot_id) return b.decode("utf-8", errors="replace") def save(self, path): with open(path, "w") as f: json.dump({"merges": self.merges}, f) @classmethod def load(cls, path): with open(path) as f: return cls([tuple(p) for p in json.load(f)["merges"]])