Before BPE learns anything, a hand-written regex cuts the text into pretokens, and no token may ever cross a cut. Part II of Cartesia's From Tokens to Bytes posts prints the patterns. Python's built-in re has no \p{L} or \p{N}, so implement the two splitters directly, with character classes from unicodedata.
Character classes
unicodedata.category(ch) starts with "L". number: it starts with "N".ch.isspace() is true, except for "\x1c", "\x1d", "\x1e", "\x1f" (Python calls these whitespace; regex engines do not).Both splitters scan left to right. At each position the first rule that matches wins, its match becomes the next piece, and scanning resumes after it. "Space" below means the single character " ".
gpt2_split(text), pattern 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
s, t, re, ve, m, ll or d, lowercase only, tried in that order.cl100k_split(text), pattern (?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\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+
'VE counts).\r, \n, a letter or a number, then a maximal run of letters.\r or \n that directly follows.\r or \n: the run up to and including its last \r or \n.allowed_span(text, start, end, split)
split is one of the two functions. Return True if text[start:end] lies inside a single piece of split(text), and False if a cut falls strictly inside it. A BPE token trained with that pretokenizer can only cover those characters at that position if this is True.ValueError unless 0 <= start < end <= len(text).Both splitters return [] for "", and their pieces always join back to text.