Skip to content

server: save and clear idle slots on new task (--clear-idle) - #20993

Merged
ngxson merged 11 commits into
ggml-org:masterfrom
yychyo:server-kv-keep-only-active
Apr 3, 2026
Merged

ngxson merged 11 commits into
ggml-org:masterfrom
yychyo:server-kv-keep-only-active

Conversation

@yychyo

@yychyo yychyo commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

In unified KV cache mode, idle slots' KV cells stay in the [0, n_kv) range
and inflate attention cost for all active sequences (even though they're masked).

--clear-idle saves idle slots to --cache-ram and clears them from VRAM, reducing n_kv to only active tokens.

Requires --cache-ram and unified KV cache. Disable with --no-clear-idle.

Benchmarks (agentic workload with multiple agents)

Open questions

Related

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: YES ✨, assisted with research and test scaffolding. All code reviewed and understood.

@ggml-gh-bot

ggml-gh-bot Bot commented Mar 25, 2026

Copy link
Copy Markdown

Hi @yychyo, thanks for your contribution!

Per our contribution guidelines, the automated PR checker found the following issue(s) that need your attention:

  • AI-generated content: This project does not accept PRs, descriptions or commit messages that are fully or predominantly AI-generated. If you have used AI to assist you in writing code, please make sure to disclose that explicitly.

Please note that maintainers reserve the right to make final decisions on PRs. If you believe there is a mistake, please comment below.

@yychyo

yychyo commented Mar 26, 2026

Copy link
Copy Markdown
Contributor Author

@yychyo
yychyo force-pushed the server-kv-keep-only-active branch from a9cde4e to 231926b Compare March 26, 2026 12:42
@yychyo
yychyo requested a review from a team as a code owner March 26, 2026 12:42
Comment on lines -1013 to +1037
// don't update the cache if the slot's context is empty
update_cache = update_cache && tokens.size() > 0;

if (update_cache) {
SRV_WRN("%s", "updating prompt cache\n");

const int64_t t_start = ggml_time_us();

ret->prompt_save(*prompt_cache);
// don't save the slot's state if its context is empty
if (tokens.size() > 0) {
ret->prompt_save(*prompt_cache);
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That's makes it possible to read an entry from cache to empty slot.

Comment thread tools/server/server-context.cpp Outdated
@@ -2689,6 +2705,34 @@ struct server_context_impl {
n_empty_consecutive = 0;
}

if (kv_keep_only_active && batch.n_tokens > 0) { // LLAMA_KV_KEEP_ONLY_ACTIVE: clear idle slots' KV

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Main logic - under feature flag.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Isn't it better to clear the idle slot as soon as it becomes idle? I.e. when we call slot.release()?

@yychyo yychyo Mar 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch! That is my first contribution, so my vision quite limited - thank you so much for guidance! Done in 2563b4a

@yychyo yychyo Mar 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added f6c4a3d . Also clear idle slots on launch, not just release. Release alone doesn't cover sequential requests (last slot has no reason to clear if nobody else needs VRAM).

@@ -2010,7 +2010,7 @@ server_prompt * server_prompt_cache::alloc(const server_prompt & prompt, size_t
bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, llama_context * ctx, int32_t id_slot) {
const int lcp_best = prompt.tokens.get_common_prefix(tokens_new);

float f_keep_best = float(lcp_best) / prompt.tokens.size();
float f_keep_best = prompt.tokens.size() > 0 ? float(lcp_best) / prompt.tokens.size() : -1.0f; // empty slot: any cache entry wins

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Enables the cache for empty slot.

@github-actions github-actions Bot added examples python python script changes server labels Mar 26, 2026
@ggerganov

Copy link
Copy Markdown
Member

Thanks, this should be a good improvement for unified KV cache setups. I have yet to take a detailed look at how you implemented it. In the meantime, hopefully we get some feedback from people with CUDA backend and -np 4 -kvu - the performance over multiple long requests should degrade much less if this works correctly.

Comment thread tools/server/server-context.cpp Outdated
Comment on lines +868 to +882
// LLAMA_KV_KEEP_ONLY_ACTIVE: clear idle slots' KV from VRAM before each decode batch
{
const char * env = getenv("LLAMA_KV_KEEP_ONLY_ACTIVE");
if (env && atoi(env)) {
if (!params_base.kv_unified) {
SRV_WRN("%s\n", "LLAMA_KV_KEEP_ONLY_ACTIVE requires unified KV cache, ignoring");
} else if (params_base.cache_ram_mib == 0) {
SRV_WRN("%s\n", "LLAMA_KV_KEEP_ONLY_ACTIVE requires --cache-ram, ignoring");
} else {
kv_keep_only_active = true;
SRV_INF("%s\n", "LLAMA_KV_KEEP_ONLY_ACTIVE: idle slots' KV will be cleared from VRAM before each decode");
}
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think we might want kv_keep_only_active to always be on by default when kv_unified == true and can be disabled with a CLI argument.

@yychyo yychyo Mar 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in ced2476

@yychyo
yychyo requested a review from a team as a code owner March 27, 2026 20:08
@yychyo yychyo changed the title server : add LLAMA_KV_KEEP_ONLY_ACTIVE to clear idle slots' KV server: clear idle slots KV on release (--kv-clear-idle) Mar 27, 2026
@yychyo

yychyo commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks, this should be a good improvement for unified KV cache setups. I have yet to take a detailed look at how you implemented it. In the meantime, hopefully we get some feedback from people with CUDA backend and -np 4 -kvu - the performance over multiple long requests should degrade much less if this works correctly.

I've made a bench script for "agentic" - like workflow:

Code
#!/usr/bin/env bash

HOST=127.0.0.1
PORT=8990
URL="http://$HOST:$PORT"
N_PREDICT="${N_PREDICT:-512}"
DELAY="${DELAY:-0}"

SERVER_CMD="${SERVER_CMD:-./build-cuda/bin/llama-server \
    -hf bartowski/Qwen_Qwen3.5-4B-GGUF:IQ4_NL \
    --host $HOST --port $PORT -ngl 99 -c 131072 --cache-ram 40960 \
    --swa-checkpoints 32 --cache-type-k q8_0 --jinja \
    --slots --temp 0.0 -b 256 -ub 256}"

make_prompt() {
    local user=$1 turn=$2
    local filler="The ancient library stood at the edge of the forgotten city where scholars gathered for centuries to study mysteries of the universe and decode symbols carved into walls of the great hall. "
    local grow="Additional context was provided by the researchers who continued their investigation into the deeper layers of understanding that emerged from careful analysis of primary sources and artifacts. "
    local p="Agent ${user}: "
    p+=$(printf "${filler}%.0s" $(seq 1 500))
    for ((r=0; r<(turn+1)*140; r++)); do p+="$grow"; done
    echo "$p"
}

post_agent() {
    local turn=$1 id=$2 outdir="$3"
    local t0=$SECONDS delay=0
    if [[ "$turn" -gt 0 && "$DELAY" -gt 0 ]]; then delay=$((RANDOM % DELAY)); sleep "$delay"; fi
    printf "  → agent %d turn %d%s\n" "$id" "$turn" "$( (( delay )) && echo " (delay=${delay}s)" )" >&2
    local prompt=$(make_prompt "$id" "$turn")
    local resp=$(printf '%s' "$prompt" | jq -Rs --argjson np "$N_PREDICT" '{prompt:., n_predict:$np, cache_prompt:true}' |
        curl -sf "$URL/completion" -H "Content-Type: application/json" -d @-) || { echo "curl failed for agent $id turn $turn" >&2; return 1; }
    echo "$resp" | jq -r --arg t "$turn" --arg aid "$id" '"\($t) \($aid) \(.timings.predicted_per_second) \(.timings.prompt_n)"' > "$outdir/turn${turn}_agent${id}.txt"
    local tg=$(echo "$resp" | jq .timings.predicted_per_second)
    local pn=$(echo "$resp" | jq .timings.prompt_n)
    printf "  ← agent %d turn %d: TG=%.1f prompt_n=%d (%ds)\n" "$id" "$turn" "$tg" "$pn" "$((SECONDS-t0))" >&2
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
  set -euo pipefail
  export SCRIPT_DIR="$(realpath "$(dirname "${BASH_SOURCE[0]}")")"
  export N_AGENTS="${1:-4}"
  export N_WORKERS="${2:-2}"
  export N_PREDICT DELAY
  LOGDIR="logs/bench-$(date +%Y%m%d-%H%M%S)-agentic"
  mkdir -p "$LOGDIR"
  export LOGDIR

  SERVER_PID=""
  stop_server() {
      if [[ -n "$SERVER_PID" ]]; then
          kill "$SERVER_PID" 2>/dev/null || true
          wait "$SERVER_PID" 2>/dev/null || true
          SERVER_PID=""
      fi
  }
  trap stop_server EXIT

  start_server() {
      local logfile="$1"; shift
      # shellcheck disable=SC2086
      $SERVER_CMD "$@" >"$logfile" 2>&1 &
      SERVER_PID=$!
      for _ in $(seq 1 60); do curl -sf "$URL/health" >/dev/null 2>&1 && break; sleep 1; done
      curl -sf "$URL/health" >/dev/null 2>&1 || { echo "server failed to start" >&2; exit 1; }
  }

  wait_port_free() { while curl -sf "$URL/health" >/dev/null 2>&1; do sleep 1; done; }

  run_phase() {
      local label="$1"; shift
      local outdir="$LOGDIR/$label"
      mkdir -p "$outdir"
      export OUTDIR="$outdir"

      echo "--- $label ---" >&2
      start_server "$LOGDIR/$label.log" "$@"
      make -j"$N_WORKERS" AGENTS="$(seq -s' ' 0 $((N_AGENTS-1)))" -f <(cat <<'__EOF'
SHELL := bash
.SHELLFLAGS := -eu -o pipefail -c
export BASH_ENV := $(SCRIPT_DIR)/bench-kv-agentic.sh

LAST_TURN := $(foreach a,$(AGENTS),$(OUTDIR)/turn3_agent$(a).txt)

.DELETE_ON_ERROR:
.SUFFIXES:
.PHONY: all
all: $(LAST_TURN)

# chain turns per agent: turn1 depends on turn0, turn2 on turn1, turn3 on turn2
$(foreach a,$(AGENTS),\
  $(foreach t,1 2 3,\
    $(eval $(OUTDIR)/turn$(t)_agent$(a).txt: $(OUTDIR)/turn$(shell echo $$(($(t)-1)))_agent$(a).txt)))

# pattern rule per agent: extract turn from filename stem (turn1_agent0 -> turn=1)
$(foreach a,$(AGENTS),\
  $(eval $(OUTDIR)/turn%_agent$(a).txt: ; @post_agent $$(firstword $$(subst _, ,$$*)) $(a) $(OUTDIR)))
__EOF
    )
      stop_server
      wait_port_free
  }

  echo "=== Agentic Parallel ($N_AGENTS agents, $N_WORKERS workers, n_predict=$N_PREDICT) ==="
  echo "SERVER_CMD: $SERVER_CMD"

  run_phase baseline --no-kv-clear-idle
  run_phase feature

  echo ""
  echo "| Turn | Agent | Baseline TG | Feature TG | Prompt tokens |"
  echo "|------|-------|-------------|------------|---------------|"
  for turn in 0 1 2 3; do
      for agent in $(seq 0 $((N_AGENTS-1))); do
          bl=($(cat "$LOGDIR/baseline/turn${turn}_agent${agent}.txt"))
          ft=($(cat "$LOGDIR/feature/turn${turn}_agent${agent}.txt"))
          printf "| %s | %s | %.1f t/s | %.1f t/s | %s |\n" "$turn" "$agent" "${bl[2]}" "${ft[2]}" "${bl[3]}"
      done
  done
  echo ""
  echo "Logs: $LOGDIR/"
fi

Runs N agents, M active at a time (make -j), with optional random delay between turns. Each agent has a unique prefix and growing context (~20k→32k tokens over 4 turns).

RTX 3090, Qwen3.5-4B IQ4_NL, 8 agents / 4 slots / 2 concurrent, --cache-ram 40960, 131K ctx:

Benchmark
❯ DELAY=5 ./bench-kv-agentic.sh 8 2 2>&1 | tee agentic.log
=== Agentic Parallel (8 agents, 2 workers, n_predict=512) ===
SERVER_CMD: ./build-cuda/bin/llama-server     -hf bartowski/Qwen_Qwen3.5-4B-GGUF:IQ4_NL     --host 127.0.0.1 --port 8990 -ngl 99 -c 131072 --cache-ram 40960     --swa-checkpoints 32 --cache-type-k q8_0 --jinja     --slots --temp 0.
0 -b 256 -ub 256
...

Log

Turn Agent Baseline TG Feature TG Prompt tokens
0 0 44.8 t/s 44.3 t/s 20425
0 1 42.1 t/s 41.1 t/s 20425
0 2 67.3 t/s 84.4 t/s 20425
0 3 64.7 t/s 88.4 t/s 20425
0 4 29.4 t/s 43.9 t/s 20425
0 5 30.1 t/s 40.8 t/s 20425
0 6 29.7 t/s 43.8 t/s 20425
0 7 71.8 t/s 88.1 t/s 20425
1 0 68.0 t/s 70.2 t/s 3924
1 1 54.2 t/s 83.7 t/s 3924
1 2 51.8 t/s 81.5 t/s 3924
1 3 65.3 t/s 70.0 t/s 3924
1 4 64.8 t/s 78.0 t/s 3924
1 5 50.9 t/s 62.3 t/s 3924
1 6 51.7 t/s 55.8 t/s 3924
1 7 65.2 t/s 58.2 t/s 3924
2 0 66.0 t/s 55.3 t/s 3924
2 1 42.6 t/s 44.3 t/s 3924
2 2 60.5 t/s 35.6 t/s 3924
2 3 47.8 t/s 50.7 t/s 3924
2 4 42.7 t/s 81.1 t/s 3924
2 5 47.8 t/s 54.0 t/s 3924
2 6 67.5 t/s 36.1 t/s 3924
2 7 47.2 t/s 51.1 t/s 3924
3 0 59.9 t/s 48.2 t/s 3924
3 1 28.0 t/s 80.1 t/s 3924
3 2 32.2 t/s 69.4 t/s 3924
3 3 39.2 t/s 58.3 t/s 3924
3 4 44.6 t/s 47.6 t/s 3924
3 5 23.9 t/s 80.3 t/s 3924
3 6 31.5 t/s 68.4 t/s 3924
3 7 61.9 t/s 79.6 t/s 3924
Metric Baseline Feature Delta
TG avg 49.8 t/s 61.7 t/s +24%
Wall time 321s 213s -34%
Cache updates avg 1892ms 768ms -59%

@yychyo

yychyo commented Mar 28, 2026 •

Copy link
Copy Markdown
Contributor Author

💡 Idea: cooldown before eviction

In parallel agentic workloads with fast tool calls (seconds apart), slots get evicted and immediately restored. --no-kv-clear-idle N (default 0 = immediate) could add a cooldown before clearing on release.

👍 / 👎 ?

@yychyo
yychyo force-pushed the server-kv-keep-only-active branch from b9a4e1f to d658a62 Compare March 28, 2026 20:16
@strawberrymelonpanda

Copy link
Copy Markdown
Contributor

feedback from people with CUDA backend and -np 4 -kvu
RTX 3090, Qwen3.5-4B IQ4_NL, 8 agents / 4 slots / 2 concurrent, --cache-ram 40960, 131K ctx:

Was just playing around with --parallel and -kvu today. -np 2 and -kvu together seem pretty good on my system with a 3090 and Qwen 27B, but @yychyo's 8 agents, 2 workers, 88+ t/s makes me feel like I'm doing something very wrong. 😆

Haven't had a chance to bench this branch yet, but watching the PR with interest.

@yychyo

yychyo commented Mar 31, 2026