Repository navigation
GRPO tool calling: accept Unsloth chat templates in TRL's response schema and training template lookup - #13202
Conversation
TRL matches chat templates by exact string to pick the tool-call parser and the multi-turn training template, so GRPOTrainer(tools=...) and environment_factory raised 'Unrecognized chat template' on unsloth/* repos (Qwen3, Qwen3.5/3.6/3.8, gpt-oss, GLM-4.5, Nemotron 3, Gemma 4). When TRL rejects a template, reuse the parser / training template of the TRL-known template that renders identically. The user's chat template is never modified.
…on special tokens
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: aa494bd106
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if isinstance(template, dict): | ||
| template = template.get("default") |
There was a problem hiding this comment.
Resolve the tool-use template instead of the default
When chat_template is a named-template dictionary containing both default and tool_use, Transformers automatically selects tool_use whenever GRPO supplies tools, but this fallback always probes default. If the edited default resembles a TRL-known family while tool_use uses different formatting, the patch silently installs the default family's parser/training template and generated tool calls are then misparsed or prompts are rewritten incorrectly. Resolve the effective template with the same tools-aware selection used by apply_chat_template rather than unconditionally reading default.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in fb60e1a: a named template set (default plus tool_use) is left to TRL, since transformers picks the entry per call and one family cannot stand in for it.
| try: | ||
| training = original(clone) | ||
| except Exception: | ||
| continue |
There was a problem hiding this comment.
Preserve the matched VLM training-template family
Do not collapse candidate training templates solely by their rendered text on these text-only probes. For example, an edited qwen3_vl_chat_template matches both the Qwen3 Instruct-2507 and Qwen3-VL families here; their training signatures are identical for the current probes, so setdefault retains the lexicographically earlier Instruct template. On an actual multimodal message that selected template drops <|vision_start|><|image_pad|><|vision_end|> and the accompanying text, corrupting vision prompts. The disambiguation must exercise multimodal inputs (and preserve the corresponding family) before selecting a training template.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in fb60e1a: when the user's template renders image content, candidates must render it identically too, so an edited Qwen3-VL template keeps the Qwen3-VL training template. Text-only templates that raise on list content skip that probe. Test added.
…plate sets to TRL
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fb60e1affd
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
|
||
| # Users pass these through chat_template_kwargs; a match must hold for each, or a template that | ||
| # ignores enable_thinking=False would borrow one that writes an empty <think> into every prompt. | ||
| _TEMPLATE_KWARGS = ({}, {"enable_thinking": False}) |
There was a problem hiding this comment.
Probe runtime template kwargs before substituting templates
When an edited template differs from a TRL template only under another supported runtime kwarg, these probes incorrectly declare them equivalent. For example, Qwen3.8 branches on reasoning_effort; an edit confined to reasoning_effort="low" is invisible both with the default kwargs and with thinking disabled, so get_training_chat_template returns TRL's training template and the actual GRPO run silently loses the edited low-effort behavior when chat_template_kwargs is applied. Probe the other family-specific kwargs (or avoid substitution when their equivalence cannot be established) so training prompts retain the user's semantics.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Below the bar: it needs an edit that only shows under a non-default kwarg. The Unsloth templates in this family differ from upstream only by llama.cpp-safe rewrites, and Qwen3.8 is prefix-preserving, so its training template is never substituted. enable_thinking=False is probed because it does diverge on a real template.
| if isinstance(template, dict): | ||
| # A named set (e.g. "tool_use") is picked per call by transformers; one family cannot stand in for it. | ||
| template = template.get("default") if len(template) == 1 else None |
There was a problem hiding this comment.
Resolve a sole tool-use template instead of rejecting it
When chat_template is {"tool_use": <edited known template>}, this expression returns None, so the wrapper re-raises TRL's unrecognized-template error even though Transformers unambiguously selects that sole tool_use entry whenever GRPO supplies tools. Unlike the previously discussed multi-entry set, this case has no per-call family ambiguity in the tool-enabled flow; extract the sole value (or resolve it with the tools-aware selection logic) so this valid tokenizer configuration receives the patch.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e9539e0: a set with a single entry is matched like a plain template; a multi-entry set still goes to TRL.
| def _call(a, b): | ||
| return {"type": "function", "function": {"name": "multiply", "arguments": {"a": a, "b": b}}} |
There was a problem hiding this comment.
Distinguish Qwen tool-argument serialization before choosing a family
When an edited Qwen3.6 template is matched, every probe supplies only integer arguments, so Qwen3.6 and Qwen3.5-Think produce identical signatures and their training templates are collapsed; the lexicographically earlier Qwen3.5 template is then returned. These families diverge for common non-integer arguments: Qwen3.6 renders booleans/null as JSON true/null, while Qwen3.5 renders True/None. A Qwen3.6 tool trajectory containing those values is therefore silently rewritten into the wrong syntax during training, so the probes need boolean/null (and other structured) arguments to preserve the correct family.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e9539e0: training-template probes now include a call with float / bool / null / string arguments, so Qwen3.6 and Qwen3.5 resolve to their own families (test added). Kept out of the parser probes, where it would only drop Gemma 4 on TRL 1.13, whose template writes None.
| for owner, name, value in saved: | ||
| setattr(owner, name, value) |
There was a problem hiding this comment.
Restore trainer modules imported during the fixture
When test_patch_is_idempotent_and_rebinds_trainer_imports imports trl.trainer.grpo_trainer after this fixture has taken its saved snapshot, the module receives the wrapped helpers but is absent from this teardown loop. Consequently the fixture restores trl.chat_template_utils while leaving the trainer module patched, so later tests in the same process observe split helper bindings and can become order-dependent. Restore bindings discovered at teardown as well, or explicitly unload/reset trainer modules imported while the fixture is active.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Test hygiene only: the wrappers act only when TRL raises its own unrecognized-template error, so a module left bound to them behaves the same for every other test.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
pre-commit.ci autofix |
|
pre-commit.ci run |
TRL's
GRPOTrainer(tools=...)andenvironment_factory=...pick the tool-call parser (add_response_schema) and the multi-turn training template (get_training_chat_template) by exact string match on the chat template. The templates shipped in theunsloth/*repos carry fixes, so they never match and GRPO with tools fails at trainer init:This hits every
unsloth/Qwen3-*model (and Qwen3.5 / 3.6 / 3.8, gpt-oss, GLM-4.5, Nemotron 3, Gemma 4), includingQwen/Qwen3-*ids, which the mapper redirects tounsloth/*.Fix
unsloth/models/_trl_tool_templates.py, installed fromPatchFastRL:enable_thinking=False). The TRL template that renders byte-identically lends its parser / training template.chat_templateis never modified, so inference and GGUF / Ollama export are unchanged. Runs without tools never reach this code.Evidence
GRPO,
unsloth/Qwen3-0.6Bwith its default template, LoRA, 3 steps,num_generations=4, B200, vLLM 0.31:tools=tools=environment_factory=tools=<think>) gives the same result as TRL with the upstream template.unsloth/Qwen3-4B-Instruct-2507/Thinking-2507stay rejected: their hub template renders like Qwen3 thinking by default but ignoresenable_thinking=False, so borrowing Qwen3's training template would add an empty<think>to every prompt (the model then drops<tool_call>and no tool call parses). Useget_chat_template(tokenizer, "qwen3-instruct")there.tests/test_trl_tool_chat_templates.py: 8 CPU tests, pass on TRL 1.13.0 and 1.15.0; with the patch reverted the behaviour tests fail and the "leave TRL alone" controls still pass.Saving a checkpoint with tools also needs unslothai/unsloth-zoo#1650.
Related: #10580, #3528 (tool calling / OpenEnv GRPO notebook, closed by unslothai/notebooks#395). Pairs with #13203 (TRL 1.15), #13204 / unslothai/unsloth-zoo#1663 (SFT on tool trajectories), #13205 (AsyncGRPO, vision tools), unslothai/unsloth-zoo#1664 (vision GRPO with fast_inference).