Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Keep reasoning when formatting chats with the gemma-4-thinking template (#16701)
Nilay846dac69906e
diff --git a/tests/test_gemma4_chat_template.py b/tests/test_gemma4_chat_template.pyindex ee32c796686..82c86b50a74 100644--- a/tests/test_gemma4_chat_template.py+++ b/tests/test_gemma4_chat_template.py@@ -275,14 +275,15 @@ def test_object_tool_result_renders_its_fields(name):)[email protected]("name", ["gemma4_template", "gemma4_thinking_template"])@pytest.mark.parametrize("key", ["reasoning_content", "reasoning"])-def test_final_turn_reasoning_becomes_the_thought_channel(key):+def test_final_turn_reasoning_becomes_the_thought_channel(name, key):msgs = [{"role": "user", "content": "2+2?"},{"role": "assistant", "content": "4", "reasoning_content": "first"},{"role": "user", "content": "3+3?"},{"role": "assistant", "content": "6", key: "3+3=6"},]- out = _render("gemma4_template", msgs)+ out = _render(name, msgs)assert "first" not in outassert out.endswith("<|turn>model\n<|channel>thought\n3+3=6\n<channel|>6<turn|>\n")diff --git a/tests/test_gemma4_empty_thought.py b/tests/test_gemma4_empty_thought.pyindex f5a622d5637..1650f3a59a1 100644--- a/tests/test_gemma4_empty_thought.py+++ b/tests/test_gemma4_empty_thought.py@@ -25,7 +25,7 @@ def _load():wanted_assign = {"gemma4_template","gemma4_thinking_template",- "_gemma4_model_turn",+ "_gemma4_thinking_prompt_empty_thought","gemma4_empty_thought_template","GEMMA4_TEMPLATE_NAMES","gemma4_empty_thought_ollama",@@ -101,9 +101,16 @@ def test_ignores_missing_or_non_string_templates():assert not NS["_gemma4_wants_empty_thought"](None, _Holder(None), _Holder(123))-def test_ignores_unsloth_thinking_template():- # Re-calling get_chat_template on an E2B tokenizer already carrying it must not switch.[email protected]("older_release", [False, True])+def test_ignores_unsloth_thinking_template(older_release):+ # Re-calling get_chat_template on an E2B tokenizer carrying it, even from an older release, must not switch.tmpl = "{{ bos_token }}" + NS["gemma4_thinking_template"]+ if older_release:+ tmpl = tmpl.replace(+ "{%- for message in loop_messages -%}",+ "{#- older -#}{%- for message in loop_messages -%}",+ 1,+ )assert not NS["_gemma4_wants_empty_thought"](_Holder(tmpl))diff --git a/unsloth/chat_templates.py b/unsloth/chat_templates.pyindex 603b6da8e20..d7466b05bae 100644--- a/unsloth/chat_templates.py+++ b/unsloth/chat_templates.py@@ -1452,6 +1452,8 @@ gemma4_thinking_template = \{{ '<turn|>\n' }}{%- endif -%}{%- set ns_tool = namespace(turns=0, tool_calls=false, tool_response=false) -%}+{%- set ns_turn = namespace(last_user_idx=-1) -%}+{%- for m in loop_messages -%}{%- if m['role'] == 'user' -%}{%- set ns_turn.last_user_idx = loop.index0 -%}{%- endif -%}{%- endfor -%}{%- for message in loop_messages -%}{%- if message['role'] != 'tool' -%}{%- set continues = message['role'] == 'assistant' and ns_tool.tool_calls -%}@@ -1467,6 +1469,12 @@ gemma4_thinking_template = \{%- set ns_tool.turns = ns_tool.turns + 1 -%}{{ '<|turn>' + role + '\n' }}{%- endif -%}+ {%- if role == "model" -%}+ {%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%}+ {%- if thinking_text and loop.index0 > ns_turn.last_user_idx -%}+ {{ '<|channel>thought\n' + thinking_text + '\n<channel|>' }}+ {%- endif -%}+ {%- endif -%}{%- set ns_tool.tool_calls = message.get('tool_calls') -%}{%- if ns_tool.tool_calls -%}{%- for tool_call in ns_tool.tool_calls -%}@@ -1589,26 +1597,12 @@ DEFAULT_SYSTEM_MESSAGE["gemma-4-thinking"] = NoneCHAT_TEMPLATES["gemma4-thinking"] = (gemma4_thinking_template, gemma4_template_eos_token, False, gemma4_ollama,)DEFAULT_SYSTEM_MESSAGE["gemma4-thinking"] = None-# 26B-A4B / 31B generate after an empty thought channel their template omits from history; final-turn reasoning fills it.-_gemma4_model_turn = "{{ '<|turn>' + role + '\n' }}\n"+# 26B-A4B / 31B generate after an empty thought channel their template omits from history; with thinking off, model turns without reasoning get it.gemma4_empty_thought_template = gemma4_thinking_template.replace(- _gemma4_model_turn + " {%- endif -%}\n",- _gemma4_model_turn + " {%- endif -%}\n" + \-""" {%- if role == "model" -%}- {%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%}- {%- if thinking_text and loop.index0 > ns_turn.last_user_idx -%}- {{ '<|channel>thought\n' + thinking_text + '\n<channel|>' }}- {%- elif not thinking and not continues -%}- {{ '<|channel>thought\n<channel|>' }}- {%- endif -%}- {%- endif -%}-""",- 1,-).replace(- "{%- for message in loop_messages -%}",- "{%- set ns_turn = namespace(last_user_idx=-1) -%}\n"- "{%- for m in loop_messages -%}{%- if m['role'] == 'user' -%}{%- set ns_turn.last_user_idx = loop.index0 -%}{%- endif -%}{%- endfor -%}\n"- "{%- for message in loop_messages -%}",+ " {{ '<|channel>thought\n' + thinking_text + '\n<channel|>' }}\n",+ " {{ '<|channel>thought\n' + thinking_text + '\n<channel|>' }}\n"+ " {%- elif not thinking and not continues -%}\n"+ " {{ '<|channel>thought\n<channel|>' }}\n",1,)assert gemma4_empty_thought_template != gemma4_thinking_template@@ -1630,6 +1624,9 @@ TEMPLATE """{{- range $i, $_ := .Messages }}{{- end }}"""'''GEMMA4_TEMPLATE_NAMES = ("gemma-4", "gemma4", "gemma-4-thinking", "gemma4-thinking",)+# Unsloth's gemma-4-thinking primes it in the generation prompt for every size, in every release+_gemma4_thinking_prompt_empty_thought = " {%- if not thinking -%}\n {{ '<|channel>thought\n<channel|>' }}\n {%- endif -%}\n"+assert _gemma4_thinking_prompt_empty_thought in gemma4_thinking_templatedef _gemma4_wants_empty_thought(*holders):@@ -1638,8 +1635,7 @@ def _gemma4_wants_empty_thought(*holders):template = getattr(holder, "chat_template", None)if isinstance(template, dict): template = template.get("default")if not isinstance(template, str): continue- # Unsloth's gemma-4-thinking primes it for every size- if template.endswith(gemma4_thinking_template): continue+ template = template.replace(_gemma4_thinking_prompt_empty_thought, "")if "<|channel>thought\\n<channel|>" in template or "<|channel>thought\n<channel|>" in template:return Truereturn False