Skip to content

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.

Ollama Phi-4 template: write roles as text, not <|user|> pseudo tokens (#17285)

Jae Birdsallb2784e3e6db1
diff --git a/tests/test_ollama_phi4_roles.py b/tests/test_ollama_phi4_roles.py
new file mode 100644
index 00000000000..e1fba22decc
--- /dev/null
+++ b/tests/test_ollama_phi4_roles.py
@@ -0,0 +1,21 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+import os
+import re
+import runpy
+
+MAPPERS_PATH = os.path.join(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
+ "unsloth",
+ "ollama_template_mappers.py",
+)
+OLLAMA_TEMPLATES = runpy.run_path(MAPPERS_PATH)["OLLAMA_TEMPLATES"]
+
+
+def test_phi4_roles_are_plain_text():
+ body = re.search(r'TEMPLATE """(.*?)"""', OLLAMA_TEMPLATES["phi-4"], re.S).group(1)
+ # Phi-4's vocab has no <|user|>-style role tokens; they would tokenize as plain text.
+ for role in ("system", "user", "assistant"):
+ assert f"<|{role}|>" not in body
+ assert f"<|im_start|>{role}<|im_sep|>" in body
diff --git a/unsloth/chat_templates.py b/unsloth/chat_templates.py
index beb0f440f26..5de363f73c2 100644
--- a/unsloth/chat_templates.py
+++ b/unsloth/chat_templates.py
@@ -874,11 +874,6 @@ phi4_template = \
"{{ '<|im_start|>assistant<|im_sep|>' }}"\
"{% endif %}"
-_phi4_ollama_template = \
- "{{ if .System }}<|im_start|><|system|><|im_sep|>{{ .System }}<|im_end|>{{ end }}"\
- "{{ if .Prompt }}<|im_start|><|user|><|im_sep|>{{ .Prompt }}<|im_end|>{{ end }}"\
- "<|im_start|><|assistant|><|im_sep|>{{ .Response }}<|im_end|>"
-
# Ollama from https://www.ollama.com/library/phi4 is different
phi4_ollama = _ollama_template("phi-4")
diff --git a/unsloth/ollama_template_mappers.py b/unsloth/ollama_template_mappers.py
index 9c26bd0d24a..9a4d54b1adf 100644
--- a/unsloth/ollama_template_mappers.py
+++ b/unsloth/ollama_template_mappers.py
@@ -975,9 +975,9 @@ OLLAMA_TEMPLATES["qwen-2"] = qwen25_ollama
# =========================================== Phi-4
_phi4_ollama_template = (
- "{{ if .System }}<|im_start|><|system|><|im_sep|>{{ .System }}<|im_end|>{{ end }}"
- "{{ if .Prompt }}<|im_start|><|user|><|im_sep|>{{ .Prompt }}<|im_end|>{{ end }}"
- "<|im_start|><|assistant|><|im_sep|>{{ .Response }}<|im_end|>"
+ "{{ if .System }}<|im_start|>system<|im_sep|>{{ .System }}<|im_end|>{{ end }}"
+ "{{ if .Prompt }}<|im_start|>user<|im_sep|>{{ .Prompt }}<|im_end|>{{ end }}"
+ "<|im_start|>assistant<|im_sep|>{{ .Response }}<|im_end|>"
)
# The ollama.com/library/phi4 template is different.