verl icon indicating copy to clipboard operation
verl copied to clipboard

initialize_system_prompt fails on alternating-role chat templates

Open gxlvera opened this issue 6 months ago • 2 comments

Overview

initialize_system_prompt fails on chat templates that require alternating roles

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 examples folder
  • [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 valid. That assumption is false for official chat templates that require alternating user/assistant/user/assistant/... roles after the optional system message.

For those templates, initialize_system_prompt raises during initialization even though the tokenizer itself is valid. For example, this error is raised when using mistralai/Mistral-7B-Instruct-v0.2

Information

  • [ ] The official example scripts
  • [x] My own modified scripts

Tasks

  • [ ] An officially supported task in the examples folder (such as GLUE/SQuAD, ...)
  • [x] My own task or dataset (give details below)

Reproduction

Save the following as scripts/reproduce_system_prompt_alternating_roles_issue.py and run it from the repository root:

PYTHONPATH=. python scripts/reproduce_system_prompt_alternating_roles_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


def main() -> None:
    print("Environment")
    print(f"python: {platform.python_version()}")
    print(f"transformers: {transformers.__version__}")

    model = "mistralai/Mistral-7B-Instruct-v0.2"
    tokenizer = AutoTokenizer.from_pretrained(model)

    print(f"\nmodel: {model}")

    one_user = [{"role": "user", "content": ""}]
    two_users = [{"role": "user", "content": ""}, {"role": "user", "content": ""}]

    print("\none user renders:")
    print(repr(tokenizer.apply_chat_template(one_user, add_generation_prompt=False, tokenize=False)))

    print("\ntwo consecutive users render:")
    try:
        print(repr(tokenizer.apply_chat_template(two_users, add_generation_prompt=False, tokenize=False)))
    except Exception as exc:
        print(f"{type(exc).__name__}: {exc}")

    print("\ninitialize_system_prompt result:")
    try:
        system_prompt = initialize_system_prompt(tokenizer)
        print(system_prompt)
        print(repr(tokenizer.decode(system_prompt, skip_special_tokens=False)))
    except Exception as exc:
        print(f"{type(exc).__name__}: {exc}")


if __name__ == "__main__":
    main()

Observed output:

Environment
python: 3.11.15
transformers: 5.8.1

model: mistralai/Mistral-7B-Instruct-v0.2

one user renders:
'<s> [INST]  [/INST]'

two consecutive users render:
TemplateError: After the optional system message, conversation roles must alternate user/assistant/user/assistant/...

initialize_system_prompt result:
TemplateError: After the optional system message, conversation roles must alternate user/assistant/user/assistant/...

Expected behavior

initialize_system_prompt should not construct invalid probe conversations for templates that require alternating roles.

We should construct a valid conversation considering templates requiring alternating roles. For templates:

[
    {"role": "user", "content": ""},
    {"role": "assistant", "content": ""},
    {"role": "user", "content": ""},
    {"role": "assistant", "content": ""},
]

That avoids relying on the invalid [user, user] conversation shape.

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.

gxlvera avatar May 27 '26 07:05 gxlvera

I think this issue comes from initialize_system_prompt assuming that rendering two consecutive empty user messages is always valid.

That is not true for chat templates that enforce alternating roles. In those templates, [user, user] is not a valid conversation shape, so the helper can fail during initialization even though the tokenizer/template itself is valid.

anzhsoft avatar May 29 '26 02:05 anzhsoft

My current plan is to make the system prompt inference validate the rendered token structure instead of relying only on the [user, user] length difference.

For templates that reject consecutive users, the helper can fall back to a valid alternating probe such as [user, assistant, user]. For templates that are not strictly append-only, it should avoid treating ordinary message header tokens as an implicit system prompt.

This should address both this issue and #6501. I will submit a PR with a focused fix and CPU-only regression tests.

anzhsoft avatar May 29 '26 02:05 anzhsoft