Skip to content

Reuse a per-session context across chat exchanges - #223

Merged
mattt merged 1 commit into
mainfrom
llama-session-context
Sep 10, 2026
Merged

mattt merged 1 commit into
mainfrom
llama-session-context

Conversation

@mattt

@mattt mattt commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator

@james-333i's #215, cherry-picked onto main with his authorship intact. GitHub couldn't squash #215 after #213 and #214 landed because it rewrites lines those PRs added, so this PR carries the same commit on a branch based on the current main.

Original description and review discussion: #215.

Every generation created a fresh llama_context and prefilled the full
rendered conversation from token zero, so multi-turn chat cost grew
with the square of the transcript and long conversations spent most of
their time re-decoding history.

Keep one context alive per session for plain chat generations. Each
exchange tokenizes the rendered prompt, keeps the longest token prefix
shared with the context's recorded state, removes diverged state with
llama_memory_seq_rm, and decodes only the remainder. Backends that
cannot rewind, such as recurrent models, fall back to clearing memory
and decoding the full prompt, and appends need no rewind on any
backend. The final prompt token is always re-decoded so sampling has
fresh logits, generated tokens extend the recorded state as they
decode, and any generation error discards the cached context.

Structured generation, image prompts, and encoder models keep
single-use contexts, and clearCachedContext lets consumers free the
cached state under memory pressure.

Adds a live test asserting prefix reuse on the second turn of a
session.

(cherry picked from commit 49a2acf)
@mattt
mattt merged commit b6020ee into main Sep 10, 2026
11 checks passed
@mattt
mattt deleted the llama-session-context branch September 10, 2026 14:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants