Repository navigation
[Feature] AMD NPU: auto compaction for NPU chats instead of stopping at a full context window - #17616
Conversation
…e NPU compaction fit [skip ci]
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
… a catalogued search_conversation [skip ci]
…h_conversation is absent, compaction in collected replies [skip ci]
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
# Conflicts: # studio/backend/routes/inference.py
…t reset [skip ci]
…ven when it evicts nothing [skip ci]
…o the user turn [skip ci]
…e-prompts keep the recall
… into the user turn [skip ci]
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Resolve against the NPU auto compaction (#17616): managed engines keep main's checkpoint fit for /compact epochs, cloud connections keep the summary fit.
…urns (unslothai#17743) ## What changes for users A long chat on a cloud connection is now summarized instead of losing its oldest turns. Until now, a connection whose provider does not compact server-side (every chat-completions connection: OpenRouter, DeepSeek, Mistral, Gemini, vLLM, SGLang, llama-server, Ollama and the rest, including Claude reached through a gateway) dropped its oldest turns once the chat passed 75% of the model's window. The thread showed "Older messages were dropped from the model's context to make room", and the dropped turns were archived and recalled inline when a later turn asked about them, but nothing carried the gist of the dropped part forward. - **Summary instead of eviction.** When a request would pass the threshold, Studio asks the same connection and model for a structured summary of the older turns, keeps the recent turns verbatim (up to 15,000 tokens or 30% of the prompt budget) and sends summary plus tail. The system prompt and pinned instructions are kept as before. The full transcript stays in the thread. - **The summary is a turn, not part of the system prompt.** It is written from chat and tool text, so it goes in as a user turn (with a short acknowledgement so strict chat templates keep alternating) instead of gaining system-prompt authority, and the evicting fit never drops it. The summary request also tells the model to leave instructions found in pages, documents and tool results out of the summary: live, an 8B model that had copied a fetched page's "system notice" into its summary and then obeyed it no longer does. - **Summary plus recall.** The summarized turns are archived as before, and on every turn that runs on a summary the existing conversation recall adds the exact passages the newest turn asks about, inside the existing recall budget. The summary gives continuity, recall gives the exact wording. - **The summary is saved per thread** and reused on later turns, so a chat is summarized once per compaction, not on every message. An edited or branched history gets its own summary. - **Fallback.** If the summary call fails, the previous behaviour (dropping the oldest turns, with recall) runs, so a chat never fails because of it. - **`/compact` works on a cloud model.** Anthropic and OpenAI (Responses) compact server-side, so `/compact` lowers their native trigger for that request. Everything else uses the summary call. - **"Auto-compact after"** in the connection form, in tokens, stored with the connection. It replaces the 75% default and can raise the trigger past the 200K default cap on server-side compaction, up to the model's window (neither vendor documents an upper limit, only Anthropic's 50K floor). Blank keeps today's defaults. - **Overflow recovery.** If a provider refuses a request as too long before any output, Studio compacts once and resends. A second refusal is shown as the error. This is off when auto-compact is off. - **It is visible.** The context meter shows a cloud model's window with a tick where the chat compacts, and the tooltip names the trigger. The thread shows "Earlier messages summarized" or "Older messages dropped" with a matching toast, and a progress state while the summary is written. - **Compact chip.** On a cloud thread over 50,000 tokens that has been idle past the provider's prompt cache lifetime, a Compact chip appears next to send. With auto-compaction on it starts on, and the next message is sent after a summary; one click keeps the full history for that message. With auto-compaction off it starts off, and only a click queues the summary. - **Coding agents get the window of a hosted connection, and use more of it.** `unsloth start` asks Studio for the window it passes to Claude Code, Codex and opencode. Hosted Anthropic and OpenRouter connections used to answer nothing, so the agents fell back to their own defaults (Claude Code assumes 200K for an ID it does not know). Studio now reads the window from the provider's model listing (Anthropic `max_input_tokens`, Gemini `inputTokenLimit`, OpenRouter `context_length` floored at its default route), under the same saved-key gate as the chat path, and from the daily models.dev catalog Studio already caches for providers whose listing has none (OpenAI), preferring its prompt cap where that is lower. Claude Code launched by `unsloth start` keeps 10% headroom only up to 32K tokens, so a 1M window compacts at 96% instead of 90%. Local GGUF, MLX and managed engines (including the NPU checkpoint compaction from unslothai#17616) are unchanged. ## Which path each connection takes | Connection | Auto-compact | | --- | --- | | Anthropic (direct, models with server compaction) | Server-side, `compact_20260112` edit | | OpenAI (direct, Responses) | Server-side, `context_management` compaction | | Every other chat connection, including Claude through OpenRouter or another gateway | Unsloth summary plus recall | | vLLM, SGLang, llama-server with no catalogued window | Unsloth summary plus recall, trigger at 75% of the window the server reports (`max_model_len`, `meta.n_ctx`) | ## Things a reviewer should know - The first compaction on a thread adds one extra model call before the reply, billed on the same connection. A backlog too long for one call is folded in over several calls, eight at most. - A saved summary keeps applying to its thread, including after auto-compact is switched off, the same way a manual compaction of a local chat does. - Cloud models now show `used / window` with the ring in the chat header where the catalogue has a window. Before, they showed a bare token count. - New storage: table `chat_thread_summaries` in the chat database (removed with its thread) and a nullable `auto_compact_tokens` column on saved connections. Both are created on first use and older builds ignore them. - New request fields: `compaction_uncapped`, and `compact_context` is now honoured for cloud connections. - Merged with main: managed engines keep the checkpoint fit unslothai#17616 added for `/compact` epochs; cloud connections take the summary fit. ## How it was checked - Backend: `tests/test_cloud_summary_compaction.py` covers the summary fit, reuse of a saved summary, the fallback to eviction, recall alongside a fresh and a reused summary, `/compact` on a cloud model including the native path, the connection setting and its clamps, the overflow retry with and without tools (refitted from the transcript, so a summarized thread folds its saved summary in rather than stacking a second one), archiving of summarized turns when more turns must also be dropped, every registered chat connection without server compaction, Claude through OpenRouter, and vLLM / SGLang / llama-server reached without a catalogued window. `tests/test_connection_catalog_window.py` covers the window reported to agents. The NPU, compaction, provider and tool transport test files pass with it. - Frontend: `tests/cloud-compaction.test.ts` plus the updated compaction tests. `npm run typecheck` and `npm test` pass. - Live against OpenRouter with the trigger set low: a 16.8K-token chat with a fact stated in its first turn was summarized by Unsloth to a few hundred tokens and both `anthropic/claude-haiku-5.5` and `meta-llama/llama-3.1-8b-instruct` still answered with the fact. The window lookup returned 1,000,000, 1,047,576 and 131,072 for three listed models. ## Not testable here - Server-side compaction on direct Anthropic and OpenAI (the `/compact` trigger and the raised cap) is covered by request-body tests only. No keys for those were available. - Recall in a live chat (it needs the embedding model); it is covered by tests with stub embeddings. - CPU-only machine: nothing here touches training or local inference. ## Screenshot Settings > Connections, new OpenRouter connection: the "Auto-compact after" field (left: main, right: this PR).  --------- Co-authored-by: Daniel Han <[email protected]>
An NPU chat (FastFlowLM through Lemonade) never compacted. The chat adapter only sent
context_overflowfor GGUF, MLX and managed vLLM/SGLang models, and the NPU route forwarded the whole history to lemond with nothing to fit against. Lemonade has no compaction of its own, so a long chat ran until FastFlowLM's KV cache filled and the user got the "filled the model's context window" error.Fix
_npu_chat_completionssetscontext_windowandcompaction_thresholdfrom the loaded NPU context length (same 25% headroom as managed engines) whenever the request asks fortruncate_oldest, so the existing external fit trims the chat before it reaches lemond._fit_external_contexttakescan_reset, which the proxy sets for the NPU's tool loop:/compactstarts a checkpoint epoch on a chat that still fits, and later turns replay it, as on GGUF. Other external providers are unchanged.ggufCompactionRequestFieldstakesisNpu, both chat-adapter call sites pass it, and/compact(composer and chat menu) accepts a tool-capable NPU model.context_overflow: "error", so the whole chat goes through and the context-full message still shows.On a real NPU
qwen3.5:4b loaded with a 2048-token context, six turns of ~550 tokens each.
AMD DevLab Strix Halo (Ryzen AI Max+ 395, XDNA 2 NPU, Ubuntu 24.04, kernel 6.17.0-1033-oem), run 43275229990, on the NPU run-settings group build with this change cherry-picked (
bab6c25vsfeaf63a), not this branch alone. Not run on Windows.Tests (red on
3de707fc81, green here)test_npu_chat_route.py: an over-window chat is compacted before lemond sees it (stream and non-stream), auto compact off / no policy forwards it whole, a chat that fits is untouched,/compactresets a fitting chat.auto-compaction-settings.test.ts,manual-compaction.test.ts: NPU gets the compaction fields,/compactqueues for an NPU model.npx tsc -b.This branch alone on a real NPU, base vs head
AMD DevLab Strix Halo (XDNA 2 NPU, Ubuntu 24.04), qwen3.5:4b loaded with a 4096-token context, ten turns of about 300 tokens each, Search and Tools on. Merge base
3de707fvs this branch (b4b36ca).Base: "Max length reached!" from turn 8 on, ~4.2k / 4.1k. Head: every turn answers, "Context compacted" divider, 2.2k / 4.1k;
/compactafterwards adds a second divider.API differential on the same hardware (Linux and Windows 11, gfx1151 boxes, 2048-token window): an over-window chat with auto compact on returns 400 "Max length reached!" on base and a reply on head after dropping 8 messages (3341 to 1137 tokens); auto compact off still refuses on both.