Skip to content

studio: KV preemption by slot checkpointing, an experiment beside #10301 - #10346

Draft
danielhanchen wants to merge 6 commits into
mainfrom
feat/kv-preemption-v2
Draft

danielhanchen wants to merge 6 commits into
mainfrom
feat/kv-preemption-v2

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

An experiment, opened as a draft so it can be tested beside #10301 and not as a candidate to replace it. It keeps preemption in Studio but pauses a chat by checkpointing its llama-server slot (POST /slots/{id}?action=save, then erase) and resumes it by restore plus a request whose prompt has the saved sequence as a proper prefix, so the whole sequence is reused from the cache and one token is recomputed. #10301 resumes by re-prefilling the partial instead.

New module studio/backend/core/inference/kv_swap.py (the controller, the slot-file header parser, the resume-rule guard, every fallback) with 44 unit tests, wired to the GGUF tool loop at its round boundaries. Rollout switch UNSLOTH_LLAMA_KV_SWAP, default on.

What was measured first

On the bundled llama-server build (b10715), before anything was built on it:

  • Slot save, erase and restore work under --kv-unified, and restore accepts any free slot id, not only the one saved from.
  • A resume hits the restored cells only when the saved sequence is a proper prefix of the new prompt. Exactly the same tokens re-prefills; there is no prefix-truncation reuse in this build. Every design decision below follows from this rule.
  • A generation that ends cleanly leaves the caller holding exactly the cached tokens plus one, which satisfies the rule for free. An aborted stream leaves the cache 4 to 5 tokens ahead of what the client saw, the in-flight speculative batch, and draining the socket does not close that gap. So a pause in the middle of a generation cannot be resumed without recompute; only a request boundary can.
  • Exactness: with speculation off, one request, the same text split into two requests, and save-erase-restore-resume are byte-identical in 10 of 10 variants. With the MTP head on, the swap adds no divergence of its own, but the request boundary itself diverges deterministically. That applies equally to the re-prefill resume in studio: KV preemption so parallel chats share one cache, with llama-server owning the parking #10301.
  • Chunk-boundary cost when a generation is split: 0.72 percent at 1024 tokens, 0.86 percent at 512, 3.41 percent at 256.

Results

Qwen3.5-4B UD-Q4_K_XL with its MTP head, Studio at -c 8192 with four slots, on a GPU shared with another tenant (raw llama-server 33 tok/s at the time against 296 tok/s on the same GPU earlier in the day, so only the on/off pairs are comparable, not the absolute rates).

Through Studio on a 2322-token conversation (123 MiB checkpoint): save 39.1 ms, erase 9.3 ms, restore 25.0 ms, and the resume reports cache_n 2322, prompt_n 1. Checkpoints are 123 to 321 MiB and write at 3.3 GB/s to disk.

run completed wall aggregate tok/s first token mean / max pauses errors
solo, swap on 1 of 1 35.3 s 34.0 0.72 s 0 0
solo, swap off 1 of 1 35.0 s 34.3 0.39 s 0 0
four chats, swap on 4 of 4 77.3 s 62.1 21.1 s / 42.1 s 0 0
four chats, swap off 4 of 4 79.9 s 60.1 21.1 s / 42.0 s 0 0

A run containing one real swap is byte-identical to the same run without one, and to a repeat of the baseline (scripts/v2_exactness.py). Arming costs nothing.

Four browser chats through Playwright: 4 of 4 finished, 3 error boxes, 6 speculative sub-batch errors, 0 swaps.

Why it is not the shipping design

Coverage. The swap can only fire at request boundaries, which in this integration are the tool-round boundaries, and Studio chats spend most of their time inside one long generation. Under real pressure the swap does not fire and the chats reach the cache limit the old way, which is what the browser run shows and what #10301 prevents.

Three integration bugs were found and fixed on the way, each with its measurement: the resume wait asked whether the whole queue fit rather than the one chat; a slot emptied by --cache-idle-slots at a round boundary was read as a failed swap; and no lifecycle end, which left finished chats resident at 14134 of 8192 cells and produced a run with 120 pauses and no successful resume.

What to take from it

The mechanism, not the integration. Slot checkpointing beats re-prefill by a margin that grows with conversation length (25 ms flat against 0.8 to 8.4 s), and it is exact. It needs a chunked generation driver, bounding max_tokens per upstream request at about 512 when more than one chat is active, so that pauses land on clean request boundaries; the pressure check then moves to the chunk boundary. Until that driver exists #10301 covers strictly more cases.

Relation to the other branches

#10301 is the Studio-side design that ships. unslothai/llama.cpp#184, #185 and #186 move the pause into the server, where a token boundary is always clean and the in-flight draft is not a problem; with one of those merged into Studio's bundled build, this module's checkpointing becomes unnecessary.

