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.

Signaturedef 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplesplit_special('hi<|eot|>yo', ['<|eot|>'])
  • Sample 2: longest matchsplit_special('x<|ab|>y<|a', ['<|a', '<|ab|>'])
  • Test 3: back to backsplit_special('<s><s>a', ['<s>'])
  • Test 4: nonesplit_special('plain text', ['<|eot|>'])