Repository navigation
Reuse KV cache across ReAct loop iterations to eliminate prompt re-processing - #1297
Conversation
Add `cached_prompt` field to `ChatLlamaState` to track the last decoded token sequence. On each `generate_blocking` call, compute the longest common prefix between the new prompt and the cached tokens: if a prefix matches, trim the KV cache to that length with `clear_kv_cache_seq` and decode only the delta tokens. Falls back to full decode on first call, prompt divergence, or if the trim API fails. Clears the cache on context window overflow so the next call starts clean. With a 5362-token system prompt and a 5-iteration ReAct loop, this reduces prompt processing from ~26,810 tokens to ~5,362 + small deltas, bringing expected TTFT on iterations 2–5 from ~7.8s toward single-pass latency. Co-Authored-By: Claude <[email protected]>
Code Review SummaryThis is a well-targeted, self-contained change that correctly implements KV cache prefix reuse for the ReAct loop. The core idea — track the last decoded token sequence, find the longest common prefix with the new prompt, trim the KV cache to that prefix boundary, and decode only the delta — is sound and the implementation is clean. The borrow-checker comment explaining why the prefix length is computed before the mutable borrow of All five acceptance criteria from issue #1288 are satisfied: the system prompt is decoded once per session, subsequent iterations process only the delta, context overflow resets the cache, the fallback to full decode on trim failure keeps KV/batch state consistent, and the existing behavior (full clear, full decode) is preserved as the first-call path. One Improvement issue with the FindingsSuggested Improvements
The call is: ctx.clear_kv_cache_seq(Some(0), Some(prefix_len as u32), None)Per the llama-cpp-2 API ( However, If Recommended fix: match ctx.clear_kv_cache_seq(Some(0), Some(prefix_len as u32), None) {
Ok(true) => prefix_len,
Ok(false) => {
// Partial trim not supported by this backend; fall back to full decode.
tracing::warn!("KV cache partial trim returned false, falling back to full decode");
ctx.clear_kv_cache();
0
}
Err(e) => {
tracing::warn!("KV cache trim failed ({}), falling back to full decode", e);
ctx.clear_kv_cache();
0
}
}In practice, with llama.cpp's attention-based backends (Metal, CUDA, CPU) the partial trim always returns
Before this PR, The sampler index passed to That said, an inline comment at line 413 explicitly stating "index is batch-relative, always the last entry regardless of decode_from" would prevent a future reader from second-guessing it. Nitpicks
Requirements Validation (issue #1288)
Verdict: Approve with the |
malibio
left a comment
There was a problem hiding this comment.
Review posted as comment above. Verdict: approve — net positive change. One improvement recommended (check the bool from clear_kv_cache_seq for partial-trim failure) before the next evolution of this code.
The inner bool returned by clear_kv_cache_seq is the llama.cpp-level return from llama_memory_seq_rm, which returns false when a partial sequence removal is not supported by the backend (e.g. recurrent models). Discarding it with Ok(_) would leave stale tail entries in the KV cache while decoding only the delta, producing incorrect logits. Treat Ok(false) the same as Err: emit a warn log and fall back to full decode so KV cache and batch are always in sync. Co-Authored-By: Claude <[email protected]>
Address Review SummaryAddressed: 1 recommendation ✅ Handled
|
…ocessing (#1297) * Reuse KV cache across ReAct loop iterations (closes #1288) Add `cached_prompt` field to `ChatLlamaState` to track the last decoded token sequence. On each `generate_blocking` call, compute the longest common prefix between the new prompt and the cached tokens: if a prefix matches, trim the KV cache to that length with `clear_kv_cache_seq` and decode only the delta tokens. Falls back to full decode on first call, prompt divergence, or if the trim API fails. Clears the cache on context window overflow so the next call starts clean. With a 5362-token system prompt and a 5-iteration ReAct loop, this reduces prompt processing from ~26,810 tokens to ~5,362 + small deltas, bringing expected TTFT on iterations 2–5 from ~7.8s toward single-pass latency. Co-Authored-By: Claude <[email protected]> * Address review: handle Ok(false) from clear_kv_cache_seq The inner bool returned by clear_kv_cache_seq is the llama.cpp-level return from llama_memory_seq_rm, which returns false when a partial sequence removal is not supported by the backend (e.g. recurrent models). Discarding it with Ok(_) would leave stale tail entries in the KV cache while decoding only the delta, producing incorrect logits. Treat Ok(false) the same as Err: emit a warn log and fall back to full decode so KV cache and batch are always in sync. Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
Closes #1288