Split text so special tokens stay whole
Why it matters Tokenizers for chat models do this split first; getting it wrong lets a template marker turn into several ordinary tokens.
Chat templates use markers like <|im_start|> that must become one id each. Before normal BPE runs, the text is split so these markers are isolated.
Write split_special(text, specials). specials is a list of strings. Scan text left to right. At each position, if any special starts there, take the LONGEST such special as its own segment. Otherwise the character belongs to the current normal segment. Return a list of (segment, is_special) tuples in order, with no empty normal segments.
def split_special(text, specials)Example
split_special("hi<|eot|>yo", ["<|eot|>"]) is [("hi", False), ("<|eot|>", True), ("yo", False)].
Understand the idea
Special tokens are like stamps on a letter: they must stay in one piece. If the tokenizer splits "<|eot|>" into "<", "|", "eot" and so on, the model never sees the single id it was trained on.
Text "x<|ab|>y<|a" with specials <|a and <|ab|>. At index 1 both specials start. Longest first picks <|ab|> (6 chars) and jumps to index 7. "y" goes to the buffer. At index 8, <|a matches. Result: ("x", normal), ("<|ab|>", special), ("y", normal), ("<|a", special).
Rule: at position i, among specials s with text.startswith(s, i), choose the longest; flush the buffer, emit s, set i += len(s). Else append text[i] to the buffer.
Production tokenizers do this before BPE so each chat marker, end-of-text token and tool-call tag maps to exactly one id. Many also refuse special strings inside user text unless allowed, to stop prompt injection through fake markers.