chat template: speed up tool-result validation and reordering (GLM-5.3)

#2
by ShijinZhang - opened

Summary

Syncs the sort-merge tool-result validation and reordering optimization from GLM-5.3 Discussion #31 (by @vMaroon , merged in the FP8 repo) to the BF16 repo. The change is limited to the tool-result validation and reordering block in chat_template.jinja; all other template logic is byte-identical to this repo's current template (verified: all differences confined to lines 175-241, the sort-merge block).

The existing chat template uses nested loops and repeated macro calls to validate and reorder tool results, which introduces significant rendering overhead for large numbers of parallel tool calls. The updated implementation uses a sort-merge approach, preserving the original ordering and fallback behavior, and avoids Python-specific list.index() calls.

Correctness Validation

Compared this repo's current template against the optimized implementation using randomized conversations and targeted edge cases (fresh runs against this exact BF16 base, not carried over from the Flash validation).

Suite 1 β€” Jinja2 differential (Python 3.13, Jinja2 3.1.6, ImmutableSandboxedEnvironment with loopcontrols and a Transformers-compatible tojson adapter), run under all four trim_blocks/lstrip_blocks configurations (2,000 cases each): byte-identical outputs / identical error types and messages, 0 behavioral mismatches.

Suite 2 β€” MiniJinja 2.24.0 differential (Python binding, pycompat=True, HF-compatible tojson): 15,000-case seeded corpus under chainable-undefined semantics β€” 11,586 byte-identical successes + 3,414 identical-error cases, 0 mismatches.

Suite 3 β€” NVIDIA Dynamo production renderer: the real Rust dynamo-renderer 8.0.1 (crates.io) with minijinja + minijinja-contrib 2.24.0 β€” the exact versions in Dynamo main's Cargo.lock (verified via cargo tree) β€” rendering both templates through the full production path on the identical 15,000-case corpus, 0 mismatches.

ShijinZhang changed pull request status to open
ZHANGYUXUAN-zR changed pull request status to merged

Sign up or log in to comment