[qwen3_5] swift backend drops assistant reasoning when the same turn has tool_calls (train/infer mismatch, likely root cause of #9234)
Bug Description
With template_backend='swift', the qwen3_5 agent template drops the assistant's reasoning (<think>...</think>) whenever the same assistant turn also carries tool_calls. The official chat_template.jinja (used by vLLM / transformers at inference) keeps it. As a result, a model trained with ms-swift never sees "think, then call a tool" in its training data, while it is served with exactly that format.
This looks like a likely root cause of #9234 (</think><|im_end|> / empty <tool_call> after SFT on Qwen3.5/3.6-35B-A3B). The symptoms match: the model learns </think> followed directly by the end of the turn, because the training rendering never shows </think> followed by <tool_call>.
Both issues below are still present on main (checked at dbc395ff02, 2026-09-28).
Root cause
swift/agent_template/qwen3_coder.py,Qwen3_5AgentTemplate._add_tool_call_prefix: the preceding assistant message'scontent(which holds<think>...</think>) is only used to decide whether to insert\n\n. It is not included in the returned string, so the reasoning text is dropped when the tool-call turn is rebuilt.swift/template/base.py,_remove_history_thinking(and_add_non_thinking_prefix) callget_last_user_round(messages)with the defaultinclude_tool=True. The jinja template uses the last user message as the boundary for removing historical reasoning. Withtoolmessages counted as a boundary, reasoning in the current agent round is treated as history.get_last_user_roundalready hasinclude_toolonmain(from #9923, which is correct forlast_roundloss scaling). But these two callers still use the default.
Reproduction (CPU only, no weights)
# ms-swift 4.5.3 / transformers 5.16.1
from huggingface_hub import snapshot_download
from transformers import AutoTokenizer
from swift.model import get_model_processor
from swift.template import get_template
model_dir = snapshot_download('Qwen/Qwen3.5-35B-A3B', allow_patterns=['*.json', '*.jinja', '*.txt', 'merges*', 'vocab*'])
tools = [{'type': 'function', 'function': {'name': 'search', 'description': 'Search stock.',
'parameters': {'type': 'object', 'properties': {'query': {'type': 'string'}}, 'required': ['query']}}}]
messages = [
{'role': 'user', 'content': 'Check the stock and draft an order email if it is low.'},
{'role': 'assistant', 'content': '<think>\nI need to check the stock first.\n</think>\n\n',
'tool_calls': [{'type': 'function', 'function': {'name': 'search', 'arguments': {'query': 'stock'}}}]},
{'role': 'tool', 'name': 'search', 'content': 'Stock: 3 left.'},
{'role': 'assistant', 'content': '<think>\n3 is low, so an order is needed.\n</think>\n\nStock is low (3 left). Here is the draft.'},
]
tok = AutoTokenizer.from_pretrained(model_dir)
jinja_text = tok.apply_chat_template(messages, tools=tools, tokenize=False)
_, processor = get_model_processor(model_dir, load_model=False)
template = get_template(processor, template_backend='swift', loss_scale='last_round')
swift_text = tok.decode(template.encode({'messages': messages, 'tools': tools})['input_ids'])
print('jinja has 1st-turn reasoning:', 'I need to check the stock first.' in jinja_text) # True
print('swift has 1st-turn reasoning:', 'I need to check the stock first.' in swift_text) # False
print('identical:', jinja_text == swift_text) # FalseOn 12 hand-written samples (thinking only, tool calls only, no thinking, multi-step tool calls, reasoning + tool calls in one turn), the swift backend matched the jinja token-for-token on 5 of 12 with last_round and 10 of 12 with all. Every mismatch was a sample with reasoning and tool calls in the same assistant turn.
Workaround
We registered a patched agent template and template through ms-swift's own registry (agent_template_map / register_template) without editing ms-swift:
_add_tool_call_prefixreturns the preceding content (including<think>...</think>) followed by the tool-call text- the history-thinking boundary uses
usermessages only, as the jinja does
With these two changes, the swift backend matched the jinja token-for-token on 12 of 12 samples, with both loss_scale='last_round' and 'all'. We can open a PR if that would help.
A related note for agent SFT: with loss_scale='last_round', only the final assistant sub-turn gets loss, so intermediate tool-call turns are not trained. loss_scale='all' may be the safer default recommendation for multi-step agent data.
Environment
- ms-swift 4.5.3 (also checked source on
main@ dbc395ff02) - transformers 5.16.1, torch 2.14.0+cpu, Python 3.12
- Tokenizer:
Qwen/Qwen3.5-35B-A3B(andQwen/Qwen3.5-35B-A3B-Base, whose chat template is identical)
Source: modelscope/ms-swift