Tracking: Add `{% generation %}` chat templates for common model families
Context
SFT with assistant_only_loss=True requires the chat template to include {% generation %} / {% endgeneration %} markers so that return_assistant_tokens_mask=True can produce correct masks. Very few models ship these markers natively.
TRL should provide training chat templates with these markers for known model families (via get_training_chat_template()), and the SFT trainer auto-applies them when assistant_only_loss=True.
This issue tracks adding training templates for all model families with chat template support.
What needs to happen for each model
- Create
<model>_training.jinja: the original template with{% generation %}/{% endgeneration %}added around assistant output (and prefix-preservation fixes if needed) - Load it in
chat_template_utils.pyand add a branch inget_training_chat_template() - Add a test verifying text output is identical to the original and masks are correct
Model families
Causal LMs with chat template
- [x] Qwen2.5 https://github.com/huggingface/trl/pull/5522
- [x] Qwen3 https://github.com/huggingface/trl/pull/5470
- [x] Qwen3-2507 (Instruct) https://github.com/huggingface/trl/pull/5574
- [x] Qwen3.5 https://github.com/huggingface/trl/pull/5824
- [x] Qwen3.6 https://github.com/huggingface/trl/pull/5642
- [x] Cohere https://github.com/huggingface/trl/pull/5627
- [x] Cohere2 https://github.com/huggingface/trl/pull/5675
- [x] DeepSeek-V3 https://github.com/huggingface/trl/pull/5527
- [x] Gemma https://github.com/huggingface/trl/pull/5523
- [x] Gemma2 https://github.com/huggingface/trl/pull/5523
- [x] GLM-4-MoE #5519
- [x] GPT-OSS #5484
- [x] Llama 3 #5493
- [x] Phi-3 https://github.com/huggingface/trl/pull/5526
- [x] Phi-3.5 https://github.com/huggingface/trl/pull/5746
- [ ] FalconMamba https://github.com/huggingface/trl/pull/5723 -> won't support, see the PR comment
VLMs
- [x] Gemma3 https://github.com/huggingface/trl/pull/5685
- [x] Qwen3-VL https://github.com/huggingface/trl/pull/5764
- [ ] Qwen2-VL
- [ ] Qwen2.5-VL
- [ ] SmolVLM
- [x] Idefics3
- [ ] LLaVA
- [ ] LLaVA-Next
No chat template (no action needed)
- Bloom, GPT2, GPTNeoX, OPT, T5
Notes
- VLMs currently don't support
assistant_only_lossin SFT (blocked by a separate check). These should still be tracked so templates are ready when support lands.
Additional tips for contributors:
-
Check if prefix preservation fixes are needed
Edit: nvm, Quentin has already drafted a table for checking in https://github.com/huggingface/trl/issues/5460
~~You can check if additional prefix preservation fixes are needed for a model by testing the tokenizer's chat template, with TRL's
is_chat_template_prefix_preserving, for example:~~from transformers import AutoTokenizer from trl.chat_template_utils import is_chat_template_prefix_preserving gpt = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM") qwen = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3ForCausalLM") print("gptoss_prefix_preserving =", is_chat_template_prefix_preserving(gpt)) # True print("qwen3_prefix_preserving =", is_chat_template_prefix_preserving(qwen)) # False -
Make sure you're on latest transformers version, newer tokenizers might return errors otherwise.
-
You can also check the merged PRs linked in the issue for additional examples
Hi @qgallouedec — I'd like to take Gemma 3 from the VLM list.
Plan, following the 3-step pattern from #5523 (Gemma/Gemma2):
- Add
gemma3_training.jinjawith{% generation %}/{% endgeneration %}around assistant output - Wire it into
chat_template_utils.py+ add a branch inget_training_chat_template() - Add a test asserting (a) rendered text is identical to the original template and (b)
return_assistant_tokens_mask=Trueproduces correct masks
I'll also run is_chat_template_prefix_preserving (per @casinca's tip) to see if prefix-preservation fixes are needed.
Understood that the VLM assistant_only_loss guard in sft_trainer.py is tracked separately — this PR will be template-only prep, as the issue notes.
Starting on it unless someone is already in flight.
Sounds good @hwanython. Note that Gemma 3 doesn't support tool calling, so we don't need to ensure prefix-preservation for it, just {% generation %} / {% endgeneration %} markers
can I contribute in it? phi 3.5 or FalconMamba ?
Hi @qgallouedec and @casinca , I'd like to contribute to this tracking issue by implementing Phi-3.5 support for training chat templates with {% generation %} markers.
I've reviewed PR #5526 (Phi-3 implementation) and have a clear plan:
- Create
phi3_5_training.jinjaandphi3_5.jinjawith{% generation %}/{% endgeneration %}markers around assistant output - Load the template in
chat_template_utils.pyand register it inget_training_chat_template() - add phi3.5 to chat_template/README as well
- Add Phi-3.5 to the
TestGetTrainingChatTemplateparametrized tests The implementation closely follows the Phi-3 pattern already established. Would you like me to proceed?
Would you like to add on or correct something
Hi @qgallouedec, happy to pick up Qwen3.5 next.
One concern, though — TRL bundles two Qwen3.5 inference templates (2b_and_below and 4b_and_above, separate add_response_schema branches), so the PR would add two training variants. The problem is on the
test side: only tiny-Qwen3_5ForConditionalGeneration exists, and it's built from Qwen/Qwen3.5-0.8B (per scripts/generate_tiny_models/.../qwen3_5_for_conditional_generation.py), so it carries the
2b_and_below template. That means the 4b_and_above branch in TestGetTrainingChatTemplate has nothing to dispatch through.
The two templates only differ in the add_generation_prompt block, so either:
- Ship with the single fixture, test the
2b_and_belowvariant, and note the4b_and_abovebranch is covered-by-inspection (near-identical). I can do this end-to-end now. - Add a
-4bfixture first for full coverage — but I think pushing totrl-internal-testingneeds maintainer access, so that'd be on your side before I can wire the test.
Happy to go with (1) and ship now, or wait on a -4b fixture if you'd rather have the coverage. Your call.
good point, let's replace the tiny-Qwen3_5ForConditionalGeneration by tiny-Qwen3_5ForConditionalGeneration-Think and tiny-Qwen3_5ForConditionalGeneration-NoThink
@qgallouedec, makes sense — -Think / -NoThink maps cleanly onto the existing 4b_and_above (default thinking ON) and 2b_and_below (default thinking OFF) inference templates, so the naming is coherent.
Happy to take this on, with one caveat on division of labor: I can PR the script change, plus the template files and all the test updates. But the actual Hub push to trl-internal-testing would need to be on your side.
One scope question on "replace": tiny-Qwen3_5ForConditionalGeneration is referenced in 11 places across 6 files —test_chat_template_utils.py, test_sft_trainer.py, test_grpo_trainer.py, test_rloo_trainer.py, test_dpo_trainer.py, and test_data_utils.py. A hard rename would cascade through all of those, but I'm happy to do the full sweep and update every reference — just want to confirm that's the direction you'd like before I touch the trainer tests. The alternative is keeping the existing fixture and adding -Think / -NoThink as siblings, which would scope the PR down to just the chat-template tests. WDYT?
Either way, I'd plan to split this into two PRs — the generator script change first (you regenerate + push the fixtures), then the templates + test updates once the fixtures land — so the Hub-push dependency stays isolated from the template work.
you should be able to open a pr on the model repo and put the link here: https://github.com/huggingface/trl/blob/5950714aff517db7beb54e2256e3e69bedcc1f50/tests/conftest.py#L54-L72
Ah my bad, not true, you're right, it's a new model, so my comment isn't relevant. I'll upload the model myself with the script you provide, no worry
Hey @qgallouedec — taking a look at the Qwen2-VL and Qwen2.5-VL rows here, and there's something I wanted to surface before opening a PR.
Neither family currently has a base .jinja shipped under trl/chat_templates/. And the chat templates that come down from the upstream model repos on HF are tool-blind — tools=[...] is silently ignored at render time. So the row in #5460 that marks them as "Supports tools = Yes" doesn't really hold once you look at the wire output.
I dug into this on the #5460 thread (https://github.com/huggingface/trl/issues/5460#issuecomment-4416196349 — my last few comments there have the testing notes), and it ends up coupling the two issues: whatever base template a _training.jinja would target for these rows is itself an open question, because there isn't a settled tool-capable base for the Qwen2-VL / Qwen2.5-VL families yet.
Wanted to flag this before I picked a direction. How would you like me to proceed?
Neither family currently has a base .jinja shipped under trl/chat_templates/.
then we should add one file for each template
And the chat templates that come down from the upstream model repos on HF are tool-blind
that's alright, tool is out of the scope here. we're just adding the generation marker.
So the row in https://github.com/huggingface/trl/issues/5460 that marks them as "Supports tools = Yes" doesn't really hold once you look at the wire output.
Right! my mistake, I'll fix #5460
Perfect, that clears it up — generation-marker-only, tools out of scope. I'll add base and training templates for both, one family per PR (Qwen2-VL first, then Qwen2.5-VL) to keep each reviewable. Starting on it now.
@qgallouedec — Llava ships generation markers natively (only wrapping text, not the <image> placeholder).
Two questions:
- For Llava, should we still add a
llava_training.jinjapatch, or just register the original template + add a test param and document native support? - Llava's upstream excludes
<image>from{% generation %}. In SmolVLM and the Idefics3 PRs, I included<image>inside the markers. Which is correct — should image placeholder tokens be masked as assistant tokens, or treated as non-generated like the prompt cue?
Update: dug into this.
Q1 — Llava. get_training_chat_template returns None early when the template already has {% generation %} markers (which Llava does) and prefix-preservation is N/A (Llava has no tools). No llava.jinja or llava_training.jinja needed — just register in the test parametrize block and supported-families docs.
Q2 — <image> placement. Swept every *_training.jinja. Established TRL convention is image inside {% generation %}. Only outlier is qwen3_vl_training.jinja, which drops assistant images entirely (inherited from upstream).
In the current TRL flow, prepare_multimodal_messages only injects images into user messages, so the assistant-side image branch is dead code regardless of placement.
@qgallouedec – your call.
Hi,
I am using openbmb/MiniCPM5-1B model and I have also modified chat template before configuring SFTTrainer but still it's giving me following error:
ValueError: The chat template is not training-compatible (missing prefix-preservation or `{% generation %}` markers) and patching is not supported for this template. Please manually modify the chat template for training.
I tried following template formats, but all were giving same error: 1st teamplate:
TRAIN_CHAT_TEMPLATE = (
"{{- bos_token }}"
"{%- for message in messages %}"
"{%- if message['role'] == 'system' %}"
"{{- '<|im_start|>system\\n' + message['content'] + '<|im_end|>\\n' }}"
"{%- elif message['role'] == 'user' %}"
"{{- '<|im_start|>user\\n' + message['content'] + '<|im_end|>\\n' }}"
"{%- elif message['role'] == 'assistant' %}"
"{{- '<|im_start|>assistant\\n' }}"
"{%- generation %}"
"{{- message['content'] + '<|im_end|>' }}"
"{%- endgeneration %}"
"{{- '\\n' }}"
"{%- endif %}"
"{%- endfor %}"
"{%- if add_generation_prompt %}"
"{{- '<|im_start|>assistant\\n' }}"
"{%- endif %}"
)
2nd template:
TRAIN_CHAT_TEMPLATE = (
"{{- bos_token }}"
"{%- for message in messages %}"
"{%- if message['role'] == 'system' %}"
"{{- '<|im_start|>system\\n' + message['content'] + '<|im_end|>\\n' }}"
"{%- elif message['role'] == 'user' %}"
"{{- '<|im_start|>user\\n' + message['content'] + '<|im_end|>\\n' }}"
"{%- elif message['role'] == 'assistant' %}"
"{{- '<|im_start|>assistant\\n' }}"
"{%- generation %}"
"{{- message['content'] }}"
"{%- endgeneration %}"
"{{- '<|im_end|>\\n' }}"
"{{- '\\n' }}"
"{%- endif %}"
"{%- endfor %}"
"{%- if add_generation_prompt %}"
"{{- '<|im_start|>assistant\\n' }}"
"{%- endif %}"
)
3rd template:
TRAIN_CHAT_TEMPLATE = (
"{{- bos_token }}"
"{%- for message in messages %}"
"{%- if message['role'] == 'system' %}"
"{{- '<|im_start|>system\\n' + message['content'] + '<|im_end|>\\n' }}"
"{%- elif message['role'] == 'user' %}"
"{{- '<|im_start|>user\\n' + message['content'] + '<|im_end|>\\n' }}"
"{%- elif message['role'] == 'assistant' %}"
"{%- generation %}"
"{{- '<|im_start|>assistant\\n' }}"
"{{- message['content'] }}"
"{{- '<|im_end|>\\n' }}"
"{%- endgeneration %}"
"{{- '\\n' }}"
"{%- endif %}"
"{%- endfor %}"
"{%- if add_generation_prompt %}"
"{{- '<|im_start|>assistant\\n' }}"
"{%- endif %}"
)
please suggest if anyone knows the RCA and what to do
Thanks
thanks for reporting, we recently merged a pr that should fix it https://github.com/huggingface/trl/pull/5988
thanks all, I'm going to close this one as all LM are now supported. VLM are now out of the scope because they don't support return_assistant_tokens_mask` yet, see https://github.com/huggingface/transformers/issues/44521
VLMs are now back in scope: huggingface/transformers#44521 was fixed by huggingface/transformers#48793 (ships with transformers 5.18). Follow-up tracked in #7376, with the implementation in #7377 (requires transformers>=5.18.0).