danielhanchen and others added 6 commits September 5, 2026 06:22
Adds core/inference/kv_swap.py, which moves a chat's KV out of the shared cache
with llama-server's slot state API instead of letting the newest chat fail with
'Context size has been exceeded'. One chat keeps decoding; the others have their
cells saved and erased, and read back when there is room.

The shape follows four measured properties of llama-server b10715:

  - restore accepts any free slot id, not only the one the save came from;
  - a resume prompt lands on the restored cells only if the saved sequence is a
    PROPER prefix of it. Exactly N tokens re-prefills just as a mismatch does,
    so resume_prompt_is_valid() rejects equal length as well as short;
  - a generation that ends cleanly leaves the caller holding exactly KV+1
    tokens, which is the only shape that satisfies the rule for free;
  - an aborted stream leaves the KV 4-5 tokens ahead of the caller, so a
    mid-generation preemption cannot resume without recompute and falls back.

Save happens before erase and the erase is skipped unless the save reported
tokens, so a failed checkpoint costs recompute and never content.

Buffer defaults to n_parallel * (draft_n_max + 3), covering the in-flight
speculative lead on every slot at once.

39 unit tests over the header parser, the resume rule, the policy, the
accounting, both swap moves and the fallback path.
…aries

generate_chat_completion and generate_chat_completion_with_tools take an
id_slot, appended never inserted, and put it in all three payload builders.
Without a pin llama-server picks a slot by LRU and a checkpoint has nothing to
name. The value may be a callable, because the OpenAI route builds its generator
before admission grants a slot; _resolve_id_slot reads it on the first round and
treats a raising callable as no pin, so an unpinned run still generates.

LlamaCppBackend.kv_swap_controller() wires a controller to the live geometry
(shared context, slot count, draft depth) and rebinds the transport each call so
a reload cannot leave a stale auth header. read_slots_snapshot() gives the
ledger llama-server's own view, which differs from the stream by the in-flight
speculative batch.

The route drives the swap from _gguf_recost, the hook that already runs at the
top of every tool round. That boundary is the one place a checkpoint is free:
the previous request completed, so the next round's prompt is the saved sequence
plus the tool result, which is the proper extension a resume needs to land on
restored cells. Mid-round the KV runs ahead of us and the swap is skipped.

A swapped-out chat blocks on the executor thread where recost_waiting already
waits, and the stream wrapper sends ': preempt-paused' in place of the keep-alive
so the UI shows 'Paused while another chat finishes' rather than a stall.
Every failure path falls back to plain admission; none of them error.
can_resume(): a paused chat waited on plan().victims being empty, which is the
whole queue fitting, not itself. Every resume in the first 4-chat run therefore
sat out the full timeout (waited=300.1s) even when room had come back. It now
asks only whether it fits alongside what is currently resident.

KvSwapNothingToSave: llama-server clears an idle slot into its own prompt cache
when --cache-idle-slots is on under a unified KV, which is the default, so a
slot is often empty at a round boundary. That was being treated as a failed
swap and the chat was paused waiting for room it was not using. It is now a
distinct signal and the round simply continues.

A timed-out wait used to attempt the restore anyway and got 'Unable to restore
slot: No available space in KV cache', losing the checkpoint to an error. It now
drops the checkpoint deliberately and re-prefills, which always works.

Wait ceiling 300s -> 900s: waiting for another chat to finish is the intended
behaviour here and these chats run for minutes.
The ledger had no lifecycle end. Nothing called finish(), so every completed
chat stayed counted as resident, the running total climbed with every request,
and once it passed the context every chat became a victim at its first round
while no wait could ever be satisfied. A four-chat run measured resident 14134
against an 8192 pool, 120 pauses for 4800 generated tokens, first token at 462 s
mean, and not one successful resume: all seven swaps timed out and re-prefilled.

The stream teardown now drops the chat, reconcile() zeroes a chat whose slot the
server reports as released rather than leaving a stale size behind, and a
readout larger than the whole pool is clamped so one bad sample cannot poison
the ledger. Wait ceiling back to 300s now that waits can end.

For the record, on this model a checkpoint is 130 to 321 MB and restores in 31
to 70 ms, against about 8.4 s to re-prefill the same 3558 tokens at 423 tok/s.
…est knob

Pinning overrides llama-server's own slot choice, so with UNSLOTH_LLAMA_KV_SWAP=0
the request now goes out exactly as it did before and the off arm is a real
control rather than a differently-pinned variant.

UNSLOTH_LLAMA_KV_SWAP_EVERY forces a swap at every round boundary whatever the
pressure, so the checkpoint path can be exercised and timed on a machine that is
not short of cache. A forced swap does not wait for room it does not need.

