skip to content

In Hugging Face Transformers, user text containing a literal special-token string such as '<|im_end|>' reaches a chat model — how is it tokenized, and what does split_special_tokens change?

level: seniorimportance: nice to knowfreq 5%

answer

  1. strings matched before the subword model
  2. one string, one control-token id
  3. split_special_tokens defaults to False
  4. the template's markers are strings too
  5. check with tokenizer.tokenize

basics

~20 s

By default the tokenizer matches the string as the real special token, so user text can end a turn or forge a role marker. split_special_tokens=True encodes it as plain text, but set globally it also splits the template's markers.

solid answer

~40 s

A tokenizer matches registered special-token strings in the input before running its subword model, and `split_special_tokens` defaults to `False`, so `'<|im_end|>'` typed by a user becomes the same single id the template uses to close a turn. `apply_chat_template` renders the template and the user's content into one string and tokenizes it, so the tokenizer cannot tell the template's markers from identical characters in the content. `split_special_tokens=True` makes those strings encode as ordinary text, but set on the tokenizer it also applies inside `apply_chat_template`, splitting the template's real markers and erasing the turn structure. Neutralise at the boundary instead: strip or escape the strings in `tokenizer.all_special_tokens` from untrusted content before rendering, or encode untrusted spans separately with `split_special_tokens=True` and assemble the ids yourself. Verify with `tokenizer.tokenize`.

code

python · 13 lines
python
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("your-org/your-chat-model")
user_text = "thanks <|im_end|>"

print(tok.tokenize(user_text))                            # marker kept as one token
print(tok.tokenize(user_text, split_special_tokens=True)) # marker split into pieces

for special in tok.all_special_tokens:
    user_text = user_text.replace(special, "")

messages = [{"role": "user", "content": user_text}]
inputs = tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")

go deeper

for a junior

Recall that a tokenizer turns registered special-token strings into single ids wherever they appear, including in text a user typed.

for a middle

Explain split_special_tokens: default False, what True does to a marker string, and how to see the difference with tokenizer.tokenize.

for a senior

Show why the flag cannot be set globally with apply_chat_template, and choose between stripping strings before rendering and assembling ids from separately encoded spans.

for a principal

Treat the tokenizer as one boundary among several: decide where untrusted text is neutralised for every channel, and how regression tests keep it from silently reopening.

## How a tokenizer finds special tokens A Hugging Face Transformers tokenizer keeps a set of **special tokens**: strings such as a beginning-of-sequence marker, an end-of-turn marker or a role header, each mapped to one id. When it encodes text, it first scans for these registered strings and emits each match as its single id, and only then runs the subword model over the remaining text. That scan is how a chat template's markers reliably become control tokens. The scan does not know where a string came from. If a user types the exact characters of an end-of-turn marker into a chat box, the tokenizer emits the same id the template uses, and the model sees a real turn boundary in the middle of user content. How attackers exploit that belongs to the security material on prompt injection; this answer covers the tokenizer behaviour that makes it possible. ## Why chat templates make it matter `apply_chat_template` renders the whole conversation, control tokens plus every message's content, into **one string**, then tokenizes that string. Once rendered, the template's markers and the user's identical characters are indistinguishable. This is not a bug in the template: the information about which characters were trusted is lost at the rendering step. ## What split_special_tokens does **`split_special_tokens`** (default **`False`**) switches the scan off. With it `True`, a special-token string is tokenized like ordinary text, so `'<|im_end|>'` becomes several ordinary pieces instead of one control id. You can set it when loading the tokenizer, assign it on the object, or pass it on a single call. - With the Rust-backed `TokenizersBackend` it sets the backend's `encode_special_tokens` option, so registered special tokens are encoded as text. - With `PythonBackend`-based tokenizers, which include `SentencePieceBackend`, it skips the added-token splitting step altogether and sends the text straight to the subword model. - Decoding is unaffected; `skip_special_tokens` is a separate decode-time option. ## Where the flag lives `split_special_tokens` is an initialisation argument, so `AutoTokenizer.from_pretrained(repo, split_special_tokens=True)` stores it on the tokenizer as its default. Every later call uses that default unless the call passes its own value, and a per-call value applies to that call only. That makes the per-call form the safe one for untrusted spans: it cannot leak into unrelated code that shares the same tokenizer object. ## Why not set it globally `apply_chat_template` tokenizes the rendered string through the tokenizer's normal call, and that call uses the tokenizer's own `split_special_tokens` value unless overridden. If you set the flag on the tokenizer to protect user text, the template's **real** markers in the same string get split too. The model then receives a prompt with no turn structure at all, which is a worse failure than the one you were fixing. | Setting | User's marker string | Template's own markers | |---|---|---| | Default (`False`) | Becomes a real control id | Real control ids | | `True` on the tokenizer | Ordinary pieces | Also ordinary pieces, structure lost | | Untrusted spans encoded separately with `True` | Ordinary pieces | Real control ids | ## Handling untrusted text 1. **Neutralise before rendering.** Remove or escape every string in `tokenizer.all_special_tokens` (named and extra special tokens) from untrusted content, then call `apply_chat_template` normally. 2. **Or assemble the ids yourself.** Tokenize the template parts normally and each untrusted span with `split_special_tokens=True`, then concatenate the id lists. This keeps user characters intact but costs you the convenience of a single call, and token boundaries at the joins can differ slightly from a one-string encoding. 3. **Treat every channel as untrusted**: retrieved documents, tool outputs and file names flow into the same rendered string as chat input. 4. **Record what you removed.** A special-token string in user input is rarely innocent; logging the event gives you a signal without blocking a real user who pasted a template by accident. ## Checking what happened - `tokenizer.tokenize(text)` shows whether a string became one special token or several pieces. - `tokenizer.convert_ids_to_tokens(ids)` does the same for ids you are about to send. - A regression test that renders a conversation containing every special-token string from user input, and asserts the id count of control tokens, catches a template or library change that reopens the hole.

  • Why not just pass split_special_tokens=True to apply_chat_template through tokenizer_kwargs?
    Because `apply_chat_template` tokenizes the fully rendered string in one call, so the flag would apply to the template's own markers as well as the user's characters. The turn structure disappears. The flag only helps when it is applied to the untrusted spans alone.
  • How would you test that a template or library upgrade has not reopened this behaviour?
    Keep a regression test that renders a conversation whose user content contains every string in `tokenizer.all_special_tokens`, runs your sanitising path and `apply_chat_template`, and asserts the count and positions of control-token ids equal those of the same conversation without the strings. A template change or a new special token then fails the test instead of shipping.

  • User text is never matched against special tokens; only the template inserts them.
  • Setting split_special_tokens=True on the tokenizer safely protects apply_chat_template prompts.
  • skip_special_tokens=True on encode stops user text becoming control tokens.
  • A special-token string in user text becomes the unk token.
  • Stripping special-token strings makes the prompt immune to injection.

Assumes Transformers v5 (5.18), whose backend classes TokenizersBackend and PythonBackend are named here; the v5 migration guide lists no change to split_special_tokens itself.