12-04 更新 实时
首页/ 技术栈/ 正文

投机解码加速工具调用 智能体仍需缓存

技术栈 来源:Towards Data Science 2026-11-27 22:00 0 阅读 机器翻译
投机解码加速工具调用 智能体仍需缓存

草稿模型如何节省时间

大型目标模型每次前向传播只生成一个 Token。在笔记本电脑或单块 GPU 上,每次前向传播都受限于权重从内存中被读取的速度,而运算单元则部分处于空闲状态。在投机解码(speculative decoding)[1, 2] 中,一个小型草稿模型会猜测接下来的 k 个 Token,目标模型则一次前向传播校验全部 k 个 Token,保留双方一致的最长前缀,再补上自己生成的一个 Token。在贪婪解码下,输出原则上与目标模型单独生成的结果完全一致。这就是所谓「无损」的说法,但在我的实测中,它并不总是成立。你能获得多少加速,取决于目标模型接受了多少猜测(即接受率),以及一次验证前向传播相较于一次普通前向传播的成本。

一次贪婪解码步骤大致如下(已简化;真正的循环位于 llama.cpp 内部):

def speculative_step(target, draft, context, k=4): # 1. 草稿模型猜测 k 个 Token,每次只需一次开销很低的前向传播 guesses = [] for _ in range(k): guesses.append(draft.next_token(context + guesses)) # 2. 目标模型一次前向传播即为全部 k 个位置打分,并返回 # 目标模型自身在 k + 1 个位置上各自会选出的 Token picks = target.next_tokens(context, guesses) # 3. 保留到第一个不一致之前的猜测,然后再加上目标模型自己给出的 Token n = 0 while n < k and guesses[n] == picks[n]: n += 1 return guesses[:n] + [picks[n]] # 始终至少有一个新 Token

以下所有内容来自两个模型家族、两个推理引擎的 29,854 次计时请求,外加提示缓存后续测试的 832 次。我使用 llama.cpp [5] 的 llama-server(build 11960),因为大多数本地智能体通过 HTTP 与模型通信,每个步骤一次请求。主要配对(A)以 4-bit(Q4_K_M)的 Qwen3-8B 为目标模型,Qwen3-0.6B(Q8_0)为草稿模型 [4],并关闭思考模式。为检验结果是否在 Qwen 家族之外同样成立,我用 Llama-3.1-8B-Instruct 和 Llama-3.2-1B-Instruct(配对 C)重复了核心扫描。我还把配对 A 跑在 MLX——Apple 的数组框架——上,它自带草稿模型支持。

MT-Bench 首轮对话 [6]

BFCL 的 simple 与 multiple [8]

生成的文本外加一个 JSON schema

来自 22 个重放的 BFCL 多轮回合的 208 个步骤

W5 花的工作量最多。我用目标模型运行 BFCL 多轮任务,在 BFCL 环境中执行其工具调用,并在每一步保存上下文,因此每个 W5 请求都是一个保存下来的状态:系统提示、工具 schema、此前的对话以及工具结果。构建器的第一版在 8 个任务后崩溃了。Qwen 发出的一个工具调用,其 JSON 在字符串中间被截断,llama-server 以 HTTP 500 拒绝了它,而我的脚本对此没有应对方案。现在这类回合会以 "aborted" 结束。W5 的平均提示为 4,085 个 Token;平均回答为 48 个 Token。

每个提示都在计时开始前用模型自身的对话模板渲染并完成分词,因此计时只覆盖智能体实际等待的部分。计时的部分是一次流式请求:

# 在计时之前:使用模型自身的模板进行渲染(包含工具模式),然后进行分词 prompt = post("/apply-template", {"messages": messages, "tools": tools, "chat_template_kwargs": {"enable_thinking": False}})["prompt"] tokens = post("/tokenize", {"content": prompt})["tokens"] t0 = time.perf_counter() stream = requests.post(f"{url}/completion", stream=True, json={ "prompt": tokens, "n_predict": max_new_tokens, "temperature": 0, "top_k": 1, # 贪婪 "cache_prompt": False, # 每个请求都支付其完整的预填充 "stream": True, "return_tokens": True, }) # ...读取 SSE 块;最后一个块携带计时信息: # prompt_ms, predicted_ms, draft_n, draft_n_accepted latency_s = time.perf_counter() - t0