Measured live through Studio on a 2322-token conversation, 123 MiB checkpoint:
save 39.1 ms, erase 9.3 ms, restore 25.0 ms, and the resume comes back
cache_n=2322 prompt_n=1, so the whole sequence is reused and exactly one token
is recomputed.
shimmyshimmer added a commit that referenced this pull request Oct 23, 2026
## Summary

Removes 22 image files that nothing in the repo loads, on any surface:
the Studio web UI, the Desktop app (macOS, Windows, Linux), the
installers, Docker and the wheel. No user-visible change.

All but `react.svg` ship today: Vite copies `public/` into
`frontend/dist/`, which goes into the wheel, the Desktop bundles and the
Docker images. Against the published `unsloth-2026.10.7` wheel (30.95
MB) this takes 2.40 MB off the download.

Removed:

- `studio/frontend/public/Sloth emojis/`: 16 stickers that are not in
the profile avatar list (`sloth-avatars.ts`), the chat greeting, the
login or 404 screens, or the JupyterLab sticker list in
`docker/jupyter/install_sloth_stickers.py`:
`241024 Sloth Drink Jus.png`, `251008 Sloth Pin.png`, `FO2C6766BA42
Sloth Gift.png`, `FO71A40FA5581 Sloth and Llama.png`, `Sloth w Gameboy
Confetti no Logo.png`, `Sloth w PC Confetti no Logo.png`, `Sloth w PC no
Logo.png`, `UnSloth Eat GPU Mouth.png`, `UnSloth Eat GPU.png`, `UnSloth
Laptop.png`, `large sloth laugh.png`, `sloth huglove large33.png`,
`sloth pc emoji.png`, `sloth rounded.png`, `sloth w pc transparent.png`,
`sloth with gameboy.png`
- `studio/frontend/public/hub/profile/logo/Qwen.svg`: the Hub uses
`qwen.png` for Qwen
- `studio/frontend/public/provider-logos/misc/perplexity.png`
- `studio/frontend/public/logotext.png`
- `studio/frontend/public/vite.svg` and
`studio/frontend/src/assets/react.svg`: Vite template leftovers; the
favicon is `favicon.png`
- `studio/src-tauri/icons/tray-icon.png`: the 18 px tray icon. The tray
embeds `[email protected]` on macOS, `tray-icon-color.png` on Windows and
Linux, and `tray-icon-dark.png` / `tray-icon-light.png` for the macOS
appearance switch; `include_image!` takes an exact path, so the 1x file
was never picked up

## How unused was established

- Every tracked file was searched for each asset's file name, raw and
URL-encoded, with word boundaries so `Hellix-SemiBold.woff` does not
count as a hit for `.woff2`. That covers the frontend, backend,
`tauri*.conf.json` (base, macOS, Linux, Windows), NSIS / AppImage / dmg
packaging, `install.sh`, `install.ps1`, Dockerfiles, workflows,
`pyproject.toml` and `MANIFEST.in`.
- Checked for paths built at runtime (template literals over `public/`
folders, `import.meta.glob`, directory listings): none reach these
files.
- Saved profile avatars: the avatar picker list has never offered any of
the removed stickers (full `git log -p` of `sloth-avatars.ts`), so no
stored `avatarDataUrl` can point at one.
- Open PRs: grepped the heads of all open same-repo PRs. The only hits
(`sloth w pc transparent.png` in #10346, `sloth rounded.png` in #5108)
are old main code those branches inherited from their merge base;
neither PR touches `studio/frontend`, and main already dropped both
usages (#12804 removed the Canvas surface).
- Other unslothai repos: GitHub code search for each name returns
nothing.

## Deliberately kept

- `images/`: about 20 of its files are not referenced in this repo, but
the folder is hotlinked from outside it. The notebooks repo links
`Merge.png`, `Assistant.png`, `Terminal_Type.png`, `Where_Terminal.png`,
`start free finetune button.png` and `Documentation Button.png`; Hugging
Face model cards link `buy me a coffee button.png` (88 of 737 sampled
unsloth cards), among others; older READMEs still shown on PyPI release
pages link the rest. Removing any of them would break those pages.

## Verification

- `studio/frontend`: `npm run typecheck` clean, `npm test` 13730 passed
/ 0 failed, `npm run build` clean; the built `dist/` references none of
the removed names. `npm run biome:check` errors are the existing ones on
main (non-blocking in CI) and biome does not read image files.
- `tests/studio/test_pwa_manifest.py`,
`tests/test_installer_shortcut_icons.py`,
`tests/studio/install/test_package_discovery.py`: 19 passed, 2 skipped.
- Staging CI across macOS / Windows / Linux with the Playwright leg
(link below once green).

Not run from this host: a Desktop build. The Tauri bundle config and the
tray `include_image!` paths do not reference the removed files.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant