Skip to content

Misc. bug: Jinja rendering overhead with long tool-call histories and early-exit loops #32002

Open

Description

@Neroued

Name and Version

3b4d6ab, still present in master.

Operating systems

No response

Which llama.cpp modules do you know to be affected?

Other (Please specify in the next section)

Command line

Problem description & steps to reproduce

I've been using llama.cpp's Jinja interpreter from NInfer, and on long tool-call histories the render step grew into a noticeable chunk of TTFT. Here's what I found plus a branch that fixes it.

The expensive part

A for loop pays for the entire iterable before it runs the first iteration. With N=4096:

{%- set ns = namespace(n=0) -%}
{%- for i in range(n) -%}
    {%- for j in range(i, n) -%}
        {%- set ns.n = ns.n + 1 -%}
        {%- break -%}
    {%- endfor -%}
{%- endfor -%}
{{- ns.n -}}

The body runs 4096 times, but the inner ranges still contain 8,390,656 elements (4096 * 4097 / 2). Each one goes through three full passes before the first break is even reachable: range() builds a value_array of boxed ints, for_statement copies it into a local std::vector<value> items, and then allocates a std::function per element to bind the loop variable.

So break saves the body but not the setup, and nested early-exit loops are quadratic. That's 646 ms on a 9950X3D for ~4,000 iterations of real work.

The rest is ordinary interpreter overhead:

  • identifier::execute_impl has auto builtins = global_builtins(); (runtime.cpp:93). global_builtins() returns a reference, so every variable read copies the whole builtin table. It's done correctly elsewhere in the same file, so this looks like a typo that survived.
  • Scopes copy their variable map on entry; payloads are shared, but it's still an allocation and refcount traffic per scope.
  • Value has storage for several payload types, so the arithmetic and comparison paths type-check and allocate an Undefined or a literal per operand.
  • Loops and ifs buffer into a value_array and concatenate at the end; break/continue throw.

What the branch does

perf/jinja-rendering. Ranges keep (start, stop, step) and materialize only when something needs real elements; binding and filtering advance one element at a time. loop.index stays cheap, loop.nextitem scans ahead only when read, and on a filtered loop loop.length/revindex consume the rest of the input on access (an unfiltered array or range just reports its size). Beyond that: parent-scope lookup instead of copying, a smaller Value with one literal allocation per AST node, direct output accumulation, break as a flag.

What it changes in behavior

Lazy setup changes output in a few places, and two of those are upstream bugs that have nothing to do with being fast:

  • {% for a,b in [[1,2],[3]] %}{{ a }}{% break %}{% endfor %} throws Too few items to unpack upstream, because the second element gets unpacked during prep even though the loop breaks on the first one. The branch prints 1.
  • Upstream drops buffered output when break or continue unwinds out of an if. {% for i in [1] %}A{% if true %}B{% break %}{% endif %}C{% endfor %} gives A upstream and AB here and in Jinja2; with continue, {% for i in [1,2] %}A{% if true %}B{% continue %}{% endif %}C{% endfor %} gives AA upstream and ABAB both places.

The two have different causes. The unpack error comes from binding every element during loop setup; the dropped output comes from the unwind walking out through a block that buffers its own output. Neither depends on the lazy iterator, so both can be fixed on their own.

One change I'd actually call a risk: the loop now sees mutations to the list it's iterating where upstream iterates a snapshot. That's what Jinja2 does ({% set _ = a.append(3) %} inside the loop extends it), but a template that appends unconditionally would stop terminating, where today it doesn't. Nothing in models/templates iterates a list it mutates.

Everything else I compared comes out identical: filtered loop.length/revindex consumption, stats marking, error text. for/else also matches: else runs when no iteration finished without a break or continue, so breaking on the first iteration still runs it, while breaking after a complete iteration does not. Upstream, the branch and Jinja2 agree on all three.

Numbers

Median of five renders, templates compiled once and reused, timing includes json to Value conversion but excludes parse and compile.

Workload CPU Upstream This branch Python Jinja2
Early-exit suffix loops, N=4096 Ryzen 9950X3D 646.05 ms 2.55 ms 8.67 ms
Same DGX Spark 746.27 ms 2.54 ms 10.39 ms
GLM-4.7, 1,601 messages Ryzen 9950X3D 46.63 ms 6.23 ms 9.86 ms
Same DGX Spark 64.88 ms 13.29 ms 10.56 ms
Qwen3.5, 1,601 messages Ryzen 9950X3D 68.15 ms 8.49 ms 13.21 ms
Same DGX Spark 80.23 ms 14.80 ms 15.37 ms

Two commits: 57cc79a4e is benchmark-only with the interpreter untouched, d08c42825 is the change plus tests. The script is scripts/jinja/benchmark.py and needs no weights. Existing jinja and chat-template tests pass; I also ran both C++ builds against Jinja2 on the same inputs and compared marked string parts.

What I'm asking

The main point I'd like to settle is the intended behavior for mutable iterables and deferred filtering. My preference is to follow Jinja2 here, with the observable changes covered explicitly by tests. Lazy range construction and on-demand loop metadata can also be considered separately from whether mutable lists retain snapshot iteration.

For landing the changes, I could start with the builtin-table copies and the buffered-output fix, then separate the iterator changes, scope management, and Value representation into focused PRs. Would that split fit the project? In particular, are there compatibility requirements that would make preserving snapshot iteration preferable?

First Bad Commit

No response

Relevant log output

Logs

Activity

  1. CISC commented on Nov 10, 2026

    @CISC
    Member

    The main point I'd like to settle is the intended behavior for mutable iterables and deferred filtering. My preference is to follow Jinja2 here, with the observable changes covered explicitly by tests. Lazy range construction and on-demand loop metadata can also be considered separately from whether mutable lists retain snapshot iteration.

    Where possible within reason Jinja2 compatibility is preferred.

    For landing the changes, I could start with the builtin-table copies and the buffered-output fix, then separate the iterator changes, scope management, and Value representation into focused PRs. Would that split fit the project?

    Yes please.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions