Skip to content

GRPO tool calling: accept Unsloth chat templates in TRL's response schema and training template lookup - #13202

Merged
danielhanchen merged 6 commits into
mainfrom
trl-tool-chat-templates
Oct 10, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
trl-tool-chat-templates

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

TRL's GRPOTrainer(tools=...) and environment_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 the unsloth/* repos carry fixes, so they never match and GRPO with tools fails at trainer init:

ValueError: Unrecognized chat template, failed to add response schema.

This hits every unsloth/Qwen3-* model (and Qwen3.5 / 3.6 / 3.8, gpt-oss, GLM-4.5, Nemotron 3, Gemma 4), including Qwen/Qwen3-* ids, which the mapper redirects to unsloth/*.

Fix

unsloth/models/_trl_tool_templates.py, installed from PatchFastRL:

  • TRL always runs first. Only when it raises its own "unrecognized" / "not supported" error, the user's template and every TRL-known template render a fixed set of tool conversations (single and parallel tool calls, tool results, plain answers; default kwargs and enable_thinking=False). The TRL template that renders byte-identically lends its parser / training template.
  • No match, or several matches with different parsers, re-raises TRL's original error.
  • The user's chat_template is never modified, so inference and GGUF / Ollama export are unchanged. Runs without tools never reach this code.
  • Rebinds the functions in every module that imported them (GRPO, SFT, async GRPO worker, generated Unsloth trainers); idempotent.

Evidence

GRPO, unsloth/Qwen3-0.6B with its default template, LoRA, 3 steps, num_generations=4, B200, vLLM 0.31:

TRL mode fast_inference main this PR
1.13.0 tools= False ValueError at init 12 tool calls executed, 84 tool tokens masked per step
1.13.0 tools= True ValueError at init same, generation on Unsloth's vLLM engine
1.13.0 environment_factory= False / True ValueError at init 12 calls each
1.15.0 tools= True ValueError at init 12 calls
  • Parsing a real Qwen3 completion (with <think>) gives the same result as TRL with the upstream template.
  • Template sweep (TRL 1.13 and 1.15): accepted now for Qwen3 0.6B/4B (+bnb-4bit), gpt-oss-20b, GLM-4.5-Air, Nemotron-3 Nano 4B/30B, Gemma-4-E2B, Qwen3.5/3.6/3.8; already-identical templates (Qwen2.5, Llama 3.1/3.2, Qwen3-VL, R1-Distill) are untouched; LFM2 / LFM2.5 hub templates render no tool calls and stay rejected. unsloth/Qwen3-4B-Instruct-2507 / Thinking-2507 stay rejected: their hub template renders like Qwen3 thinking by default but ignores enable_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). Use get_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.
  • Regression smoke A/B (merge base vs this stack, TRL 1.13): 0 regressions, 103 cases each side.

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).

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-10T07:35:24.031546Z efa8fdd New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread unsloth/models/_trl_tool_templates.py Outdated
Comment on lines +98 to +99
if isinstance(template, dict):
template = template.get("default")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment thread unsloth/models/_trl_tool_templates.py Outdated
Comment on lines +106 to +108
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in e9539e0: a set with a single entry is matched like a plain template; a multi-entry set still goes to TRL.

Comment on lines +46 to +47
def _call(a, b):
return {"type": "function", "function": {"name": "multiply", "arguments": {"a": a, "b": b}}}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +78 to +79
for owner, name, value in saved:
setattr(owner, name, value)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: e9539e0ef5

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci autofix

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant