Chat template: look up tool names in one pass

#27
by vMaroon - opened

get_tool_name loops over every tool call in the conversation for each tool message, so render time grows with the square of the tool calls in the history.

This pairs tool messages with their tool calls once before the message loop: both are sorted together by id and paired in one pass. Every assistant tool call with the id contributes its name, in order, as on main. It only uses sort, namespace and list concatenation, so it renders under MiniJinja too. get_tool_name stays defined and unused.

Tool calls main this PR
400 0.28 s 0.03 s
1,600 4.3 s 0.11 s
3,200 17.3 s 0.25 s

transformers 5.22.1 with jinja2 3.1.6, one M4 core, one tool call per assistant message.

Output is byte-identical to main on 46,000 randomized conversations (duplicate, unmatched and case-variant ids, shuffled and missing results), under jinja2 and under MiniJinja 3.1.0 through its Python binding.

tokenizer_config.json carries a second copy of the template with CRLF line endings. I left it as is - can update it here too.

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

Sign up or log in to comment