initialize_system_prompt can make mistake when the chat template is not strictly append-only
System Info
python: 3.11.15
transformers: 5.8.1
This is a tokenizer-only reproduction. It does not require GPUs, Ray, SGLang, vLLM, or an end-to-end training run.
Information
The problem arises when using:
- [ ] The official example scripts
- [x] My own modified scripts
The script only imports verl.utils.chat_template.initialize_system_prompt and uses an official Hugging Face tokenizer.
Tasks
The tasks I am working on are:
- [ ] An officially supported task in the
examplesfolder - [x] My own task or dataset
This issue is about the tokenizer/chat-template utility used by the agent gateway, not a specific training dataset.
Description
verl.utils.chat_template.initialize_system_prompt currently probes a tokenizer with:
token1 = tokenizer.apply_chat_template(
[{"role": "user", "content": ""}],
add_generation_prompt=False,
tokenize=True,
)
token2 = tokenizer.apply_chat_template(
[{"role": "user", "content": ""}] * 2,
add_generation_prompt=False,
tokenize=True,
)
system_prompt = token1[: -(len(token2) - len(token1))]
This assumes that rendering [user, user] is append-only relative to rendering [user].
That assumption is false for templates that add eos_token only after the whole rendered conversation when add_generation_prompt=False. In that case, the diff between token2 and token 1 is not exactly token1, and the length-diff extraction can return ordinary message header tokens instead of an implicit system prompt.
Information
- [ ] The official example scripts
- [ ] My own modified scripts
Tasks
- [ ] An officially supported task in the
examplesfolder (such as GLUE/SQuAD, ...) - [ ] My own task or dataset (give details below)
Reproduction
For example, with microsoft/Phi-3-mini-4k-instruct, the function extracts <|user|> as the system prompt even though this template has no implicit system prompt.
Save the following as scripts/reproduce_system_prompt_header_misextraction_issue.py and run it from the repository root:
PYTHONPATH=. python scripts/reproduce_system_prompt_header_misextraction_issue.py
#!/usr/bin/env python3
from __future__ import annotations
import platform
import transformers
from transformers import AutoTokenizer
from verl.utils.chat_template import initialize_system_prompt
from verl.utils.tokenizer import normalize_token_ids
def decode(tokenizer, ids: list[int]) -> str:
return tokenizer.decode(ids, skip_special_tokens=False)
def main() -> None:
print("Environment")
print(f"python: {platform.python_version()}")
print(f"transformers: {transformers.__version__}")
model = "microsoft/Phi-3-mini-4k-instruct"
tokenizer = AutoTokenizer.from_pretrained(model)
print(f"\nmodel: {model}")
print(f"eos_token: {tokenizer.eos_token!r} ({tokenizer.eos_token_id})")
one_user = [{"role": "user", "content": ""}]
two_users = [{"role": "user", "content": ""}, {"role": "user", "content": ""}]
for name, messages in [("one_user", one_user), ("two_users", two_users)]:
text = tokenizer.apply_chat_template(messages, add_generation_prompt=False, tokenize=False)
ids = normalize_token_ids(tokenizer.apply_chat_template(messages, add_generation_prompt=False, tokenize=True))
print(f"\n{name} text:")
print(repr(text))
print(f"{name} ids:")
print(ids)
print(f"{name} decoded:")
print(repr(decode(tokenizer, ids)))
system_prompt = initialize_system_prompt(tokenizer)
print("\ninitialize_system_prompt result:")
print(system_prompt)
print(repr(decode(tokenizer, system_prompt)))
print("\nexpected: [] because this template has no implicit system prompt")
print("actual: [32010], decoded as '<|user|>'")
message = [{"role": "user", "content": "hello"}]
full_new_message_ids = normalize_token_ids(
tokenizer.apply_chat_template(message, add_generation_prompt=True, tokenize=True)
)
incremental_like_ids = full_new_message_ids[len(system_prompt) :]
print("\nEffect on gateway-style incremental encoding for a new user message:")
print("full standalone new-message prompt:")
print(repr(decode(tokenizer, full_new_message_ids)))
print("after stripping extracted system_prompt:")
print(repr(decode(tokenizer, incremental_like_ids)))
print("The '<|user|>' header is removed, so the incremental prompt is malformed.")
if __name__ == "__main__":
main()
Observed output:
Environment
python: 3.11.15
transformers: 5.8.1
model: microsoft/Phi-3-mini-4k-instruct
eos_token: '<|endoftext|>' (32000)
one_user text:
'<|user|>\n<|end|>\n<|endoftext|>'
one_user ids:
[32010, 32007, 32000]
one_user decoded:
'<|user|>\n<|end|>\n<|endoftext|>'
two_users text:
'<|user|>\n<|end|>\n<|user|>\n<|end|>\n<|endoftext|>'
two_users ids:
[32010, 32007, 32010, 32007, 32000]
two_users decoded:
'<|user|>\n<|end|>\n<|user|>\n<|end|>\n<|endoftext|>'
initialize_system_prompt result:
[32010]
'<|user|>'
expected: [] because this template has no implicit system prompt
actual: [32010], decoded as '<|user|>'
Effect on gateway-style incremental encoding for a new user message:
full standalone new-message prompt:
'<|user|> hello<|end|><|assistant|>'
after stripping extracted system_prompt:
'hello<|end|><|assistant|>'
The '<|user|>' header is removed, so the incremental prompt is malformed.
Expected behavior
initialize_system_prompt should not infer ordinary message header tokens, such as Phi-3's <|user|>, as an implicit system prompt.
If no implicit system prompt exists, the function should return [].
More generally, the extraction logic should not rely on the assumption that:
apply_chat_template([user, user]) == apply_chat_template([user]) + appended_delta
because some official chat templates add final conversation-level tokens, such as eos_token, after the whole message loop.
More broadly, this system-prompt-stripping path may be worth deprecating. For incremental message encoding, deriving delta tokens by rendering a dummy context and diffing the rendered text, for example dummy user / assistant context plus the appended messages, is a more robust path than extracting and stripping a global system_prompt prefix.
Another "append-only" assumption also affects the multi-turn rollout encoding in the agent loop.
Current multi-turn agent (i.e., ToolAgentLoop) builds the token sequence incrementally. Specifically, _handle_processing_tools_state renders only the tool response via self.apply_chat_template(add_messages, remove_system_prompt=True), which starts at <|im_start|> and has no leading \n either. So at the assistant→tool boundary the framework produces:
... </tool_call><|im_end|><|im_start|>user\n<tool_response> ... # incrementally append tool response
while apply_chat_template of the equivalent full conversation produces:
... </tool_call><|im_end|>\n<|im_start|>user\n<tool_response> ... # reference
The single \n turn-separator token (id 198 for Qwen) is silently dropped at every turn boundary.
Reproduction scripts:
#!/usr/bin/env python3
from transformers import AutoTokenizer
from verl.utils.chat_template import apply_chat_template, initialize_system_prompt
from verl.utils.tokenizer import normalize_token_ids
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
user_msg = {"role": "user", "content": "What is the weather in Paris?"}
assistant_text = '<tool_call>\n{"name": "get_weather", "arguments": {"city": "Paris"}}\n</tool_call>'
tool_msg = {"role": "tool", "content": "sunny, 25C"}
# computed once in AgentLoopBase.__init__, later stripped from every follow-up turn
system_prompt = initialize_system_prompt(tokenizer)
# _handle_pending_state: initial prompt fed to the first model call
prompt_ids = apply_chat_template(tokenizer, [user_msg], tokenize=True, add_generation_prompt=True)
# mimic the LLM generation call: the model emits assistant_text and stops AT <|im_end|>;
# it never emits the template's trailing "\n" after <|im_end|>
assistant_ids = tokenizer.encode(assistant_text, add_special_tokens=False) + [
tokenizer.convert_tokens_to_ids("<|im_end|>")
]
# mirror ToolAgentLoop's incremental append of the tool message (tool_agent_loop.py:380-385):
# self.apply_chat_template(add_messages, remove_system_prompt=True)
# renders only the new tool turn and strips the system-prompt prefix
tool_ids = normalize_token_ids(
apply_chat_template(tokenizer, [tool_msg], tokenize=True, add_generation_prompt=True)
)[len(system_prompt):]
incremental_ids = prompt_ids + assistant_ids + tool_ids
# reference: render the whole conversation at once
reference_ids = normalize_token_ids(
apply_chat_template(
tokenizer,
[user_msg, {"role": "assistant", "content": assistant_text}, tool_msg],
tokenize=True,
add_generation_prompt=True,
)
)
print("equal?", incremental_ids == reference_ids, "| incremental:", len(incremental_ids), "reference:", len(reference_ids))
print("incremental:\n", tokenizer.decode(incremental_ids))
print("reference :\n", tokenizer.decode(reference_ids))
Output:
equal? False | incremental: 54 reference: 55
incremental:
<|im_start|>user
What is the weather in Paris?<|im_end|>
<|im_start|>assistant
<tool_call>
{"name": "get_weather", "arguments": {"city": "Paris"}}
</tool_call><|im_end|><|im_start|>user
<tool_response>
sunny, 25C
</tool_response><|im_end|>
<|im_start|>assistant
reference :
<|im_start|>user
What is the weather in Paris?<|im_end|>
<|im_start|>assistant
<tool_call>
{"name": "get_weather", "arguments": {"city": "Paris"}}
</tool_call><|im_end|>
<|im_start|>user
<tool_response>
sunny, 25C
</tool_response><|im_end|>
<|im_start|>assistant
where \n is missing in this incremental appending manner.