Skip to content

server : share prompt prefix cells between slots (--slot-attach) - #30970

Open
rochaudhari wants to merge 1 commit into
ggml-org:masterfrom
rochaudhari:prefix-sharing
Open

rochaudhari wants to merge 1 commit into
ggml-org:masterfrom
rochaudhari:prefix-sharing

Conversation

@rochaudhari

@rochaudhari rochaudhari commented Oct 22, 2026 •

Copy link
Copy Markdown

Overview

A new session has following limitations which reusing prefix that another slot holds:

  1. It cannot use cells from a slot that is busy, which is the concurrent-session case,
  2. Two sessions cannot share one copy; each slot that has the prefix keeps its own copy in the KV cache.

With Unified KV cache + this PR, a new request can also start from the cells of another slot that holds the same prefix. Prefix is neither copied or computed.

Recurrent and hybrid models can only resume at a checkpoint, so they attach at a checkpoint of the other slot. To make this useful, the server also creates a checkpoint where a prompt diverges from a known prompt, at least 1,024 tokens in, so later prompts can attach up to that point.

Attach is on by default, and --no-slot-attach turns it off. It also turns itself off where it cannot work, for example without a unified KV cache or with sliding-window models.

Additional information

Original discussion: #30664

Behaviour

  • When a slot attaches: when another slot's cells cover at least as many prompt tokens as the slot's own cells, or a copy from the RAM prompt cache. On a tie it attaches, so the prefix is held once instead of twice.
  • Shortest attach: 256 tokens. For hybrid models, this is measured at the checkpoint position, not the length of the shared prefix.
  • Turns itself off with:
    • a KV cache that isn't unified;
    • memory that can't share cells (for example sliding-window attention), and DeepSeek V4;
    • a multimodal projector, speculative decoding or LoRA adapters;
    • --context-shift, or --cache-reuse when it's active.
  • --cache-reuse: takes priority over attach. The --fim-qwen-* presets set --cache-reuse 256, so attach is off for them. Hybrid and recurrent models turn cache reuse off at load, so attach stays on for them.
  • n_cache_reuse in a request: ignored while attach is on, logged once at info level and then at debug level. Master honours it, so clients that rely on it need the server started with --no-slot-attach.
  • Startup log:
    • one info line when attach turns itself off;
    • a warning instead, if --slot-attach was given explicitly;
    • nothing for --no-slot-attach.
  • Purge order when the KV cache is full: idle slots whose cells no other slot holds are purged first, because purging a slot whose cells are shared frees little. Master purges the idle slot with the lowest id first.
  • Metrics: slot_attach_total, slot_attach_tokens_total and slot_attach_checkpoints_total.
  • attach is turned off for spec dec.
  • If server is launched with multimodal, if request contains media it will not attach feature. For text only prompts, attach will work.

Supported memory types

Attach gives the same output as same-slot reuse on each of these:

  • Plain KV cache (llama_kv_cache), for example qwen3: largest difference 2.4e-6.
  • Hybrid (llama_memory_hybrid), for example qwen3next, Qwen3.5 and Qwen3.6: 0 on CPU, and 1.5e-5 on GPU, which is GPU noise (see below).
  • Recurrent (llama_memory_recurrent), for example mamba, mamba2 and RWKV: 0. RWKV wasn't run, but it uses the same memory type as Mamba.
  • Hybrid with indexer (llama_memory_hybrid_idx), for example glm5-next and qwen4exp: 0.
  • DSA (llama_kv_cache_dsa), for example deepseek32, glm-dsa and hy_v4: 0.
  • MSA (llama_kv_cache_msa), for example minimax-m3: 0.

Not supported: attach turns itself off

  • Sliding-window attention (the iswa caches), for example gemma3 and dots3note: a shared cell can't be masked differently for each slot.
  • DeepSeek V4 (llama_kv_cache_dsv4): its attach gives wrong outputs, so it's excluded by architecture name until that's fixed.