BASE 是单独的目标模型。DRAFT-k 添加了草稿模型,每步最多使用 k 个草稿 Token。每个配置对每个提示运行三次(Llama 和 MLX 运行为两次),在全新的服务器上,以打乱顺序进行。我以每个请求的墙钟延迟来评判一切,从发送请求到接收最后一个 Token。加速比是相同提示上 BASE 平均延迟除以推测平均延迟,带有 95% 的 Bootstrap 置信区间。每个提示的延迟是其重复运行的中位数,而 Bootstrap 以配对方式重采样提示,以便一个提示始终与其自身的基线匹配:

def bootstrap_ratio_ci(base, spec, n_boot=2000, seed=0): base, spec = np.asarray(base), np.asarray(spec) # 每个提示一个值,顺序相同 point = base.mean() / spec.mean() idx = np.random.default_rng(seed).integers(0, len(base), size=(n_boot, len(base))) ratios = base[idx].mean(axis=1) / spec[idx].mean(axis=1) return point, *np.percentile(ratios, [2.5, 97.5])

这一切都跑在一台配备 48 GB 统一内存的 Apple M5 Pro 笔记本上,前后大约三个晚上。白天我会把它停下来,因为笔记本会发烫;我还放弃了原计划中的一个 32B 目标模型,因为那会花太长时间。我的冒烟测试批次只有 5 条提示词,但文件名与完整扫描的批次相同,所以扫描把它们当成已完成的跳过了。我在开始分析之前就发现了这个问题,现在的完成检查还会比较一个批次里的提示词数量。

图 1. 配对 A(Qwen3-8B 与 Qwen3-0.6B)上 DRAFT-4 相对 BASE 的端到端加速比。虚线表示没有变化。

在 k = 4 时,代码生成的速度是单独运行目标模型的 1.72 倍,JSON 提取为 1.65 倍,单次工具调用为 1.41 倍。Chat 提升了 1.19 倍。W5 的长智能体上下文运行速度是 BASE 的 0.94 倍(95% CI 0.93 至 0.95):每一步大约多花 6% 的时间。

接受率与前面四类吻合:JSON 有 95% 的 Token、工具调用有 92% 的 Token、代码有 88% 的 Token 来自草稿模型的猜测,而 Chat 只有 49%。我原本以为从 schema 复制来的花括号和键名会撑起接受率,而参数值会把它拉低。事实并非如此:MLX 会标记每个输出 Token 是否由草稿生成,而在工具调用中,草稿提供了 79% 的结构 Token 和 78% 的参数值 Token。

为什么智能体步骤变慢了

W5 的接受率为 66%,远高于 Chat。但草稿模型也必须读取提示词,因此在推测执行下,预填充会略微变长,而只有解码会变短,端到端收益受限于一次请求花在解码上的时间占比。Amdahl 定律 [3] 给出了具体数字:

