"""Byte-level BPE tokenizer, written from scratch. Training: split text into "words" with a regex (GPT-4 style), count them, then repeatedly merge the most frequent adjacent pair of token ids. Pair counts are updated incrementally so training is fast even in pure Python. """ import heapq import json from collections import Counter, defaultdict import regex as re SPLIT_PATTERN = r"""'(?i:[sdmt]|ll|ve|re)|[^\r\n\p{L}\p{N}]?+\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]++[\r\n]*|\s*[\r\n]|\s+(?!\S)|\s+""" SPECIAL_TOKENS = ["<|endoftext|>", "<|user|>", "<|assistant|>", "<|end|>"] class Tokenizer: def __init__(self, merges=None, special_tokens=None): self.merges = merges or [] # list of (a, b); merge i creates id 256 + i self.pattern = re.compile(SPLIT_PATTERN) self._build(special_tokens or SPECIAL_TOKENS) def _build(self, special_tokens): self.ranks = {tuple(p): i for i, p 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] base = 256 + len(self.merges) self.special = {t: base + i for i, t in enumerate(special_tokens)} self.special_inv = {v: k for k, v in self.special.items()} self.special_re = re.compile("(" + "|".join(re.escape(t) for t in special_tokens) + ")") self.cache = {} @property def vocab_size(self): return 256 + len(self.merges) + len(self.special) # ---------------- training ---------------- @classmethod def train(cls, text_iter, vocab_size, verbose=True): pat = re.compile(SPLIT_PATTERN) counts = Counter() for text in text_iter: counts.update(pat.findall(text)) words = [list(w.encode("utf-8")) for w in counts] freqs = list(counts.values()) if verbose: print(f" {len(words):,} unique pre-tokens") pair_counts = defaultdict(int) where = defaultdict(set) for wi, (w, f) in enumerate(zip(words, freqs)): for p in zip(w, w[1:]): pair_counts[p] += f where[p].add(wi) heap = [(-c, p) for p, c in pair_counts.items()] heapq.heapify(heap) n_merges = vocab_size - 256 - len(SPECIAL_TOKENS) merges = [] while len(merges) < n_merges and heap: negc, pair = heapq.heappop(heap) cur = pair_counts.get(pair, 0) if cur <= 0: continue if -negc != cur: # stale entry, re-queue with the true count heapq.heappush(heap, (-cur, pair)) continue new_id = 256 + len(merges) merges.append(pair) a, b = pair for wi in list(where[pair]): w, f = words[wi], freqs[wi] if len(w) < 2: continue for p in zip(w, w[1:]): pair_counts[p] -= f nw, i = [], 0 while i < len(w): if i < len(w) - 1 and w[i] == a and w[i + 1] == b: nw.append(new_id) i += 2 else: nw.append(w[i]) i += 1 for p in zip(nw, nw[1:]): pair_counts[p] += f where[p].add(wi) heapq.heappush(heap, (-pair_counts[p], p)) words[wi] = nw del pair_counts[pair] where.pop(pair, None) if verbose and len(merges) % 500 == 0: print(f" merge {len(merges)}/{n_merges}") return cls(merges) # ---------------- encode / decode ---------------- def _encode_chunk(self, chunk): ids = self.cache.get(chunk) if ids is not None: return ids ids = list(chunk.encode("utf-8")) while len(ids) >= 2: best = min(zip(ids, ids[1:]), key=lambda p: self.ranks.get(p, 1 << 30)) r = self.ranks.get(best) if r is None: break new_id, nw, i = 256 + r, [], 0 while i < len(ids): if i < len(ids) - 1 and ids[i] == best[0] and ids[i + 1] == best[1]: nw.append(new_id) i += 2 else: nw.append(ids[i]) i += 1 ids = nw if len(self.cache) < 500_000: self.cache[chunk] = ids return ids def encode_ordinary(self, text): out = [] for chunk in self.pattern.findall(text): out.extend(self._encode_chunk(chunk)) return out def encode(self, text, allow_special=True): if not allow_special: return self.encode_ordinary(text) out = [] for part in self.special_re.split(text): if not part: continue if part in self.special: out.append(self.special[part]) else: out.extend(self.encode_ordinary(part)) return out def decode(self, ids): parts = [] for i in ids: if i in self.special_inv: parts.append(self.special_inv[i].encode("utf-8")) else: parts.append(self.vocab[i]) return b"".join(parts).decode("utf-8", errors="replace") # ---------------- persistence ---------------- def save(self, path): with open(path, "w") as f: json.dump({"type": "byte-level-bpe", "pattern": SPLIT_PATTERN, "merges": self.merges, "special_tokens": list(self.special)}, f) @classmethod def load(cls, path): with open(path) as f: d = json.load(f) return cls([tuple(m) for m in d["merges"]], d["special_tokens"]) def render_chat(tok, messages, add_generation_prompt=False): """<|endoftext|><|user|>...<|end|><|assistant|>...<|end|>... Returns (ids, mask) where mask=1 on tokens the model should learn to produce (assistant replies and their closing <|end|>).""" ids, mask = [tok.special["<|endoftext|>"]], [0] for m in messages: role = tok.special["<|user|>" if m["role"] == "user" else "<|assistant|>"] body = tok.encode_ordinary(m["content"]) + [tok.special["<|end|>"]] learn = 1 if m["role"] == "assistant" else 0 ids += [role] + body mask += [0] + [learn] * len(body) if add_generation_prompt: ids.append(tok.special["<|assistant|>"]) mask.append(0) return ids, mask