Numbers

Setup: NVIDIA A40 (48 GB), CUDA 12.8, q8_0 KV, 4 slots with unified KV, 3 concurrent sessions, MTP off. Prompts use Hermes's real tools and system prompt; the project context, skills and memory parts are synthetic. The shared prefix is 14.1K tokens. Times are the mean of 3 runs. The KV cell counts come from one separate run.

Values are "off -> attach":

Model TTFT, session 3 Decode, 3 sessions KV cells used KV saved
Qwen3.8-27B (dense hybrid) 12.82 -> 0.53 s 60 -> 72 tok/s (+20%) 42,925 -> 14,682 66%, 0.92 GiB
Qwen3.6-35B-A3B (hybrid MoE) 3.80 -> 0.27 s 169 -> 200 tok/s (+18%) 43,480 -> 15,332 65%, 0.29 GiB
Qwen3-30B-A3B (attention only) 6.50 -> 0.13 s 95 -> 159 tok/s (+67%) 42,545 -> 14,914 65%, 1.34 GiB

A checkpoint copy on the 35B is 62.8 MiB and takes about 29 ms per attach.

Tests

  • 4 test functions, 9 cases, in tools/server/tests/unit/test_completion.py.
  • utils.py gains slot_attach (unset, True or False) and n_cache_reuse.

Related and follow-ups

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: Yes. Used Claude for coding, testing and benchmarking.

@rochaudhari
rochaudhari requested review from a team as code owners October 22, 2026 09:40
@github-actions github-actions Bot added documentation Improvements or additions to documentation server labels Oct 22, 2026
Comment thread tools/server/README.md Resolved
@joelagnel

joelagnel commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Roshan, could you please squash the two patches? The second patch overwrites a lot of the first patch, so it's difficult to review both independently. I suggest making it one patch. The combined lines of code will also be lower.

Comment thread tools/server/server-context.cpp Resolved
Comment thread tools/server/server-context.cpp Resolved
@rochaudhari

rochaudhari commented Oct 28, 2026 •

Copy link
Copy Markdown
Author

@ggerganov @ngxson @angt Can you please take a look at this. Thanks!

@rochaudhari

rochaudhari commented Oct 29, 2026 •

Copy link
Copy Markdown
Author

Turning on attach for multimodal. Attach is kept only for text based prompt, any request containing media will not use attach feature. However, requests with media can act as donor.

@ORippler ORippler left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. I guess decode numbers were pre #29510 ?
  2. Should also exclude DS-V4.1. In that light, is the change generic/will we reject all llm-architectures that do not support KV cache sharing?

@rochaudhari

Copy link
Copy Markdown
Author
  1. I guess decode numbers were pre llama + CUDA: flash_attn_ext_rows (fix unified kv for multi-seq) #29510 ?
  2. Should also exclude DS-V4.1. In that light, is the change generic/will we reject all llm-architectures that do not support KV cache sharing?

@ORippler

  1. yes, decode numbers were pre llama + CUDA: flash_attn_ext_rows (fix unified kv for multi-seq) #29510.
  2. Thanks for catching this. Current change is not fully generic, and existing llama_model_n_swa() returns 0 for these models. To make the check fully generic something like llama_memory_can_share_cells() would be needed in libllama. Non generic solution would be simply add this model in current exclusion list. Changes in libllama for new function would require design consensus as well. I am thinking to go with adding this name to list and follow-up change in libllama as separate PR for new capability. Let me know your thoughts.

@slamfinger

Copy link
Copy Markdown

Following the Nov 12 thread on a possible llama_memory_can_share_cells() query, one thought: it may be useful to describe the supported memory operation more precisely than a single general “attach” capability. The PR describes shared-cell attachment for compatible KV memory, while hybrid and recurrent memories resume at checkpoints and incur checkpoint creation/copy costs. Those are distinct mechanisms; a single can_share_cells() predicate could be too coarse if it also gates checkpoint-based attachment.

