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.

Make auto-appended EOS deterministic in chat templates (#7702)

Vineeth Sai Varikuntla2eae08cc2877
diff --git a/tests/python/test_construct_chat_template_validation.py b/tests/python/test_construct_chat_template_validation.py
index 53d281d4351..1f73b6edf29 100644
--- a/tests/python/test_construct_chat_template_validation.py
+++ b/tests/python/test_construct_chat_template_validation.py
@@ -194,3 +194,47 @@ def test_static_prefix_without_system_still_rejects_system_message():
{"role": "user", "content": "Hi"},
],
)
+
+
+def test_auto_appended_eos_prefers_the_tokenizer_eos_deterministically():
+ """When the template has no EOS after {OUTPUT}, construct_chat_template appends one
+ itself and picks `extra_eos_tokens[0]`. `extra_eos_tokens.insert(0, tokenizer.eos_token)`
+ exists to make that the tokenizer's own EOS, so the choice must not depend on set
+ ordering: de-duplicating through `set()` made the appended token, and therefore the
+ token ending every formatted training sample, vary with PYTHONHASHSEED."""
+
+ class _TwoEosTokenizer(_SuccessFakeTokenizer):
+ def get_vocab(self):
+ return {"</s>": 0, "<|myeos|>": 2}
+
+ _, jinja_template, _, _ = construct_chat_template(
+ tokenizer = _TwoEosTokenizer(),
+ chat_template = (
+ "### User: {INPUT}\n### Assistant: {OUTPUT}\n"
+ "### User: {INPUT}\n### Assistant: {OUTPUT}\n"
+ ),
+ default_system_message = None,
+ extra_eos_tokens = ["<|myeos|>"],
+ )
+ assistant_turn = jinja_template.split("'assistant' %}")[1].split("{% else %}")[0]
+ assert _TwoEosTokenizer.eos_token in assistant_turn
+ assert "<|myeos|>" not in assistant_turn
+
+
+def test_input_boundary_prefers_the_longest_eos_token():
+ class _PrefixEosTokenizer(_SuccessFakeTokenizer):
+ def get_vocab(self):
+ return {"</s>": 0, "</s>extra": 2}
+
+ _, jinja_template, _, _ = construct_chat_template(
+ tokenizer = _PrefixEosTokenizer(),
+ chat_template = (
+ "### User: {INPUT}</s>extra\n### Assistant: {OUTPUT}</s>\n"
+ "### User: {INPUT}</s>extra\n### Assistant: {OUTPUT}</s>\n"
+ ),
+ default_system_message = None,
+ extra_eos_tokens = ["</s>extra"],
+ )
+
+ rendered_user_turn = _render(jinja_template, [{"role": "user", "content": "Hi"}])
+ assert rendered_user_turn == "### User: Hi</s>extra"
diff --git a/unsloth/chat_templates.py b/unsloth/chat_templates.py
index 27abf9a75fb..0c49b870334 100644
--- a/unsloth/chat_templates.py
+++ b/unsloth/chat_templates.py
@@ -2444,7 +2444,9 @@ extra_eos_tokens = None,
"Unsloth: Base llama-3 models did not train <|eot_id|>.\n"\
"Please use the instruct version or use <|end_of_text|>"
)
- extra_eos_tokens = list(set(extra_eos_tokens))
+ # dict.fromkeys, not set: `extra_eos_tokens.insert(0, tokenizer.eos_token)` above
+ # sets a priority that `extra_eos_tokens[0]` relies on when appending the EOS.
+ extra_eos_tokens = list(dict.fromkeys(extra_eos_tokens))
count_eos = 0
for eos in extra_eos_tokens:
@@ -2483,7 +2485,9 @@ extra_eos_tokens = None,
final_combined_check = left if final_combined_check else chat_template
# Isolate input
- extra_eos_tokens_regex = "|".join(f"(?:{re.escape(x)})" for x in extra_eos_tokens)
+ # Regex alternations prefer the first match, so match prefix tokens last.
+ eos_tokens_for_matching = sorted(extra_eos_tokens, key = len, reverse = True)
+ extra_eos_tokens_regex = "|".join(f"(?:{re.escape(x)})" for x in eos_tokens_for_matching)
if len(extra_eos_tokens_regex) != 0:
find_end = f"(?:{extra_eos_tokens_regex})?"
else: