Eval bug: Step 3.7 Flash gets stuck in reasoning trying to make tool calls (autoparser)
Name and Version
% ./build/bin/llama-cli --version version: 9524 (59917d392) built with AppleClang 21.0.0.21000101 for Darwin arm64
Operating systems
Mac
GGML backends
Metal
Hardware
Mac M1 GPU.
Models
Step 3.7 Flash
Problem description & steps to reproduce
Description
Ever since https://github.com/ggml-org/llama.cpp/pull/23845 was opened, I've been trying Step 3.7 Flash and experiencing a strange issue where it would get stuck in reasoning loop patterns when using the pi agent. This is an example reasoning pattern of what I mean:
If the server computes probabilities for each token and stores them, this could grow. Let me check what completion_token_output is.
Let me search for it.
Also, I want to check if there's something in the llama_decode or graph evaluation that allocates per-token.
Actually, let me look at the llama-context.cpp decode function more carefully.
Wait, I think I found something very relevant. Let me look at the llama_decode function and the llama_batch allocation.
Actually, let me look at llama-context.cpp around line 3451 where llama_decode is defined.
Actually, let me take a different approach. Let me look at the ggml_backend_sched code to see if it reallocates buffers dynamically.
Let me search for the scheduler implementation.
Also, let me look at the llama_graph_result and llm_graph_result structures. These might allocate memory per inference step.
Actually, looking at llama-context.cpp line 409:
The main thing to watch for are repeated instances where the model looks like it is going to perform a tool call ("Let me search for ...", "Let me inspect read..."), but then follows up with something like "Actually..."
Sometimes it is able to leave these loops, other times it gets stuck forever. This kind of reasoning pattern never happens when using the official stepfun API.
Investigation
I decided to test an earlier version of llama.cpp where I remember Step 3.5 Flash was working fine (3dadc88b589ca43b8fca0e1beb22d4b78a09b4dd) and couldn't reproduce the issue. The output looked a lot more like what I see in stepfun API.
I did git bisect to find the first commit which introduced the issue, and it pointed to 566059a26b0ce8faec4ea053605719d399c64cc5
Tried multiple times and confirmed that this is the first commit that shows the problematic behavior
How to reproduce
The way I reproduce is with the pi coding harness, so I will give instructions to reproduce my environment as much as possible:
- Run llama server with stepfun IQ4_XS quant and these args (no mmproj since support for step3vl was added after autoparser, and I used this for bisecting):
ctx=262144
parallel=1
ctx_size=$((ctx * parallel))
llama-server --no-mmap --no-warmup --model Step-3.7-flash-IQ4_XS-00001-of-00003.gguf \
--ctx-size $ctx_size -np $parallel -fa on --temp 1.0 --top-p 0.95 \
--repeat-penalty 1.0 --presence-penalty 0.0 \
-cram 0 \
--host 0.0.0.0
- cd into a clean checkout of llama.cpp on commit d132f22fc92f36848f7ccf2fc9987cd0b0120825. The commit might be irrelevant and it might work on master, but this is what I'm using. This should be a separate checkout than the llama.cpp dir used for development.
- install pi harness. at the time of writing, I'm using pi 0.78.1. Create ~/.pi/agent/models.json with the following contents:
{
"providers": {
"local-llm": {
"baseUrl": "http://127.0.0.1:8080/v1",
"api": "openai-completions",
"apiKey": "local",
"models": [
{
"id": "llama.cpp",
"contextWindow": 262144,
"maxTokens": 80000
}
]
},
"step-3.7-flash": {
"baseUrl": "https://api.stepfun.ai/v1",
"api": "openai-completions",
"apiKey": "$STEP_API_KEY",
"models": [
{
"id": "step-3.7-flash",
"contextWindow": 262144,
"maxTokens": 80000
}
]
}
}
}
(The stepfun api entry is only needed if interested in checking the stepfun API. You need to put at least $20 to leave the basic tool call tier).
- create a "prompt.txt" file with the following contents:
This is llama.cpp source code. I'm currently using llama.cpp to run a heavy quantization of Qwen 3.5 397B on a 128G mac studio, and after loading with 128K context, htop shows 126GB used.
I would have assumed that when llama.cpp allocates context memory, it doesn't need to dynamically grow. Yet after chatting with the model for a conversation that lasts about 30k tokens, I start to see llama-server memory increase and swap being used.
I wonder if there's some CLI flag I'm missing to prevent dynamic allocations. I'm using llama.cpp metal backend with 100% of the layers offloaded to GPU.
This is the full script I'm using:
#!/bin/sh -e
model=$HOME/qwen-3.5-397b/Qwen3.5-397B-A17B-IQ3_XXS-00001-of-00004.gguf
mmproj=$HOME/qwen-3.5-397b/mmproj-F16.gguf
parallel=1
ctx=131072
ctx_size=$((ctx * parallel))
llama-server --no-mmap --no-warmup --model $model --mmproj $mmproj --ctx-size $ctx_size -np $parallel --temp 0.6 --top-p 0.95 --top-k 20 --min-p 0.00 -cram 0 --host
0.0.0.0 --swa-full
Explore the codebase to find other possible causes of memory increase.
- Run
pi --no-extensions "$(cat prompt.txt)"
It is not very exact but eventually you should start seeing these repetition patterns, even if the model eventually does respond. Most likely it will get stuck in an infinite reasoning loop. ~If you see it generate 7k reasoning tokens without making a single tool call, that's a good signal.~
The last commit that doesn't have this bug is 34df42f7bef5a711b2b40f5d2b6b78254def99c3. Running this test on that version should not reproduce the same reasoning patterns and match the official API much more closely.
Unfortunately I cannot think of a simpler way to reproduce the issue. It seems to be only reproducible in a complex tool calling environment. What makes it worse is that even the official API is not perfect and has tool calling issues that manifest randomly as I've reported here. This makes me think that the past infinite reasoning loops that I've seen happening with Step 3.5 in the stepfun chat were caused by chat template or parsing bugs.
Even on the stepfun API or llama.cpp version that doesn't have this specific bug (where multiple times in a row it looks like it is going to make a tool call but falls back to "Actually..."), this model can still reason a lot and get into redundant investigation/tool calls.
I've seen instances where this test uses 90%+ of the 256k context before a response is returned,but it can return an answer much sooner, with less than 20% of the context used. ~In any case you should never see any instance where the model generated 7k+ tokens without making a tool call~. Here's one recent example where it used 93% of the context, but still managed to return an answer:
First Bad Commit
566059a26b0ce8faec4ea053605719d399c64cc5
Relevant log output
Logs are irrelevant here.
cc @pwilkin @forforever73
Huge thanks for taking time to reproduce this and bisect it down. Just to make sure: after the autoparser refactor, what is the current situation for Step 3.5 in terms of the infinite loop ? or is Step 3.7 simply happening more frequently now?
Just to make sure: after the autoparser refactor, what is the current situation for Step 3.5 in terms of the infinite loop ?
I still haven't tested Step 3.5 too much yet after autoparser was merged, but I'm planning to try reproducing it.
There might also be more than one issue. As discussed here, @AesSedai IQ4_XS quants for Step 3.7 flash, and the new quants for Step 3.5 Flash have significantly higher perplexity/kld than what was measured a few months ago. I know that it is a separate thing to the template, but might also be a factor.
I did have Q4_K_M old quants from @AesSedai which has very low perplexity (< 1% IIRC) and tried running it a couple of times under this benchmark. While I did see some minor repetition, it never seemed to got stuck in infinite reasoning. I'm still going to re-test his new Step 3.5 Flash IQ4_XS quants later.
I'm trying to figure out what exactly in the autoparser could've caused this... really weird.
This is even weirder because I locally ran StepFun 3.5 with the autoparser for quite some time, with no artifacts at all.
I can't help much on this but I pushed GPT 5.5 to do an investigation, which could be complete hallucination:
Investigation
StepFun's generation prompt force-opens reasoning:
<|im_start|>assistant
<think>
The model is expected to generate reasoning text and later close it:
</think>
With tools enabled, llama.cpp uses lazy grammar triggers for tool calls. The same reasoning-budget sampler is used even when the token budget is unlimited, because lazy grammar needs thinking-block suppression: <tool_call> should not activate tool-call grammar while the model is still inside <think>...</think>.
The problem was that the autoparser found raw reasoning delimiters including surrounding whitespace:
start = "<think>\n"
end = "\n</think>\n"
but common_chat_params only exposed trimmed thinking tags:
thinking_start_tag = "<think>"
thinking_end_tag = "</think>"
Those trimmed tags are correct for API-facing metadata and normal parsing, but they are not enough for reasoning-budget state tracking. The sampler was initialized from the trimmed strings, while the template's generation prompt contains the raw pre-opened marker <think>\n.
Depending on tokenization, <think>\n can be represented differently from <think>. That means accepting generation-prompt prefill tokens may not make the reasoning-budget sampler enter the counting state. If the sampler stays idle, lazy grammar can treat a generated <tool_call> inside reasoning as a real tool-call trigger.
Why It Affected The Default Case
This was not limited to callers passing enable_thinking=false or an explicit reasoning budget.
For lazy tool grammar, the reasoning-budget sampler is initialized even with unlimited budget so it can suppress grammar triggers inside thinking. Therefore the default case with tools and enable_thinking=true still depends on correct reasoning state.
In the failing StepFun path:
- The template pre-opens reasoning in the prompt with
<think>\n. - The model starts generating reasoning text.
- The reasoning-budget sampler may not notice that reasoning was already opened.
- A literal
<tool_call>generated during reasoning can activate the lazy tool grammar too early.
The visible symptom can look like a StepFun tool/reasoning regression rather than a generic parser bug.
That's against the current codebase though, the original autoparser branch didn't even have reasoning budgets.
Also no, StepFun doesn't have grouped tokenization for reasoning tokens with newlines, just checked:
0 -> '<|begin▁of▁sentence|>'
5809 -> '\n'
5809 -> '\n'
128798 -> '<think>'
5809 -> '\n'
5809 -> '\n'
5809 -> '\n'
128799 -> '</think>'
5809 -> '\n'
5809 -> '\n'
Yea seems like hallucination. GPT also failed to fix the issue in the autoparser, so I asked it to produce a patch that opts out of it for Step 3.7 Flash and seems to have fixed it for me (still running a bunch of tests as those take a while):
diff --git a/common/chat.cpp b/common/chat.cpp
index ef151691c..9aa28ab93 100644
--- a/common/chat.cpp
+++ b/common/chat.cpp
@@ -2048,6 +2048,183 @@ static common_chat_params common_chat_params_init_deepseek_v3_2(const common_cha
return data;
}
+static common_chat_params common_chat_params_init_stepfun_3_7(const common_chat_template & tmpl,
+ const autoparser::generation_params & inputs) {
+ common_chat_params data;
+
+ data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
+ data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
+ data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
+ data.supports_thinking = true;
+
+ const std::string ASSISTANT_PREFIX = "<|im_start|>assistant\n";
+ const std::string THINK_START = "<think>\n";
+ const std::string THINK_END = "</think>";
+ const std::string TOOL_CALL_START = "<tool_call>";
+ const std::string TOOL_CALL_END = "</tool_call>";
+ const std::string FUNCTION_START = "<function=";
+ const std::string FUNCTION_END = "</function>";
+ const std::string PARAMETER_START = "<parameter=";
+ const std::string PARAMETER_END = "</parameter>";
+
+ // The Step 3.7 generation prompt force-opens thinking as "<think>\n". Keep
+ // that exact start marker so the current reasoning-budget sampler sees the
+ // prefilled thinking block.
+ data.thinking_start_tag = THINK_START;
+ data.thinking_end_tag = THINK_END;
+ data.preserved_tokens = {
+ "<think>",
+ THINK_END,
+ TOOL_CALL_START,
+ TOOL_CALL_END,
+ FUNCTION_START,
+ FUNCTION_END,
+ PARAMETER_START,
+ PARAMETER_END,
+ };
+
+ if (!inputs.enable_thinking && string_ends_with(data.generation_prompt, THINK_START)) {
+ data.prompt += THINK_END;
+ data.generation_prompt += THINK_END;
+ }
+
+ if (inputs.has_continuation()) {
+ const auto & msg = inputs.continue_msg;
+
+ data.generation_prompt = ASSISTANT_PREFIX + THINK_START + msg.reasoning_content;
+ if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
+ data.generation_prompt += "\n" + THINK_END + "\n" + msg.render_content();
+ }
+
+ data.prompt += data.generation_prompt;
+ }
+
+ auto has_tools = inputs.tools.is_array() && !inputs.tools.empty();
+ auto has_response_format = !inputs.json_schema.is_null() && inputs.json_schema.is_object();
+ auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
+ auto include_grammar = has_response_format || (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE);
+
+ auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
+ auto generation_prompt = p.literal(ASSISTANT_PREFIX);
+ auto end = p.end();
+
+ auto think_open = p.literal(THINK_START) | (p.literal("<think>") + p.optional(p.literal("\n")));
+ auto think_close = p.optional(p.literal("\n")) + p.literal(THINK_END) + p.optional(p.literal("\n"));
+
+ auto reasoning = p.eps();
+ if (extract_reasoning && inputs.enable_thinking) {
+ reasoning = think_open +
+ p.reasoning(p.until_one_of({ "\n" + THINK_END, THINK_END })) +
+ p.optional(think_close);
+ } else if (extract_reasoning) {
+ reasoning = p.optional(think_open + p.until_one_of({ "\n" + THINK_END, THINK_END }) + think_close);
+ }
+
+ if (has_response_format) {
+ return generation_prompt + reasoning +
+ p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema)) + end;
+ }
+
+ if (!has_tools || inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_NONE) {
+ return generation_prompt + reasoning + p.content(p.rest()) + end;
+ }
+
+ auto tool_choice = p.choice();
+ foreach_function(inputs.tools, [&](const json & tool) {
+ const auto & function = tool.at("function");
+ std::string name = function.at("name");
+ auto params = function.contains("parameters") ? function.at("parameters") : json::object();
+
+ auto schema_info = common_schema_info();
+ schema_info.resolve_refs(params);
+
+ auto args = p.sequence();
+ auto arg_string = p.rule("stepfun-xml-arg-string", p.until_one_of({
+ "\n" + PARAMETER_END,
+ "\n" + PARAMETER_START,
+ "\n" + FUNCTION_END,
+ PARAMETER_END,
+ PARAMETER_START,
+ FUNCTION_END,
+ }));
+
+ foreach_parameter(function, [&](const std::string & param_name, const json & param_schema, bool is_required) {
+ auto rule_name = "tool-" + name + "-arg-" + param_name;
+
+ auto arg_open = p.literal(PARAMETER_START) +
+ p.tool_arg_name(p.literal(param_name)) +
+ p.literal(">") +
+ p.optional(p.literal("\n"));
+ auto arg_close = p.optional(p.tool_arg_close(
+ p.optional(p.literal("\n")) +
+ p.literal(PARAMETER_END) +
+ p.optional(p.literal("\n"))));
+
+ auto arg_value = p.eps();
+ if (schema_info.resolves_to_string(param_schema)) {
+ arg_value = p.tool_arg_string_value(arg_string);
+ } else {
+ arg_value = p.tool_arg_json_value(
+ p.schema(p.json(), rule_name + "-schema", param_schema, false));
+ }
+
+ auto arg_rule = p.rule(rule_name, p.tool_arg(p.tool_arg_open(arg_open) + arg_value + arg_close));
+ args += p.repeat(arg_rule, /* min = */ is_required ? 1 : 0, /* max = */ 1);
+ });
+
+ auto tool_open = p.tool_open(
+ p.literal(FUNCTION_START) +
+ p.tool_name(p.literal(name)) +
+ p.literal(">") +
+ p.optional(p.literal("\n")));
+ auto tool_close = p.tool_close(
+ p.optional(p.literal("\n")) +
+ p.literal(FUNCTION_END) +
+ p.optional(p.literal("\n")));
+
+ auto tool_parser = p.tool(tool_open + p.tool_args(args) + tool_close);
+ tool_choice |= p.rule("tool-" + name, tool_parser);
+ });
+
+ auto min_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0;
+ auto max_calls = inputs.parallel_tool_calls ? -1 : 1;
+ auto tool_call = p.rule("tool-call",
+ p.literal(TOOL_CALL_START) +
+ p.optional(p.literal("\n")) +
+ tool_choice +
+ p.literal(TOOL_CALL_END) +
+ p.space());
+ auto tool_calls = p.trigger_rule("tool-call-root", p.repeat(tool_call, min_calls, max_calls));
+
+ auto content_before_tools = p.content(p.until(TOOL_CALL_START));
+ return generation_prompt + reasoning + content_before_tools + tool_calls + end;
+ });
+
+ data.parser = parser.save();
+
+ if (include_grammar) {
+ data.grammar_lazy = has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO && !has_response_format;
+ data.grammar = build_grammar([&](const common_grammar_builder & builder) {
+ foreach_function(inputs.tools, [&](const json & tool) {
+ const auto & function = tool.at("function");
+ auto schema = function.contains("parameters") ? function.at("parameters") : json::object();
+ builder.resolve_refs(schema);
+ });
+ if (has_response_format) {
+ auto schema = inputs.json_schema;
+ builder.resolve_refs(schema);
+ }
+ parser.build_grammar(builder, data.grammar_lazy);
+ });
+
+ data.grammar_triggers = {
+ { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, TOOL_CALL_START },
+ };
+ }
+
+ return data;
+}
+
namespace workaround {
static void map_developer_role_to_system(json & messages) {
@@ -2325,6 +2502,20 @@ std::optional<common_chat_params> common_chat_try_specialized_template(
return common_chat_params_init_deepseek_v3_2(tmpl, params);
}
+ // StepFun Step 3.7 uses the XML tool-call shape from the old manual
+ // Step/Nemotron route, but its template source has reasoning_effort
+ // handling that distinguishes it from Step 3.5/Qwen/Nemotron.
+ if (src.find("reasoning_effort is defined") != std::string::npos &&
+ src.find("render_message_content(message)") != std::string::npos &&
+ src.find("<tool_call>") != std::string::npos &&
+ src.find("<function=") != std::string::npos &&
+ src.find("<parameter=") != std::string::npos &&
+ src.find("<|im_start|>assistant\\n<think>\\n") != std::string::npos) {
+ workaround::func_args_not_string(params.messages);
+ LOG_DBG("Using specialized template: StepFun Step 3.7\n");
+ return common_chat_params_init_stepfun_3_7(tmpl, params);
+ }
+
// Gemma4 format detection
if (src.find("'<|tool_call>call:'") != std::string::npos) {
if (src.find("{#- OpenAI Chat Completions:") == std::string::npos) {
Okay, this is bizarre. I'll have to compare those two parsers (the autoparser-generated one and the one your clanker spit out) and see what's the difference.
I've mentioned that it never produces 7k tokens without calling a tool, but that was not a good signal. I just had it produce thousands of thinking tokens before making a tool call. To be clear: It was not stuck trying to make a tool call, it simply had a huge reasoning block. What you should be looking for is it getting stuck trying to make a tool call as I've shown in the issue description.
It is one of the reasons I like Step Flash models: They have an lot of variability in their outputs, each session is completely different even with the same inputs.
@pwilkin Thanks for looking into it
As I mentioned, even the official API parser is problematic 😓
Here's something I saw while running this test against the official API:
Not to mention random tool call failures which happen every once in a while.
Oh, this will always run you into problems: having prompts that use actual reserved tokens (<think>, </think>, <tool_call> etc). You have no idea how much of a pain that was when working on the parser code ;)
FWIW I just ran your query in my OpenCode on my local StepFun 3.7 IQ4_XS, Q8 KV quants, 140k context. So far it's doing tool calls, not overthinking - longest thinking segment was:
The user is running llama.cpp with a large model and seeing memory increase during a long conversation. They want to understand if there are CLI flags to prevent dynamic allocations, or if there are other causes of memory increase.
Let me start by examining the llama.cpp codebase structure, focusing on:
- Memory allocation patterns
- Context/sequence handling that might grow dynamically
- Server-side memory management
- Any flags related to memory allocation
Let me first look at the project structure and then dive into relevant code.
BTW, if you're still interested in the answer to your question that you sent to the agent, then -ctxcp is probably the reason :)
BTW, if you're still interested in the answer to your question that you sent to the agent, then -ctxcp is probably the reason :)
Yea I already know the answer. Initially when I really had this question, I used GPT/codex to reply.
But it has since evolved into a personal benchmark to test local LLM capacity to read and understand code by both finding the answer (and how accurate it considers ctxcp to be the reason) and if it can spot extras such as the fact that --swa-full has no effect on Qwen 3.5.
Okay, so I've somewhat managed to get what you had:
Let me read around line 748.
Actually, let me read the llama-kv-cache.cpp file from line 700 to 900.
Wait, I think I should also look at the llama-memory-recurrent.cpp for the update method.
Actually, let me search for realloc in all .cpp files in src/.
I already did this and only found a few matches. Let me search more broadly.
Actually, let me look at the llama-kv-cache.cpp for any resize or reserve in the update method.
Let me read the llama-kv-cache.cpp file around the update method.
Actually, let me read the llama-kv-cache.cpp file from line 700 to 900.
Wait, I think I should look at the llama_kv_cache_context class and its update method.
Let me grep for llama_kv_cache_context in src/llama-kv-cache.cpp.
Actually, let me just read the llama-kv-cache.cpp file.
Let me also look at the llama-memory-recurrent.cpp for the update method.
Actually, I think I should focus on the llama-kv-cache.cpp update method. Let me read it.
While I've not observed any infinite loops with single short or interactive chats with Step 3.7, it does seems to massively overthink and repeatedly go into circles while reasoning through relatively simple questions or prompts.
3.5 behaved very well and I regret having upgraded to 3.7. Anyone else seeing problems in non Agentic / non tool-calling uses cases? Thanks.
@tarruda could you please check on #24624 ?
Hi @pwilkin
I gave it a try and doesn't seem fixed on #24624