There is already a memory-level capability-query precedent in llama_memory_can_shift() (include/llama.h), which dispatches to the active memory implementation. Would a similar operation-specific interface fit here—for example, separate capabilities for shared-cell attachment and checkpoint-based attachment/copy—or would a richer memory-capability descriptor be preferable?

I would still keep explicit rejection for paths known to produce incorrect output (the PR currently identifies DeepSeek V4), since a capability query should describe what an implementation supports, not substitute for correctness validation.

I’m asking only about the memory capability boundary for this PR, not proposing a client-facing fork API.

thefallentree added a commit to thefallentree/llama.cpp-gp100 that referenced this pull request Nov 14, 2026
…very

- timings.cache_reusable_n and the prometheus counter
  llamacpp:prompt_tokens_reusable_total: the prompt tokens shared with the
  cached state the slot starts from (its own tokens or the host cache entry it
  loaded), before a checkpoint restore. cache_n / cache_reusable_n is the hit
  share of what could have been reused; the rest is the distance back to the
  restored checkpoint. An INFO line per task logs both.
- --checkpoint-every N (LLAMA_ARG_CHECKPOINT_EVERY, default 0 = off): a long
  prompt also gets a context checkpoint every N tokens, so a prompt that
  diverges in its middle re-processes at most about N tokens.

Idea: mkyt docs/decisions.md P4-6 (checkpoints at message boundaries and every
~8K tokens, hit share of reusable tokens), ignis, llama.cpp ggml-org#30970.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ngxson

ngxson commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

honestly cell-sharing is quite a headache so I would avoid it at this stage. there are quite many edge cases, including recurrence memory and also KV shifting (for example, one cell shared by 2 seq but one seq decide to shift it)

in anyway, I'm working on a similar feature here. appreciate if you can take a look: #32358

@rochaudhari

rochaudhari commented Nov 16, 2026 •

Copy link
Copy Markdown
Author

honestly cell-sharing is quite a headache so I would avoid it at this stage. there are quite many edge cases, including recurrence memory and also KV shifting (for example, one cell shared by 2 seq but one seq decide to shift it)

in anyway, I'm working on a similar feature here. appreciate if you can take a look: #32358

@ngxson Agree that there are many cases need to be handled with cell sharing feature, however, my plan is to add them incrementally. Recurrent memory is already handled in this PR and this PR disables cell sharing for cell shifting case (and other cases mentioned in description).

I looked at #32358 and it looks like it is also doing cell sharing but there is difference in scope: #32358 waits for a busy slot when requests arrive together and current PR reuses a prefix that's already computed, including in idle slots.

Do you see any other edge cases which current PR and description does not cover?

@rochaudhari

Copy link
Copy Markdown
Author

Following the Nov 12 thread on a possible llama_memory_can_share_cells() query, one thought: it may be useful to describe the supported memory operation more precisely than a single general “attach” capability. The PR describes shared-cell attachment for compatible KV memory, while hybrid and recurrent memories resume at checkpoints and incur checkpoint creation/copy costs. Those are distinct mechanisms; a single can_share_cells() predicate could be too coarse if it also gates checkpoint-based attachment.

There is already a memory-level capability-query precedent in llama_memory_can_shift() (include/llama.h), which dispatches to the active memory implementation. Would a similar operation-specific interface fit here—for example, separate capabilities for shared-cell attachment and checkpoint-based attachment/copy—or would a richer memory-capability descriptor be preferable?

I would still keep explicit rejection for paths known to produce incorrect output (the PR currently identifies DeepSeek V4), since a capability query should describe what an implementation supports, not substitute for correctness validation.

I’m asking only about the memory capability boundary for this PR, not proposing a client-facing fork API.

@slamfinger Agree on keeping separate capabilities for shared-cell attachment and checkpoint based attachment. Regarding scope of this PR, I would add explicit check in current PR and capabilities check in separate PR.

