Skip to content

Avoid replaying static chat prompt state - #367

Closed
aleroot wants to merge 1 commit into
ml-explore:mainfrom
aleroot:static_repeated_prompt
Closed

aleroot wants to merge 1 commit into
ml-explore:mainfrom
aleroot:static_repeated_prompt

Conversation

@aleroot

@aleroot aleroot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

Avoid replaying static prompt material in long-lived ChatSession instances.

ChatSession now renders session instructions and prompt tool schemas only when the KV cache is first built, or after clear(). Later turns append only incremental messages/tool results, while parser tool schemas remain available for tool-call parsing.

Why

For chatbots and agents, static instructions are already represented in the KV cache after the first turn. Re-rendering them on every response wastes context and prefill work. For agents, repeated tool schemas can be especially expensive.

The existing tools: API remains source-compatible. A grouped ToolConfiguration supports advanced prompt/parser schema separation without expanding every initializer.

Notes

clear() resets the session cache, so the next response rebuilds the static prefix. Apps that change instructions mid-session should call clear() or create a new session.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

@davidkoski

Copy link
Copy Markdown
Member

Is this the correct behavior? I agree it is represented in the KVCache, but consider this from mlx-lm:

            if args.system_prompt is not None:
                messages.append({"role": "system", "content": args.system_prompt})
            messages.append({"role": "user", "content": query})
            prompt = tokenizer.apply_chat_template(
                messages,
                add_generation_prompt=True,
            )
            last_response = None
            for response in stream_generate(...

That is inside the loop and it always injects the system prompt -- my understanding was this is what was expected. Gemini was a little wishy washy on answering :-)

@aleroot

aleroot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor Author

Is this the correct behavior? I agree it is represented in the KVCache, but consider this from mlx-lm:

            if args.system_prompt is not None:
                messages.append({"role": "system", "content": args.system_prompt})
            messages.append({"role": "user", "content": query})
            prompt = tokenizer.apply_chat_template(
                messages,
                add_generation_prompt=True,
            )
            last_response = None
            for response in stream_generate(...

That is inside the loop and it always injects the system prompt -- my understanding was this is what was expected. Gemini was a little wishy washy on answering :-)

Good catch. The mlx_lm.chat loop does indeed add the system prompt every turn. Because it reuses the same prompt cache and stream_generate performs no prefix comparison, those tokens are physically appended again; the cache does not deduplicate them.
After checking the broader implementation, I do not think that CLI behavior is a sufficient generic contract. mlx_lm.server instead renders the complete conversation, finds the exact cached token prefix, and sends only the remaining suffix.
My goal to avoid duplicate prefill is still fine, but the current “omit instructions/tools after the first turn” implementation is too broad. Real templates can emit BOS or a default system message for an isolated user message, and swift-transformers can switch from tool_use to the default template when tools becomes nil.
I’m going to revise this around exact full-prompt token-prefix reuse rather than treating static material as a one-time rendering operation. The system/tools should remain part of every canonical logical render; only their already-cached tokens should be skipped during prefill. I will update this later today ideally.

@aleroot
aleroot force-pushed the static_repeated_prompt branch 7 times, most recently from 9808efe to ebf2f84 Compare June 24, 2026 12:12
@aleroot

aleroot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor Author

@davidkoski my initial approach here was a bit optimistic 🙂, in fact simplistic.

I have now reworked the solution around exact token-prefix reuse rather than omitting static prompt after the first turn. The session still renders the canonical full prompt with instructions and prompt-side tool schemas, then verifies that the static-only render is an exact token prefix of that full prompt. On the first turn we prefill the full prompt and remember that reusable prefix; on later turns, if the prompt configuration is unchanged and the KV cache is safe to reuse, we pass only the suffix tokens that are not already represented in the cache.

So the behavior should now match the right semantic model: instructions/tools remain part of every canonical prompt render, but already-cached static prefix tokens are not replayed through the model. This should improve performances when using the library from a coding agent.

When eventually #360 will be merged, this can be improved further.

@aleroot

aleroot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor Author

I am still working on some issues, I will update this PR further and add some more comments.

Render the canonical static+turn prompt fragment and store the proven static token prefix with the KV cache state. Subsequent turns prefill only the suffix of the full render when that prefix still matches, preserving the performance win without relying on role/template assumptions.

Treat restored external caches as unknown prompt state and throw on prefix mismatch instead of appending incompatible tokens to an existing KV cache.

Add model-prefill tests that prove suffix-only evaluation, avoid standalone dynamic-template regressions, and cover cache mismatch after prompt-affecting changes.
@aleroot
aleroot force-pushed the static_repeated_prompt branch from ebf2f84 to a83868f Compare June 24, 2026 13:06
@aleroot aleroot closed this Jun 24, 2026
@aleroot
aleroot deleted the static_repeated_prompt branch June 24, 2026 19:59
@aleroot aleroot mentioned this pull request Jun 25, 2026
4 tasks done
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…ped-nax-20261026

Optimize guarded Gemma4 NAX prefill with token-row mapping
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…donate

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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