fix: chat_template, close model turn across tool results + keep tool-call reasoning

#25
by dimondev - opened

Summary

Two defects in chat_template.jinja, both verified with ChatLint against 49 conversation shapes. The patched file is attached / inlined as this PR.

Hub main this PR
score 260/294 (88%) 283/294 (96%)
errors 25 2

The remaining 2 are the preamble-hoist issue also present on E4B/31B (assistant text emitted after <tool_response|>); not addressed here.

Fix 1: misplaced endif (22 marker_balance errors)

ns.prev_non_tool_role was assigned outside the role != 'tool' block, so a tool message overwrote it to 'tool'. The next assistant turn then failed continue_same_model_turn and opened a second <|turn>model without closing the first:

broken:  ...<tool_response|><|turn>model\nIt is 18C...
fixed:   ...<tool_response|>It is 18C...<turn|>\n<|turn>user\n

This is the same class of turn-tag imbalance the Jul 15 fix cleared on gemma-4-31B-it / gemma-4-E4B-it. Those repos already have the endif in the right place; Diffusion Gemma did not get that change.

         {%- endif -%}
-    {%- endif -%}
-
     {#- Track previous non-tool role for next iteration (avoids O(n) backward scan) -#}
     {%- set ns.prev_non_tool_role = message['role'] -%}
+    {%- endif -%}
 {%- endfor -%}

Fix 2: tool-call reasoning dropped after the next user turn

- {%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or (preserve_thinking and message.get('tool_calls')) -%}
+ {%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or message.get('tool_calls') or preserve_thinking -%}

With the default preserve_thinking=false, an assistant turn that called a tool lost its reasoning_content as soon as a later user message existed, blowing ~27% of the cached prefix on every agent step after the first tool call.

Reproduce

pip install chatlint
# before
curl -sL https://huggingface.co/google/diffusiongemma-26B-A4B-it/raw/main/chat_template.jinja \
  | chatlint check /dev/stdin
# after (this PR's file)
chatlint check chat_template.jinja

Ask

If this lands, consider adding ChatLint's CI workflow so a sibling repo cannot drift from the Jul 15 fix again. The original Gemma 4 turn-tag regression survived 96 days; this file shows the same class of bug can reappear on a fork that nobody re-gated.

Ready to merge
This branch is ready to get merged automatically.

Sign up or log in to comment