If we really want to avoid broader redesign and follow existing approach, using per-operation queries might be better vs descriptor approach (it also involves struct's ABI problem), but I would let maintainers provide their take on this.

thefallentree added a commit to thefallentree/llama.cpp-gp100 that referenced this pull request Nov 17, 2026
…very

- timings.cache_reusable_n and the prometheus counter
  llamacpp:prompt_tokens_reusable_total: the prompt tokens shared with the
  cached state the slot starts from (its own tokens or the host cache entry it
  loaded), before a checkpoint restore. cache_n / cache_reusable_n is the hit
  share of what could have been reused; the rest is the distance back to the
  restored checkpoint. An INFO line per task logs both.
- --checkpoint-every N (LLAMA_ARG_CHECKPOINT_EVERY, default 0 = off): a long
  prompt also gets a context checkpoint every N tokens, so a prompt that
  diverges in its middle re-processes at most about N tokens.

Idea: mkyt docs/decisions.md P4-6 (checkpoints at message boundaries and every
~8K tokens, hit share of reusable tokens), ignis, llama.cpp ggml-org#30970.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
thefallentree added a commit to thefallentree/llama.cpp-gp100 that referenced this pull request Nov 19, 2026
…very

- timings.cache_reusable_n and the prometheus counter
  llamacpp:prompt_tokens_reusable_total: the prompt tokens shared with the
  cached state the slot starts from (its own tokens or the host cache entry it
  loaded), before a checkpoint restore. cache_n / cache_reusable_n is the hit
  share of what could have been reused; the rest is the distance back to the
  restored checkpoint. An INFO line per task logs both.
- --checkpoint-every N (LLAMA_ARG_CHECKPOINT_EVERY, default 0 = off): a long
  prompt also gets a context checkpoint every N tokens, so a prompt that
  diverges in its middle re-processes at most about N tokens.

Idea: mkyt docs/decisions.md P4-6 (checkpoints at message boundaries and every
~8K tokens, hit share of reusable tokens), ignis, llama.cpp ggml-org#30970.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
thefallentree added a commit to thefallentree/llama.cpp-gp100 that referenced this pull request Nov 19, 2026
…very

- timings.cache_reusable_n and the prometheus counter
  llamacpp:prompt_tokens_reusable_total: the prompt tokens shared with the
  cached state the slot starts from (its own tokens or the host cache entry it
  loaded), before a checkpoint restore. cache_n / cache_reusable_n is the hit
  share of what could have been reused; the rest is the distance back to the
  restored checkpoint. An INFO line per task logs both.
- --checkpoint-every N (LLAMA_ARG_CHECKPOINT_EVERY, default 0 = off): a long
  prompt also gets a context checkpoint every N tokens, so a prompt that
  diverges in its middle re-processes at most about N tokens.

Idea: mkyt docs/decisions.md P4-6 (checkpoints at message boundaries and every
~8K tokens, hit share of reusable tokens), ignis, llama.cpp ggml-org#30970.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
thefallentree added a commit to thefallentree/llama.cpp-gp100 that referenced this pull request Nov 20, 2026
…very

- timings.cache_reusable_n and the prometheus counter
  llamacpp:prompt_tokens_reusable_total: the prompt tokens shared with the
  cached state the slot starts from (its own tokens or the host cache entry it
  loaded), before a checkpoint restore. cache_n / cache_reusable_n is the hit
  share of what could have been reused; the rest is the distance back to the
  restored checkpoint. An INFO line per task logs both.
- --checkpoint-every N (LLAMA_ARG_CHECKPOINT_EVERY, default 0 = off): a long
  prompt also gets a context checkpoint every N tokens, so a prompt that
  diverges in its middle re-processes at most about N tokens.

Idea: mkyt docs/decisions.md P4-6 (checkpoints at message boundaries and every
~8K tokens, hit share of reusable tokens), ignis, llama.cpp ggml-org#30970.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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

Labels

documentation Improvements or additions to documentation server

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants