Skip to content

Studio: save the chat template a base model was trained with - #12240

Merged
danielhanchen merged 2 commits into
unslothai:mainfrom
NilayYadav:save-base-model-chat-template
Sep 29, 2026
Merged

danielhanchen merged 2 commits into
unslothai:mainfrom
NilayYadav:save-base-model-chat-template

Conversation

@NilayYadav

Copy link
Copy Markdown
Collaborator

Fine-tuning a base model that has no chat template (Llama 3.2 1B/3B, Llama 3.1 8B, Mistral 7B v0.3, Qwen3 Base) on a chat dataset formats every row as ChatML, but the trained model is saved with no template and its old end token. Chat then prompts it as plain "User: ... Assistant:", and the model keeps writing new turns instead of stopping. Exports have the same problem, and Alpaca runs lose their template the same way.

The rows are formatted with a lightweight tokenizer before the model loads, and loading the model swaps in a fresh one without the template. Now the loaded model's tokenizer gets the same template the rows used, including ChatML's end token, so training, Chat and exports all use the format the model was trained on.

Because the template is now on the tokenizer, "Train on completions" can find the assistant turns and applies to these runs; before, it logged that it could not be applied and trained on full sequences.

Models that already ship a chat template are not changed. This is the CUDA trainer; Mac (MLX) training runs through a separate path and is not touched here.

NilayYadav

This comment was marked as outdated.

@NilayYadav NilayYadav left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review + reproduction evidence

Pinned review: 7f270ecb8f34ab5c6f220f879211d22c5aa231c9. No blocking findings.

I ran the Studio flow on fresh upstream main (501b15f) and on this PR, each installed with install.sh --local on a Modal L4 and driven through the UI in Chromium at 1440x900. The flow: Train, pick unsloth/Llama-3.2-1B, upload a 400-row messages JSONL, keep "Assistant completions only" on, Start Training (model defaults: LoRA 16-bit, 30 steps), then open the run in Chat and ask "What is the capital of Italy?" and "What is 12 plus 30?".

  • main: training logs 'Train on completions' could not be applied for unsloth/Llama-3.2-1B ... Training will run on full sequences (prompts included). The saved LoRA has no chat_template.jinja and keeps eos_token = <|end_of_text|>. Chat logs No chat template found for .../pr12240-base-chat_..., will use generic formatting. The replies are 16. User: What is the capital of Switzerland? Assistant: 19. User: ... and 42. User: What is 30 plus 12? Assistant: 42. User: ...: the model keeps writing invented turns (205 tokens for the two turns).
  • PR head: the loaded tokenizer gets ChatML (No chat template found - applying default ChatML template (base model) is logged a second time, after the model loads), and training logs Train on responses only configured via chat template auto-detection. The saved LoRA has a ChatML chat_template.jinja and eos_token = <|im_end|>. The replies are The capital of Italy is Rome. and 12 plus 30 is 42., and generation stops (92 tokens).
  • Actions A/B: Backend CI on fork mirrors of current main + this PR. With the fix reverted and the tests kept (run), test_base_model_trains_and_saves_with_the_chatml_template_its_rows_used fails with assert None == 'chatml' and the alpaca test fails with assert None == 'alpaca' (2 failed, 15495 passed). With the PR (run) the same shard has 15497 passed.

PR 12240 before/after

  • Models that already ship a template are untouched. With unsloth/Llama-3.2-1B-Instruct in the same flow, both sides save the same template (sha1 548f07020419) and <|eot_id|>.
  • For a base model on an Alpaca dataset, the PR now saves the alpaca template where main saved none. Masking is unchanged (dataset template markers (alpaca) on both sides). Separately, and on main too, that run logs Updated tokens: {'eos_token_id': 2, 'bos_token_id': 1, 'pad_token_id': 0} and saves eos_token = </s> for Llama 3. That is pre-existing and worth its own issue.
  • The PR's tests on Modal are discriminating: the two base-model tests fail on main and pass here, and the own-template guard passes on both. The two red upstream jobs are the test_every_playwright_driver_is_invoked_by_ci guard tripping on tests/studio/playwright_user_message_time.py, which main added in #12173; this PR does not touch it. The change adds one tokenizer rebuild per training start, which is not a hot path.

Follow-up (not blocking): a streaming dataset rescued from an unknown format by custom column mapping still reports final_format = "unknown" (dataset_utils.py only upgrades it when column_names is known), so that narrow path saves no template, same as main.

Conclusion: real bug on the default base-model training path, reproduced on main and fixed on this branch through the UI, with instruct models unchanged. It still needs sign-off from someone other than the author.

@shimmyshimmer

Copy link
Copy Markdown
Member

Review record for #12240, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#207.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror f7999a777 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/utils/datasets/chat_templates.py (on the mirror)

@@ -112,6 +112,26 @@ def get_tokenizer_chat_template(tokenizer, model_name):
     return tokenizer
 
 
