Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/source/chat_templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ TRL ships patched templates under [`trl/chat_templates/`](https://github.com/hug

## Supported model families

TRL stores reference copies of the original templates so it can identify supported models at init and swap in a training template when needed. The following families are recognized: Cohere, Cohere2, DeepSeek-V3 (including DeepSeek-R1, DeepSeek-R1-0528, DeepSeek-V3-0324 and DeepSeek-V3.1), DeepSeek-R1-Distill, DiffusionGemma, Gemma, Gemma3, Gemma4 (including Gemma-4-12B, Gemma-4-26B-A4B and Gemma-4-31B), GLM-4-MoE (4.5, 4.6, 4.7), GLM-5, GLM-5.1, GLM-5.2, GLM-5.3, GLM-5.3-Flash, GPT-OSS, Idefics3, LFM2, LFM2.5 (including LFM2.5-1.2B-Instruct, LFM2.5-2.6B and LFM2.5-24B-A2B), LFM2.5-VL (including LFM2.5-VL-450M), Llama 3 / 3.1 / 3.2, Llava-Next, Mistral Large 4, Mistral Medium 3.5, Muse Glimmer, Muse Spark Open, Nemotron 3 (Nano, Super, Ultra), Nemotron 3.5 Lightning, Phi-3, Phi-3.5, Phi-4, Phi-4-mini (including Phi-4-mini-flash-reasoning), Phi-4-mini-reasoning, Qwen2-VL, Qwen2.5 (including the base checkpoints), Qwen2.5-VL, Qwen3 (including the Instruct-2507 and Thinking-2507 variants), Qwen3-Coder (including Qwen3-Coder-Next), Qwen3-VL, Qwen3.5, Qwen3.6, Qwen3.8, SmolLM2, SmolVLM (including SmolVLM2).
TRL stores reference copies of the original templates so it can identify supported models at init and swap in a training template when needed. The following families are recognized: Cohere, Cohere2, DeepSeek-V3 (including DeepSeek-R1, DeepSeek-R1-0528, DeepSeek-V3-0324 and DeepSeek-V3.1), DeepSeek-R1-Distill, DiffusionGemma, Gemma, Gemma3, Gemma4 (including Gemma-4-12B, Gemma-4-26B-A4B and Gemma-4-31B), GLM-4-MoE (4.5, 4.6, 4.7), GLM-5, GLM-5.1, GLM-5.2, GLM-5.3, GLM-5.3-Flash, GPT-OSS, Idefics3, Laguna (XS.2, M.1, XS-2.1, S-2.1), LFM2, LFM2.5 (including LFM2.5-1.2B-Instruct, LFM2.5-2.6B and LFM2.5-24B-A2B), LFM2.5-VL (including LFM2.5-VL-450M), Llama 3 / 3.1 / 3.2, Llava-Next, Mistral Large 4, Mistral Medium 3.5, Muse Glimmer, Muse Spark Open, Nemotron 3 (Nano, Super, Ultra), Nemotron 3.5 Lightning, Phi-3, Phi-3.5, Phi-4, Phi-4-mini (including Phi-4-mini-flash-reasoning), Phi-4-mini-reasoning, Qwen2-VL, Qwen2.5 (including the base checkpoints), Qwen2.5-VL, Qwen3 (including the Instruct-2507 and Thinking-2507 variants), Qwen3-Coder (including Qwen3-Coder-Next), Qwen3-VL, Qwen3.5, Qwen3.6, Qwen3.8, SmolLM2, SmolVLM (including SmolVLM2).

## Training templates

Expand Down
4 changes: 4 additions & 0 deletions scripts/check_chat_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
"nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16",
"openai/gpt-oss-20b",
"poolside/Laguna-M.1",
"poolside/Laguna-S-2.1",
"poolside/Laguna-XS-2.1",
"poolside/Laguna-XS.2",
"Qwen/Qwen2-VL-2B-Instruct",
"Qwen/Qwen2.5-0.5B",
"Qwen/Qwen2.5-32B-Instruct",
Expand Down
40 changes: 40 additions & 0 deletions tests/test_chat_template_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@
has_generation_markers,
is_chat_template_prefix_preserving,
is_chat_template_stop_token_trained,
laguna_chat_template,
laguna_v2_chat_template,
laguna_v3_chat_template,
laguna_v4_chat_template,
lfm2_2_5_v2_chat_template,
lfm2_2_5_v4_chat_template,
lfm2_2_5_vl_v2_chat_template,
Expand Down Expand Up @@ -512,6 +516,42 @@ def test_add_response_schema_glm_think_prefill(self, tokenizer_name, chat_templa
response = tokenizer(completion, add_special_tokens=False).input_ids
assert parse_response(tokenizer, response, prefix=prefix.input_ids) == expected

@pytest.mark.parametrize(
"chat_template",
[
pytest.param(laguna_chat_template, id="laguna"),
pytest.param(laguna_v2_chat_template, id="laguna-v2"),
pytest.param(laguna_v3_chat_template, id="laguna-v3"),
pytest.param(laguna_v4_chat_template, id="laguna-v4"),
],
)
@pytest.mark.parametrize("enable_thinking", [False, True])
@pytest.mark.skipif(
not _SUPPORTS_RESPONSE_TEMPLATE,
reason="Laguna only gets a new-style response template, which requires transformers>=5.13",
)
def test_add_response_schema_laguna(self, chat_template, enable_thinking):
# No tiny Laguna model yet: parsing only depends on the rendered text, so borrow a tokenizer
tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3ForCausalLM")
tokenizer.chat_template = chat_template
tokenizer = add_response_schema(tokenizer)
tool_calls = [
{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}},
{"type": "function", "function": {"name": "get_weather", "arguments": {"city": "Paris (FR), France"}}},
]
assistant = {"role": "assistant", "content": "Let me check.", "tool_calls": tool_calls}
if enable_thinking:
assistant["reasoning_content"] = "Hmmm."
messages = [{"role": "user", "content": "What is 3*4?"}, assistant]
prefix = tokenizer.apply_chat_template(
messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True, enable_thinking=enable_thinking
)
text = tokenizer.apply_chat_template(
messages, tokenize=True, return_dict=True, enable_thinking=enable_thinking
)
response = text.input_ids[len(prefix.input_ids) :]
assert parse_response(tokenizer, response, prefix=prefix.input_ids, tools=[multiply]) == assistant

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Newline breaks Laguna content round-trip

Medium Severity

The shared Laguna round-trip test expects content to equal Let me check. for every template, but laguna.jinja and laguna_v2.jinja emit a newline after the text when tool_calls follow. laguna_template closes content at <tool_call> (no leading whitespace) rather than at </assistant>, so that newline stays in content and the assertion fails for those two templates. Parsed GRPO messages would carry the same trailing newline.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 96efd18. Configure here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not an issue: the content field uses the text content parser, which strips the text by default (strip=True, transformers ≥ 5.13). The trailing newline that laguna.jinja and laguna_v2.jinja emit before <tool_call> doesn't reach content. test_add_response_schema_laguna passes for all four templates, with and without thinking.


@pytest.mark.parametrize(
"completion, expected",
[
Expand Down
48 changes: 48 additions & 0 deletions trl/chat_template_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,37 @@ def clone_chat_template(
},
}

laguna_template = {
# Same tool-call format as `glm4moe_template`. The generation prompt pre-fills `<think>` (thinking) or `</think>`:
# the anchor consumes it, and reasoning opens only if a `</think>` follows
"defaults": {"role": "assistant"},
"start_anchor_pattern": r"<assistant>\n?(?:<think>|</think>\n?)?",
"fields": {
"reasoning_content": {
"open_pattern": r"\s*(?:<think>)?\n?(?=[\s\S]*?</think>)",
"close_pattern": r"\n?</think>\s*",
"content": "text",
},
"tool_calls": {
# Laguna-XS.2 and Laguna-M.1 put a newline after the name and between key and value; the 2.1 templates
# put none
"open_pattern": r"<tool_call>(?P<name>[^<\s]+)\s*",
"close_pattern": r"</tool_call>\s*",
"repeats": True,
"content": "xml-inline",
"content_args": {
"tag_pattern": r"<arg_key>(?P<key>[^<]+)</arg_key>\s*<arg_value>(?P<value>.*?)</arg_value>",
"value_parser": _XML_INLINE_VALUE_PARSER,
},
"transform": {"type": "function", "function": {"name": "{name}", "arguments": "{content}"}},
},
"content": {
"close_pattern": r"\s*</assistant>\s*|$",
"content": "text",
},
},
}

llama3_template = {
"defaults": {"role": "assistant"},
"start_anchor": "<|start_header_id|>assistant<|end_header_id|>\n\n",
Expand Down Expand Up @@ -723,6 +754,14 @@ def clone_chat_template(

idefics3_chat_template = (_CHAT_TEMPLATES_DIR / "idefics3.jinja").read_text(encoding="utf-8")

laguna_chat_template = (_CHAT_TEMPLATES_DIR / "laguna.jinja").read_text(encoding="utf-8")

laguna_v2_chat_template = (_CHAT_TEMPLATES_DIR / "laguna_v2.jinja").read_text(encoding="utf-8")

laguna_v3_chat_template = (_CHAT_TEMPLATES_DIR / "laguna_v3.jinja").read_text(encoding="utf-8")

laguna_v4_chat_template = (_CHAT_TEMPLATES_DIR / "laguna_v4.jinja").read_text(encoding="utf-8")

lfm2_chat_template = (_CHAT_TEMPLATES_DIR / "lfm2.jinja").read_text(encoding="utf-8")

lfm2_v2_chat_template = (_CHAT_TEMPLATES_DIR / "lfm2_v2.jinja").read_text(encoding="utf-8")
Expand Down Expand Up @@ -892,6 +931,15 @@ def add_response_schema(processing_class: ProcessingClassT) -> ProcessingClassT:
schema, template = None, glm4moe_template
elif chat_template in [gptoss_chat_template, gptoss_training_chat_template]:
schema, template = gptoss_schema, gptoss_template
elif chat_template in [
laguna_chat_template,
laguna_v2_chat_template,
laguna_v3_chat_template,
laguna_v4_chat_template,
]:
# Only the new-style template; the legacy `response_schema` is being removed upstream
# (huggingface/transformers#47320).
schema, template = None, laguna_template
elif chat_template in [llama3_1_chat_template, llama3_2_chat_template]:
schema, template = llama3_schema, llama3_template
elif chat_template in [
Expand Down
16 changes: 16 additions & 0 deletions trl/chat_templates/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,22 @@ Original GPT-OSS chat template.

Original Idefics3 chat template (as shipped by `HuggingFaceM4/Idefics3-8B-Llama3`). Does not support tool calling.

### `laguna.jinja`

Original Laguna chat template (as shipped by `poolside/Laguna-XS.2`). Wraps turns in `<user>` / `<assistant>` tags and writes tool calls in the same format as `glm4moe.jinja` (`<tool_call>name\n<arg_key>key</arg_key>\n<arg_value>value</arg_value>\n</tool_call>`). The generation prompt pre-fills `<think>` with `enable_thinking=True` and `</think>` otherwise. The template already has `{% generation %}` markers and is prefix-preserving, so it needs no training template. Response parsing uses `laguna_template`.

### `laguna_v2.jinja`

Laguna-M.1 chat template (as shipped by `poolside/Laguna-M.1`). Same as `laguna.jinja`, except that it has no default system message. Response parsing uses `laguna_template`.

### `laguna_v3.jinja`

Laguna 2.1 chat template (as shipped by `poolside/Laguna-XS-2.1`). Same as `laguna.jinja`, without the newlines around the turns, the reasoning and the tool-call arguments (`<tool_call>name<arg_key>key</arg_key><arg_value>value</arg_value></tool_call>`), and without the tool-call format instructions in the system message. It renders the reasoning of assistant turns only with `enable_thinking=True`. Response parsing uses `laguna_template`.

### `laguna_v4.jinja`

Laguna 2.1 chat template (as shipped by `poolside/Laguna-S-2.1`). Same as `laguna_v3.jinja`, except that thinking is enabled by default and `preserve_thinking=True` also renders the reasoning with thinking disabled. Response parsing uses `laguna_template`.

### `lfm2.jinja`

Original LFM2 chat template (as shipped by `LiquidAI/LFM2-*` checkpoints). ChatML-style. Renders `tools` into the system prompt wrapped in `<|tool_list_start|>` / `<|tool_list_end|>`, and wraps `tool` message content in `<|tool_response_start|>` / `<|tool_response_end|>`. It never reads `message['tool_calls']` though, so assistant tool calls are silently dropped: the model is trained to emit `<|tool_call_start|>` / `<|tool_call_end|>` as plain text inside `content`.
Expand Down
132 changes: 132 additions & 0 deletions trl/chat_templates/laguna.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
{#- Iteration on laguna_glm_thinking_v5/chat_template.jinja -#}
{#- Adds a default system message (used when no system message is provided in `messages`). -#}
{{- "〈|EOS|〉" -}}
{%- set enable_thinking = enable_thinking | default(false) -%}
{%- set render_assistant_messages_raw = render_assistant_messages_raw | default(false) -%}
{%- set add_generation_prompt = add_generation_prompt | default(false) -%}

{#- ───── header (system message) ───── -#}
{%- set system_message = "You are a helpful, conversationally-fluent assistant made by Poolside. You are here to be helpful to users through natural language conversations." -%}
{%- if messages and messages[0].role == "system" -%}
{%- set system_message = messages[0].content -%}
{%- endif -%}

{%- if (system_message and system_message.strip()) or tools -%}
{{- "<system>\n" -}}

{%- if system_message and system_message.strip() -%}
{{- "\n" -}}
{{- system_message.rstrip() -}}
{%- endif -%}

{%- if tools -%}
{{- "\n\n### Tools\n\n" -}}
{%- set ns = namespace(tool_string="You may call functions to assist with the user query.\n"
~ "All available function signatures are listed below:\n"
~ "<available_tools>\n") -%}
{%- for tool in tools -%}
{%- set ns.tool_string = ns.tool_string ~ (tool | tojson) ~ "\n" -%}
{%- endfor -%}
{%- if enable_thinking -%}
{%- set tool_string = ns.tool_string + "</available_tools>\n\n" ~
"Wrap your thinking in '<think>', '</think>' tags, followed by a function call. For each function call, return an unescaped XML-like object with function name and arguments within '<tool_call>' and '</tool_call>' tags, like here:\n" ~
"<think> your thoughts here </think>\n" ~
"<tool_call>function-name\n<arg_key>argument-key</arg_key>\n<arg_value>value-of-argument-key</arg_value>\n" ~
"</tool_call>" -%}
{%- else -%}
{%- set tool_string = ns.tool_string + "</available_tools>\n\n" ~
"For each function call, return an unescaped XML-like object " ~
"with function name and arguments within '<tool_call>' and '</tool_call>' tags, like here:\n" ~
"<tool_call>function-name\n<arg_key>argument-key</arg_key>\n<arg_value>value-of-argument-key</arg_value>\n" ~
"</tool_call>" -%}
{%- endif -%}
{{- tool_string -}}
{%- endif -%}

{{- "\n</system>\n" -}}
{%- endif -%}

{#- ───── main loop ───── -#}
{%- for message in messages -%}
{%- set content = message.content if message.content is string else "" -%}
{%- if message.role == "user" -%}
{{- "<user>\n" + content + "\n</user>\n" -}}
{%- elif message.role == "assistant" -%}
{%- generation -%}
{{- "<assistant>\n" -}}
{%- if render_assistant_messages_raw -%}
{#- Raw mode: prepend the generation prompt token, then dump content verbatim. -#}
{#- The generation prompt is <think> when enable_thinking, </think> otherwise. -#}
{#- Only prepend if content doesn't already start with it. -#}
{%- if enable_thinking -%}
{%- if not content.startswith('<think>') -%}
{{- '<think>' -}}
{%- endif -%}
{%- else -%}
{%- if not content.startswith('</think>') -%}
{{- '</think>' -}}
{%- endif -%}
{%- endif -%}
{{- content -}}
{#- Append closing tag if content doesn't already end with it. -#}
{%- if not content.endswith('</assistant>\n') and not content.endswith('</assistant>') -%}
{{- '\n</assistant>' -}}
{%- endif -%}
{{- "\n" -}}
{%- else -%}
{#- Extract reasoning content from message.reasoning (vLLM field name) or message.reasoning_content, or from <think> tags -#}
{%- set reasoning_content = '' %}
{%- if message.reasoning is string %}
{%- set reasoning_content = message.reasoning %}
{%- elif message.reasoning_content is string %}
{%- set reasoning_content = message.reasoning_content %}
{%- endif %}
{#- Always strip <think> tags from content if present to avoid duplication -#}
{%- if '</think>' in content %}
{%- if not reasoning_content %}
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
{%- endif %}
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
{%- endif %}
{#- Display reasoning content for all messages -#}
{%- if reasoning_content -%}
{{- '<think>\n' + reasoning_content.strip() + '\n</think>\n' -}}
{%- else -%}
{{- '</think>\n' -}}
{%- endif -%}
{#- Display main content -#}
{%- if content.strip() -%}
{{- content.strip() ~ "\n" -}}
{%- endif -%}
{%- if message.tool_calls -%}
{%- for tool_call in message.tool_calls -%}
{%- set function_data = tool_call.function -%}
{{- '<tool_call>' + function_data.name }}
{% set _args = function_data.arguments %}
{%- for k, v in _args.items() -%}
{{- "<arg_key>" ~ k ~ "</arg_key>\n" -}}
{{- "<arg_value>"}}{{ v | tojson(ensure_ascii=False) if v is not string else v }}{{ "</arg_value>\n" -}}
{%- endfor -%}
{{- "</tool_call>\n" -}}
{%- endfor -%}
{%- endif -%}
{{- "</assistant>\n" -}}
{%- endif -%}
{%- endgeneration -%}
{%- elif message.role == "tool" -%}
{{- "<tool_response>\n" + content + "\n</tool_response>\n" -}}
{%- elif message.role == "system" and loop.index0 != 0 -%}
{#- Render additional system messages (skip the first one which is handled separately in the header) -#}
{{- "<system>\n" + content + "\n</system>\n" -}}
{%- endif -%}
{%- endfor -%}
{#- ───── generation prompt ───── -#}
{%- if add_generation_prompt -%}
{{- "<assistant>\n" -}}
{#- ───── Include reasoning mode directive ───── -#}
{%- if not enable_thinking %}
{{- '</think>' -}}
{%- else %}
{{- '<think>' -}}
{%- endif %}
{%- endif -%}
Loading
Loading