预测加速比 = (P + D) / (P' + D / s)。P:BASE 预填充时间(读取提示词);D:BASE 解码时间(写出回答);P':启用推测时的预填充时间(目标模型与草稿模型都要读取提示词);s:推测带来的解码加速倍数。

llama-server 会在其 timings 对象中返回全部四项输入(prompt_ms 和 predicted_ms),因此核验只需几行代码。以下使用工具调用(W3)与智能体步骤(W5)的实测均值:

def amdahl(P, D, P_spec, s): """当只有解码提速 s 倍时的端到端加速比。""" return (P + D) / (P_spec + D / s) # 每次请求的秒数,pair A,DRAFT-4(results/tables/time_split.csv) amdahl(P=0.31, D=0.72, P_spec=0.32, s=1.75) # W3 工具调用 -> 1.41(实测 1.41) amdahl(P=3.33, D=0.97, P_spec=3.71, s=1.16) # W5 智能体步骤 -> 0.94(实测 0.94)

在 W5 中,草稿模型自身的预填充每个步骤增加 0.39 秒,而更快的解码只节省了 0.13 秒。

图 2。左:BASE 请求时间中预填充与解码所占的比例。右:DRAFT-4 的仅解码加速比(浅色)、实测端到端加速比(深色)以及 Amdahl 预测值(黑色刻度标记)。

聊天场景的预填充占比为 2%,几乎完整保留了其 1.19 倍的加速;而预填充占比 30% 的工具调用则从解码环节的 1.75 倍降至整体 1.41 倍。W5 在这两方面都更差(图 2):解码仅加速 1.16 倍,且只作用于不足四分之一的步骤耗时。在 llama.cpp 上 pair A 于 temperature 0 下的全部 29 种推测配置(含 n-gram 模式)中,Amdahl 预测值与实测加速比的偏差从未超过 0.011。

解码加速偏弱的原因是,W5 的回复把工具调用与面向用户的文字混在一起,草稿模型对它的预测效果不如 W3 那种纯粹的工具调用。即便采用 W3 的解码加速,W5 的时间拆分也只能达到约 1.01 倍。

把 22 个 BFCL 任务各自的所有步骤加总后,DRAFT-4 的耗时是 BASE 的 0.94 倍。22 个任务中只有 2 个完成得更快,平均而言,推测解码让一个 41 秒的任务多花了 2.6 秒。

开启提示缓存

我在重新翻看 W5 的数据之后,才安排了这次后续测试。主扫描中的每个请求都设置了 cache_prompt: false,所以每个 W5 步骤都要重新读取整个上下文,而智能体并不是这样运行的。智能体在第 4 步之后紧接着发送第 5 步,llama-server 可以保留上一个请求的键值(KV)缓存,只处理最长共享前缀之后的 Token。如果缓存消除了大部分预填充,那么上面的公式表明推测解码应该开始划算了。

于是,我按智能体的顺序、一个 episode 接一个 episode 地重放了同样的 208 个 W5 步骤,每次运行只在一台服务器上启用 cache_prompt: true,BASE 和 DRAFT-4 各跑两遍。整个过程大约花了 18 分钟。llama-server 会报告它实际处理了多少个提示 Token(prompt_n)、复用了多少个(cache_n),据此可以直接算出命中率:

原文较长,译文为节选;译文由英文原文机器翻译,术语按行业惯例统一,可在文末展开原文核对。

查看英文原文(Speculative Decoding Makes Tool Calls Faster. Agents Need a Cache.)

How a draft model saves time

A large target model produces one token per forward pass. On a laptop or a single GPU, each pass is limited by how fast the weights can be read from memory, and the arithmetic units sit partly idle. In speculative decoding [1, 2], a small draft model guesses the next k tokens, and the target checks all k in one pass, keeps the longest prefix it agrees with and adds one token of its own. With greedy decoding the output is, in principle, exactly what the target would have written alone. That is the "lossless" claim, and in my runs it didn't always hold. How much you gain depends on how many guesses the target accepts (the acceptance rate) and on what a verification pass costs compared with a normal one.

One greedy step looks like this (simplified; the real loop lives inside llama.cpp):

def speculative_step(target, draft, context, k=4): # 1. the draft guesses k tokens, one cheap forward pass each guesses = [] for _ in range(k): guesses.append(draft.next_token(context + guesses)) # 2. one target pass scores all k positions at once and returns # the token the target itself would pick at each of k + 1 positions picks = target.next_tokens(context, guesses) # 3. keep guesses up to the first disagreement, then add the target's own token n = 0 while n < k and guesses[n] == picks[n]: n += 1 return guesses[:n] + [picks[n]] # always at least one new token

Everything below comes from 29,854 timed requests across two model families and two inference engines, plus 832 from the prompt-cache follow-up. I used llama-server from llama.cpp [5] (build 11960), because most local agents talk to a model over HTTP, one request per step. The main pair (A) is Qwen3-8B at 4-bit (Q4_K_M) as the target and Qwen3-0.6B (Q8_0) as the draft [4], with thinking turned off. To see whether the results hold outside the Qwen family, I repeated the core sweep with Llama-3.1-8B-Instruct and Llama-3.2-1B-Instruct (pair C). I also ran pair A through MLX, Apple's array framework, which has its own draft-model support.

MT-Bench first turns [6]

BFCL simple and multiple [8]

generated text plus a JSON schema

208 steps from 22 replayed BFCL multi-turn episodes

W5 took the most work. I ran BFCL multi-turn tasks with the target model, executed its tool calls in the BFCL environments, and saved the context at every step, so each W5 request is one saved state: system prompt, tool schemas, the conversation so far and the tool results. The first version of the builder crashed after 8 tasks. Qwen had emitted a tool call whose JSON was cut off mid-string, llama-server refused it with an HTTP 500, and my script had no plan for that. Now such an episode ends as "aborted". The mean W5 prompt is 4,085 tokens; the mean answer is 48.

Every prompt is rendered with the model's own chat template and tokenized before the timer starts, so the clock covers only what an agent waits for. The timed part is one streamed request:

# before the clock: render with the model's own template (tool schemas included), then tokenizeprompt = post("/apply-template", {"messages": messages, "tools": tools, "chat_template_kwargs": {"enable_thinking": False}})["prompt"]tokens = post("/tokenize", {"content": prompt})["tokens"]t0 = time.perf_counter()stream = requests.post(f"{url}/completion", stream=True, json={ "prompt": tokens, "n_predict": max_new_tokens, "temperature": 0, "top_k": 1, # greedy "cache_prompt": False, # every request pays its full prefill "stream": True, "return_tokens": True,})# ...read the SSE chunks; the last one carries timings:# prompt_ms, predicted_ms, draft_n, draft_n_acceptedlatency_s = time.perf_counter() - t0

BASE is the target alone. DRAFT-k adds the draft model with up to k drafted tokens per step. Each configuration ran every prompt three times (twice for the Llama and MLX runs), on a fresh server, in shuffled order. I judge everything by wall-clock latency per request, from sending it to receiving the last token. Speedup is mean BASE latency divided by mean speculative latency on the same prompts, with a 95% bootstrap confidence interval. Each prompt's latency is the median of its repeats, and the bootstrap resamples prompts in pairs so that a prompt always meets its own baseline:

def bootstrap_ratio_ci(base, spec, n_boot=2000, seed=0): base, spec = np.asarray(base), np.asarray(spec) # one value per prompt, same order point = base.mean() / spec.mean() idx = np.random.default_rng(seed).integers(0, len(base), size=(n_boot, len(base))) ratios = base[idx].mean(axis=1) / spec[idx].mean(axis=1) return point, *np.percentile(ratios, [2.5, 97.5])

All of it ran on an Apple M5 Pro laptop with 48 GB of unified memory, over about three nights. I stopped it during the day because the laptop got hot, and I dropped a 32B target I had planned, because it would have taken too long. My smoke-test batches of 5 prompts also had the same file names as the full sweep, so the sweep counted them as finished and skipped them. I found it before any analysis, and the done-check now also compares the number of prompts in a batch.

Figure 1. End-to-end speedup of DRAFT-4 over BASE for pair A (Qwen3-8B with Qwen3-0.6B). The dashed line marks no change.

With k = 4, code generation ran 1.72 times faster than the target alone, JSON extraction 1.65 times and single tool calls 1.41 times. Chat gained 1.19 times. The long agent contexts of W5 ran at 0.94 times the speed of BASE (95% CI 0.93 to 0.95): each step took about 6% longer.

Acceptance rates line up with the first four: 95% of JSON tokens, 92% of tool-call tokens and 88% of code tokens came from the draft's guesses, against 49% for chat. I expected braces and key names copied from a schema to carry the acceptance rate and argument values to drag it down. They didn't: MLX marks each output token as drafted or not, and in tool calls the draft supplied 79% of the structure tokens and 78% of the argument-value tokens.

Why the agent steps got slower

W5's 66% acceptance was well above chat's. But the draft has to read the prompt too, so with speculation the prefill gets slightly longer while only the decode gets shorter, and the end-to-end gain is capped by the share of time a request spends decoding. Amdahl's law [3] gives the number:

predicted speedup = (P + D) / (P' + D / s)P BASE prefill time (reading the prompt)D BASE decode time (writing the answer)P' prefill time with speculation (target and draft both read the prompt)s decode speedup from speculation

llama-server returns all four inputs in its timings object (prompt_ms and predicted_ms), so checking this takes a few lines. With the measured means for a tool call (W3) and an agent step (W5):

def amdahl(P, D, P_spec, s): """End-to-end speedup when only decode gets s times faster.""" return (P + D) / (P_spec + D / s)# seconds per request, pair A, DRAFT-4 (results/tables/time_split.csv)amdahl(P=0.31, D=0.72, P_spec=0.32, s=1.75) # W3 tool call -> 1.41 (measured 1.41)amdahl(P=3.33, D=0.97, P_spec=3.71, s=1.16) # W5 agent step -> 0.94 (measured 0.94)

In W5 the draft's own prefill adds 0.39 seconds per step and the faster decode saves only 0.13.

Figure 2. Left: share of BASE request time spent in prefill and decode. Right: decode-only speedup (light), measured end-to-end speedup (dark) and the Amdahl prediction (black tick) for DRAFT-4.

Chat is 2% prefill and keeps nearly all of its 1.19 times, while tool calls at 30% prefill fall from 1.75 times on decode to 1.41 overall. W5 is worse on both counts (Figure 2): a decode gain of only 1.16 times, applied to less than a quarter of the step. Across all 29 speculative configurations of pair A at temperature 0 on llama.cpp, n-gram modes included, the Amdahl prediction was never more than 0.011 off the measured speedup.

The weak decode gain is because W5 replies mix tool calls with prose for the user, which the draft predicts less well than W3's bare tool calls. Even with W3's decode gain, W5's time split would only reach about 1.01 times.

Summed over the steps of each of the 22 BFCL tasks, DRAFT-4 took 0.94 times as long as BASE. Only 2 of the 22 tasks finished faster, and on average speculation added 2.6 seconds to a 41-second task.

Turning on the prompt cache

I set up this follow-up after going back over the W5 numbers. Every request in the main sweeps set cache_prompt: false, so every W5 step re-read its entire context, which is not how an agent runs. An agent sends step 5 right after step 4, and llama-server can keep the key-value (KV) cache from the previous request and process only the tokens after the longest shared prefix. If the cache removes most of the prefill, the formula above says speculation should start to pay.

So I replayed the same 208 W5 steps in agent order, episode by episode, with cache_prompt: true on one server per run, for BASE and DRAFT-4, twice each. The whole thing took about 18 minutes. llama-server reports how many prompt tokens it actually processed (prompt_n) and how many it reused (cache_n), which gives the hit rate directly:

# same request as before, but keep the KV cache between agent stepsbody["cache_prompt"] = True# after an episode: share of prompt tokens the server did not have to computeprocessed = sum(r["timings"]["prompt_n"] for r in step_responses)total = sum(len(tokens) for tokens in step_prompts)hit_rate = 1 - processed / total

The cache served 92.8% of all prompt tokens. After the first step of an episode, a step processed 89 tokens on average out of 4,136 (97.8% reused). First steps reused 44%, whatever system prompt and tool schema they happened to share with the end of the previous episode.

I also wanted to know whether the draft model kept its own cache or re-read everything. llama-server's speculative prefill time includes the draft's prefill, and it came out at 1.12 times BASE's without the cache and 1.11 times with it. Had the draft re-read its full 4,000-token context while the target used the cache, that ratio would have jumped above two, since the draft's full prefill (about 0.39 seconds per step uncached) is bigger than BASE's whole cached prefill (0.30 seconds). The ratio barely moved, so the draft reuses its context as well.

Figure 3. Left: mean time per W5 step, split into prefill and decode, with and without the prompt cache. Right: DRAFT-4 speedup over BASE per step and per episode, with 95% CIs.

DRAFT-4 speedup per step

DRAFT-4 speedup per episode

Episodes faster with DRAFT-4

Per episode, the draft saved 1.1 seconds out of 12. The cache alone made BASE steps 3.36 times faster than uncached BASE, and cache plus speculation reached 3.70 times.

Four missing tokens in Qwen3's template

In all 186 step-to-step transitions of a run, reuse stopped exactly 4 tokens before the end of the previous prompt. I compared the token IDs directly and found the cause in Qwen3's chat template. With thinking off, it ends the generation prompt with an empty block, then drops that block when it renders the same assistant turn as history:

def shared_prefix(prev_tokens, next_tokens): n = 0 for a, b in zip(prev_tokens, next_tokens): if a != b: break n += 1 return n# previous prompt + the answer it produced, against the next step's promptn = shared_prefix(prev_prompt + prev_answer, next_prompt)print(len(prev_prompt) - n) # 4 on every Qwen3 step: the dropped empty think block

Because the prefix match breaks there, the model re-processes its own previous answer on every step. With 48-token answers that is cheap.

llama.cpp can also speculate without a draft model: it looks up n-grams in the text it has already seen and proposes how they continued. It needs no second model, just a flag:

# no draft model: propose continuations of n-grams already in the contextllama-server -m Qwen3-8B-Q4_K_M.gguf -ngl 99 -c 32768 -np 1 --jinja --spec-type ngram-mod# draft model and n-gram lookup togetherllama-server -m Qwen3-8B-Q4_K_M.gguf -ngl 99 -c 32768 -np 1 --jinja \ -md Qwen3-0.6B-Q8_0.gguf --spec-draft-n-max 4 --spec-type draft-simple,ngram-mod

I'd expected this to pick up agents echoing tool output, but the best mode, ngram-mod, gave 1.00 times on tool calls, 1.00 on JSON extraction and 1.03 on W5 (uncached), and combined with the draft model it matched the draft model alone on tool calls and JSON (1.41 and 1.65 times). My guess is that the replies are too short to repeat much.

What acceptance rate do you need?

Figure 4. Per-request speedup against acceptance rate for all pair A speculative requests, with the fitted line and its crossing of 1.0.

A linear fit of per-request speedup against acceptance, over all pair A speculative requests, crosses 1.0 at an acceptance rate of 0.43 (95% CI 0.42 to 0.44):

# one point per speculative request: (draft_n_accepted / draft_n, BASE latency / its latency)slope, intercept = np.polyfit(acceptance, speedup, 1)break_even = (1.0 - intercept) / slope # acceptance where the line crosses speedup = 1

For the Llama pair, whose 1B draft is relatively more expensive, the line crosses at 0.60. Prefill share moves a request's speedup as much as acceptance does, so the fit is loose (R² of 0.42 for pair A). Below about 0.45 acceptance (0.6 with a 1B draft) I wouldn't expect a gain even on decode-heavy requests.

Draft length and temperature

Figure 5. End-to-end speedup against the maximum number of drafted tokens k, per workload, pair A. Image by author.

On JSON extraction, k = 8 (1.68 times) edged out k = 4 (1.65 times), and on tool calls they tied (1.42 and 1.41 times). On chat, k = 8 already lost (0.85 times) and k = 16 more than halved the speed (0.45 times), because every rejected guess still costs verification work. By geometric mean across workloads k = 4 and k = 8 came out best, and for mixed traffic I'd pick k = 4.

Most published speedups are measured at temperature 0, so I reran DRAFT-4 at 0.7. The speedups barely moved: 1.42 times on tool calls, 1.66 on JSON, 1.72 on code and 1.15 on chat. BASE at 0.7 still matched the greedy output on 196 of the 200 tool-call prompts (5 of the 80 for chat).

When lossless still changes the output

Greedy speculative decoding should return the same tokens as the target alone. In 1,349 of the 20,390 outputs I compared, it didn't. Most were chat: about half of pair A's W1 outputs differed from BASE at every k, against 9% of its W2 outputs and 8% of its W5 outputs, and none of its tool calls or JSON outputs on llama.cpp. If you need reproducible outputs, for tests or for caching by output hash, don't compare speculative outputs against a non-speculative baseline.

I probed 300 of the chat cases. At the first token where the two outputs diverge, I re-ran the target over the shared prefix in one batch and read its probabilities:

i = next(j for j, (a, b) in enumerate(zip(base_tokens, spec_tokens)) if a != b)r = requests.post(f"{url}/completion", json={ "prompt": prompt_tokens + base_tokens[:i], # everything both runs agree on "n_predict": 1, "temperature": 0, "top_k": 1, "n_probs": 3, "cache_prompt": False,}).json()top = {t["id"]: t["logprob"] for t in r["completion_probabilities"][0]["top_logprobs"]}gap = abs(top[base_tokens[i]] - top[spec_tokens[i]]) # near-tie if below 0.2

In 286 cases the two candidates were a near-tie (log-probability gap below 0.2, median 0.03), and the batched pass picked the token from the speculative output. Verification evaluates several tokens in one batch while a normal decode step evaluates one, so the two paths use different kernels and summation orders. With a near-tie, that rounding difference is enough to flip the token, and everything after it changes.

The other 14 cases come from just two divergence points, repeated across configurations and repeats. One is close to a tie (a gap of 0.27 between " two" and " first"), but the other isn't: in a Markdown table separator, the batched pass prefers a seven-dash token with a probability of about 0.83, while the one-token BASE path wrote the eight-dash token. The batched pass agrees with the speculative output there too, so the draft did not sneak in a token the target rejects. A gap that large is more than I'd expect from summation order, and I haven't found the cause.

DRAFT-4 speedup over BASE at temperature 0:

The Llama pair showed the same split with smaller gains. Tool calls gained slightly less than chat here, because Llama's acceptance on tool calls (83%) was lower than Qwen's (92%) and its chat acceptance (67%) higher. Its draft is also larger relative to the target (1B against 8B), so each guess costs more.

MLX gave pair A bigger gains on W1 to W4. It uses its own 4-bit weights for both models, so this compares two sets of model files as well as two engines. Every speedup went up by 0.16 to 0.24 times and the order of the workloads stayed the same.

MLX is also where the drafted-token split I quoted earlier comes from, because mlx_lm flags every generated token that came from the draft:

from mlx_lm import load, stream_generatemodel, tokenizer = load("mlx-community/Qwen3-8B-4bit")draft, _ = load("mlx-community/Qwen3-0.6B-4bit")from_draft = []for resp in stream_generate(model, tokenizer, prompt, max_tokens=256, draft_model=draft, num_draft_tokens=4): from_draft.append((resp.text, resp.from_draft))# label each token as JSON structure, key name or argument value, then average from_draft per label

All the numbers come from one M5 Pro laptop. My first plan framed the whole piece around Apple Silicon, and I dropped that, since the exact speedups are specific to this laptop while the prefill arithmetic is not. Apple Silicon has unified memory and its own balance of bandwidth and compute, and on a discrete GPU both the prefill share and the cost of a verification pass will be different.

The server may also undersell speculation. Users have reported that llama-server drafts fewer tokens and runs 10 to 15% slower than llama.cpp's speculative example [9]. A 2026 report found that multi-token-prediction speculation lost throughput at every configuration on Apple's Metal backend [10]. That is a different method, and I haven't tested it.

Run the check on your own agent

A draft model in llama-server takes a few extra flags. Flag names have changed across builds, so check llama-server --help | grep -i draft first.

# target alonellama-server -m Qwen3-8B-Q4_K_M.gguf -ngl 99 -c 32768 -np 1 --jinja# with a draft model, up to 4 drafted tokens per stepllama-server -m Qwen3-8B-Q4_K_M.gguf -ngl 99 -c 32768 -np 1 --jinja \ -md Qwen3-0.6B-Q8_0.gguf -ngld 99 \ --spec-draft-n-max 4 --spec-type draft-simple # older builds: --draft-max 4

The draft has to share the target's tokenizer, which in practice means the same model family. -np 1 keeps a single slot, so requests run one at a time, as they would for a single agent, and every step lands in the same cache slot.

Each /completion response includes a timings object, and its fields are enough to decide:

import timeimport requestsdef timed_completion(prompt, url="http://127.0.0.1:8080", cache=True): t0 = time.perf_counter() r = requests.post(f"{url}/completion", json={ "prompt": prompt, "n_predict": 256, "temperature": 0, "top_k": 1, "cache_prompt": cache, # reuse the KV cache of the previous request }).json() t = r["timings"] return { "latency_s": time.perf_counter() - t0, # what your agent waits for "prefill_ms": t["prompt_ms"], # reading the prompt "decode_ms": t["predicted_ms"], # writing the answer "tokens_processed": t["prompt_n"], # prompt tokens actually computed "tokens_reused": t.get("cache_n"), # prompt tokens served from the cache "acceptance": (t["draft_n_accepted"] / t["draft_n"]) if t.get("draft_n") else None, }

Send the prompts your agent actually sends, in the order it sends them, once to each server, and compare mean latency. Compute the prefill share, P / (P + D), from the BASE run. Above about one half I wouldn't bother with a draft model unless the decode speedup is large; at a tenth or less, most of the decode speedup survives end to end. Also look at tokens_reused on step 2 of an agent loop. Near zero means the prompt cache isn't working.

Conclusion: what I'd change on an agent server

If the server mostly answers single tool calls or JSON requests, I'd add a small draft model and not think much more about it. For an agent loop with long contexts I'd turn on the prompt cache first, which gave 3.4 times by itself, and only then add the draft. Without the cache I'd leave the draft off for agent loops altogether.

The code, prompt sets, raw results and figures are here: https://github.com/ankur287/speculative-decoding-agents

[1] Y. Leviathan, M. Kalman and Y. Matias, Fast Inference from Transformers via Speculative Decoding (2023), ICML 2023

[2] C. Chen, S. Borgeaud, G. Irving, J.-B. Lespiau, L. Sifre and J. Jumper, Accelerating Large Language Model Decoding with Speculative Sampling (2023), arXiv:2302.01318

[3] G. M. Amdahl, Validity of the Single Processor Approach to Achieving Large Scale Computing Capabilities (1967), AFIPS Spring Joint Computer Conference

[4] Qwen Team, Qwen3 Technical Report (2025), arXiv:2505.09388

[5] G. Gerganov and contributors, llama.cpp (2023), GitHub repository ggml-org/llama.cpp

[6] L. Zheng, W.-L. Chiang, Y. Sheng et al., Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena (2023), NeurIPS 2023 Datasets and Benchmarks Track

[7] M. Chen, J. Tworek, H. Jun et al., Evaluating Large Language Models Trained on Code (2021), arXiv:2107.03374

[8] S. G. Patil, H. Mao, F. Yan et al., The Berkeley Function Calling Leaderboard (BFCL): From Tool Use to Agentic Evaluation of Large Language Models (2025), ICML 2025

[9] llama.cpp issue #12968, Misc. bug: llama-server speculative decoding not as performant as llama-speculative-simple (2025), GitHub ggml-org/llama.cpp, https://github.com/ggml-org/llama.cpp/issues/12968

[10] llama.cpp issue #23752, MTP speculative decoding degrades throughput on Metal (Apple Silicon): net loss at every configuration (2026), GitHub ggml-org/llama.cpp, https://github.com/ggml-org/llama.cpp/issues/23752

From eliminating low-value tasks to accelerating high-impact projects, here’s how AI is reshaping the data science workflow

Building a Logistic Regression Model to Predict Which Colleges Expect an Early Career Salary of $60,000 or More

March 5, 20216 min read

Learn how to automate prompt engineering and unlock significant performance improvements in your LLM workload

September 4, 202422 min read

The real challenge in building reliable AI

Hierarchical attention is faster

October 7, 20236 min read

Why learn 8 scripts when you can learn 256 bytes?

April 26, 202611 min read

Set up and run the GPQA-Diamond benchmark on DeepSeek-R1's distilled models locally to evaluate its reasoning capabilities.

April 23, 20253 min read

Two copies of one small AI model keep a remote machine in sync with the cloud, with no constant streaming. A beginner-friendly world model tutorial in PyTorch.

October 6, 202617 min read

AI does not decide who gets fired. Companies do.

原文为英文,正文由自动抓取并保留原文。

本文由采集器自动同步

原文发布于 Towards Data Science(Speculative Decoding Makes Tool Calls Faster. Agents Need a Cache.),标题、摘要与正文由机器翻译,术语按行业惯例统一,未经人工逐句校订。

阅读原文 ↗