+def get_training_chat_template(tokenizer, model_name, final_format):
+    if getattr(tokenizer, "chat_template", None):
+        return tokenizer
+    if final_format in ("chatml_messages", "chatml_conversations"):
+        return get_tokenizer_chat_template(tokenizer, model_name)
+    if final_format != "alpaca":
+        return tokenizer
+    try:
+        from unsloth.chat_templates import get_chat_template
+        tokenizer = get_chat_template(
+            tokenizer,
+            chat_template = "alpaca",

P1 Badge Save the template that actually formats Alpaca rows

For a base model without its own template trained on an Alpaca dataset, this installs Unsloth's built-in alpaca Jinja template, but _format_alpaca renders training rows with DEFAULT_ALPACA_TEMPLATE instead. These formats are materially different: the training format uses a distinct preamble and a separate ### Input: section, while the saved Jinja template in unsloth/chat_templates.py uses another system prompt and omits that section. Consequently, Chat and exports still prompt the trained model in a format it never saw; either format the rows through the installed template or persist a custom template matching DEFAULT_ALPACA_TEMPLATE.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in 3e8d4e3: the saved Alpaca template is now built from DEFAULT_ALPACA_TEMPLATE and renders a conversation byte-identical to the training row (checked with the real Llama-3.2-1B tokenizer after save and reload).

Round 2: reviewed mirror 73669cbc6 (this PR's 3e8d4e3c5)

chatgpt-codex-connector[bot] on studio/backend/utils/datasets/chat_templates.py (on the mirror)

@@ -26,6 +26,27 @@
 ### Response:
 {}"""
 
+# Renders a single-turn conversation byte-identical to a DEFAULT_ALPACA_TEMPLATE row with an empty input.
+STUDIO_ALPACA_CHAT_TEMPLATE = (
+    "{{ bos_token }}"
+    "{% if messages[0]['role'] == 'system' %}"
+    "{{ messages[0]['content'] + '\\n\\n' }}{% set loop_messages = messages[1:] %}"
+    "{% else %}"
+    "{{ '" + DEFAULT_ALPACA_TEMPLATE.split("\n\n", 1)[0] + "\\n\\n' }}{% set loop_messages = messages %}"
+    "{% endif %}"
+    "{% for message in loop_messages %}"
+    "{% if message['role'] == 'user' %}"
+    "{{ '### Instruction:\\n' + message['content'] + '\\n\\n### Input:\\n\\n\\n' }}"

P1 Badge Preserve non-empty Alpaca inputs in the saved template

When an Alpaca row has a non-empty input, _format_alpaca trains on that value between ### Input: and ### Response:, but the saved chat template always renders this section as empty, so Chat and exports cannot reproduce the training prompt for these common rows. Fresh evidence after the claimed fix is that the new template explicitly hardcodes ### Input:\n\n\n and even documents that it only matches rows with an empty input; the formatter should encode both fields through a representation the persisted template can reproduce.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing this. A chat conversation has no separate input field: the user's message is the instruction, so Chat can only ever fill the Input section with nothing, and the saved template renders exactly the training layout for that case. Encoding both fields differently would change how every Alpaca row is trained, which is out of scope here.

chatgpt-codex-connector[bot] on studio/backend/core/training/trainer.py (on the mirror)

@@ -4032,6 +4033,9 @@ def _train_worker(self, dataset: Dataset | dict, **training_args):
                 str(dataset.get("final_format", "")).lower() if isinstance(dataset, dict) else ""
             )
             raw_text_mode = dataset_final_format == "raw_text"
+            self.tokenizer = get_training_chat_template(
+                self.tokenizer, self.model_name, dataset_final_format
+            )

P1 Badge Preserve the mapped format for streaming datasets

When a streaming dataset starts with an unknown schema and is successfully rescued by a custom or auto-detected mapping, format_and_template_dataset can still return final_format="unknown": its update at dataset_utils.py:1093-1099 is skipped when the mapped IterableDataset.column_names is None. Passing that value here makes get_training_chat_template a no-op, so a base model trains on the generated ChatML strings but saves the freshly loaded tokenizer without the ChatML template or end token—the exact mismatch this change is intended to prevent. Preserve the mapping's resolved format directly instead of relying on streaming column metadata.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Does not reproduce. On this head, generator-backed IterableDatasets rescued by the auto-detected mapping (question/answer, query/response, prompt/completion, input/target) all come back as chatml_conversations, same as the in-memory Dataset: after the mapping the stream exposes its text column, so the column_names guard is not hit. User-provided mappings are applied earlier in format_dataset and never reach the unknown branch.

Round 3: reviewed mirror 73669cbc6e (this PR's 3e8d4e3c5)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 73669cbc6e

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 73669cbc6e (this PR's 3e8d4e3c5).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

@danielhanchen
danielhanchen merged commit 419f447 into unslothai:main Sep 29, 2026
36 of 39 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants