llama.cpp icon indicating copy to clipboard operation
llama.cpp copied to clipboard

chat : inkling tool-call grammar crash with thinking off ("unexpected empty grammar stack")

Open nikosleft opened this issue 1 week ago • 4 comments

Name and Version

version: 1.0.0-dev (build 12631, commit e300919cc) built with Clang 22.1.8 for Windows x86_64

Bug also present in current master source (checked 2026-11-22: common/parsers/inkling.cpp unchanged since PR #32381).

Operating systems

Windows

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

llama-server

Command line

llama-server -m Inkling-2-Mini-Unbound-v2-Q4_K_M.gguf --jinja --chat-template-file inkling2-thinkoff.jinja --host 127.0.0.1 --port 8080

curl http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" -d '{
  "messages": [{"role": "user", "content": "hello"}],
  "max_tokens": 48,
  "tools": [{"type": "function", "function": {"name": "list_files", "description": "list files", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}}]
}'

Problem description & steps to reproduce

Sending a one-word chat message ("hello") with a single trivial tool attached fails mid-stream with HTTP 500, on every plain reply. Removing "tools" from the same request makes the model reply normally. Reproduces 100% of the time; see the command line section (the attached inkling2-thinkoff.jinja is needed for the repro).

Root cause, from reading the code:

  • With tools present, common_chat_params_init_inkling builds a lazy tool-call grammar that stays dormant until a trigger pattern matches the generated output.
  • The first-block trigger is PATTERN_FULL "[^<]+", i.e. "output that starts with no < is a tool call starting at the tool name".
  • That assumes the generation prompt ends at <|message_model|>. But the inkling templates pre-fill <|message_model|><|content_text|> on the thinking-off path (the stock inkling2.jinja enable_thinking=false branch, and thinkoff-style variants like the attached one). Every normal reply therefore begins with bare text.
  • The trigger fires on the first text token, the buffered text is replayed into a grammar whose root only accepts tool names, no stack survives, and llama_grammar_accept_token throws: Unexpected empty grammar stack after accepting piece: Hello (32269) (32269 is "Hello" in this model's vocab).
  • The secondary trigger <\|message_model\|>([^<]) has the same flaw for later blocks: a header followed by text without a content marker also gets force-fed into the tool-call grammar.

Net effect: inkling model + tools attached + thinking off = every plain reply dies with a mid-stream 500. The same symptom is being reported downstream through apps that embed llama.cpp, currently misattributed to their own code: lmstudio-ai/lmstudio-bug-tracker#2632.

Suggested fix: the tool names are known when the grammar is built, so anchor both triggers on the actual names instead of "anything without <":

--- a/common/parsers/inkling.cpp
+++ b/common/parsers/inkling.cpp
@@ -149,14 +149,29 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template & tmpl,
         });

         if (data.grammar_lazy) {
-            // a header followed by text and not by a content token is a tool call, the grammar starts at the name
-            data.grammar_triggers = {
-                { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|message_model\\|>([^<])" },
-            };
-            // Inkling 1: the first header is in the generation prompt, and a lazy grammar does not get the prompt.
-            // an output that starts with no content token is a tool call. not for a continuation, it starts with text
+            // tool calls carry no prefix marker, anchor the triggers on the tool names
+            std::string names;
+            foreach_function(inputs.tools, [&](size_t, const json & tool) {
+                const auto & function = tool.at("function");
+                std::string  name     = function.at("name");
+                if (name.empty()) {
+                    return;
+                }
+                if (!names.empty()) {
+                    names += "|";
+                }
+                names += regex_escape(name);
+            });
+            if (!names.empty()) {
+                // a header followed by a tool name is a tool call, the grammar starts at the name
+                data.grammar_triggers = {
+                    { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|message_model\\|>(" + names + ")" },
+                };
+                // Inkling 1: the first header is in the generation prompt, and a lazy grammar does not get the prompt.
+                // an output that starts with a tool name is a tool call. not for a continuation, it starts with text
+                if (!inputs.has_continuation()) {
+                    data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "^(" + names + ")" });
+                }
+            }
         }
     }

Verified with b12631 + this patch (Windows, Vulkan): plain replies with tools attached stream normally, real tool calls still wake the grammar and are constrained to the known tool list and valid JSON args, and opt-in thinking is unaffected. Known trade-off: a plain reply that happens to begin with a literal tool name would wake the grammar, the same failure class as literal marker triggers in other formats.

Template file for the repro: inkling2-thinkoff.jinja.txt (uploaded as .txt since GitHub rejects .jinja uploads; rename back to .jinja to use it).

First Bad Commit

4ddf2b94 - "chat : implement inkling parser (#32381)", merged 2026-11-16.

The trigger heuristic landed together with the parser itself: no later commit touches common/parsers/inkling.cpp, so no bisect was needed. Every build with inkling chat support has the bug - there is no earlier working version of this code path.

Relevant log output

Logs
{"error":{"code":500,"message":"got exception: Unexpected empty grammar stack after accepting piece: Hello (32269)","type":"server_error"}}
</details>

nikosleft avatar Nov 22 '26 17:11 nikosleft

That assumes the generation prompt ends at <|message_model|>. But the inkling templates pre-fill <|message_model|><|content_text|> on the thinking-off path (the stock inkling2.jinja enable_thinking=false branch, and thinkoff-style variants like the attached one). Every normal reply therefore begins with bare text.

This isn't the template the model ships. Is this something produced by LM Studio?

aldehir avatar Nov 22 '26 18:11 aldehir

The attached template is ours, not the model's and not LM Studio's - a local variant that pins the text channel at effort 0 (keyed off reasoning_effort), because this model opens a thinking block at effort 0 unless pinned.

For what it's worth, I re-tested after your comment with the template embedded in the GGUF (--reasoning off, same tools request): no crash. It has no add_generation_prompt handling, so the output starts with the model's own marker and the trigger never fires. So the crash seems specific to templates that pre-fill <|message_model|><|content_text|> - which is what LM Studio users apparently hit through their default path for this model (same exception with tools on, lmstudio-ai/lmstudio-bug-tracker#2632).

No urgency from my side - I'll stay on the think-off template with tools disabled until there's a fix. If it's useful, two directions come to mind: anchor the triggers on the actual tool names (diff in the OP), or make the replay degrade instead of throwing on mismatch.

nikosleft avatar Nov 22 '26 18:11 nikosleft

Another data point: the same exception also happens with the template embedded in the GGUF, without any custom template. In my case, though, the grammar trigger is not the root cause. It is the all-? output from #32778 / #32710 waking the lazy tool-call grammar.

Setup

  • b12631 official Windows CUDA 13.5 binaries (version: 1.0.0-dev (build 12631, commit e300919cc))
  • RTX 4070 12 GB, 32 GB RAM, Windows 11
  • AtomicChat/Inkling-2-Mini-Uncensored-GGUF, AD-IQ3_S, embedded chat template (no --chat-template-file)
  • llama-server --jinja -m model.gguf -ngl -1 --flash-attn auto -np 1 -c 8192 --fit on. The model doesn't fully fit in VRAM, so --fit puts some expert tensors on the CPU.

Results (fresh server for each row group)

Request without --no-op-offload with --no-op-offload
short prompt (22 tok), no tools ✅ normal reply ✅
long prompt (245 tok), no tools ❌ content is all ?, empty reasoning ✅ normal reply (749 tok prompt)
short prompt + 1 tool (~103 tok rendered) ❌ 500 Unexpected empty grammar stack after accepting piece: ? (30) ✅ normal reply
"weather in Berlin?" + 1 tool ❌ same 500 ✅ correct get_weather({"city":"Berlin"}) call
long prompt + 1 tool – ✅ normal reply

The same happens with and without --reasoning-budget, and with reasoning_effort: "none".

So in this setup the piece that kills the grammar is ? (30). That is the garbage first token from the op-offload issue, not bare text from a pre-filled <|content_text|>. With tools attached, the rendered prompt easily goes past the ~96-token threshold, which is why this looks tools-specific. The [^<]+ trigger then turns a garbage reply into a hard 500.

This may be worth keeping in mind when triaging downstream reports with this message (e.g. the LM Studio one). Some of them are probably #32778 rather than the trigger heuristic. The name-anchored triggers proposed above would still help here: the reply would come back as ???? instead of a 500.

Workaround for anyone landing here: --no-op-offload.

parda21 avatar Nov 22 '26 19:11 parda21

I checked nikosleft's name-anchored trigger proposal with a bounded native CPU fixture against parser blob 9c30cdb87962.

The unchanged parser passes 6/10 normal cases; the proposed triggers pass 10/10. The matrix includes prefilled plain text, ?, explicit text markers, first/later tool calls, continuation, no tools and an escaped tool-name dot. A separate control retains the known literal-tool-name prose hazard in both arms.

Fixture, exact source, results and reproduction. The real template/parser, trigger matcher and grammar acceptance are used; a source-extracted lazy replay adapter supplies explicit text pieces without a vocabulary. No model, HTTP request or GPU was run, so this does not claim an end-to-end HTTP500 reproduction or repair of the CPU-MoE corruption reported above.

Could this matrix be kept with the trigger fix, preserving the distinction between custom text-prefill and corrupt-output reports?

mercant1982 avatar Nov 22 '26 21:11 mercant1982