Repository navigation
server: save and clear idle slots on new task (--clear-idle) - #20993
Conversation
|
Hi @yychyo, thanks for your contribution! Per our contribution guidelines, the automated PR checker found the following issue(s) that need your attention:
Please note that maintainers reserve the right to make final decisions on PRs. If you believe there is a mistake, please comment below. |
a9cde4e to
231926b
Compare
| // 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); | ||
| } |
There was a problem hiding this comment.
That's makes it possible to read an entry from cache to empty slot.
| @@ -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 | |||
There was a problem hiding this comment.
Main logic - under feature flag.
There was a problem hiding this comment.
Isn't it better to clear the idle slot as soon as it becomes idle? I.e. when we call slot.release()?
There was a problem hiding this comment.
Good catch! That is my first contribution, so my vision quite limited - thank you so much for guidance! Done in 2563b4a
There was a problem hiding this comment.
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 | |||
There was a problem hiding this comment.
Enables the cache for empty slot.
|
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 |
| // 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"); | ||
| } | ||
| } | ||
| } | ||
|
|
There was a problem hiding this comment.
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.
The save "cost" is now paid by the finishing request.
--kv-clear-idle)
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: BenchmarkLog
|
💡 Idea: cooldown before evictionIn parallel agentic workloads with fast tool calls (seconds apart), slots get evicted and immediately restored. 👍 / 👎 ? |
b9a4e1f to
d658a62
Compare
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. |
In unified KV cache mode, idle slots' KV cells stay in the
[0, n_kv)rangeand inflate attention cost for all active sequences (even though they're masked).
--clear-idlesaves idle slots to--cache-ramand clears them from VRAM, reducingn_kvto only active tokens.Requires
--cache-ramand unified KV cache. Disable with--no-clear-idle.Benchmarks (agentic workload with multiple agents)
--clear-idle) #20993 (comment)--clear-idle) #20993 (comment)--clear-idle) #20993 (comment)Open questions
Misc. bug: llama-server with -kvu and --parallel 4 slows down tg with more inactive slots #19523 (comment) - should we enable this flag by default for CUDA backend only?- All GPU backends iterate [0, n_kv) in attention (Metal/Vulkan skip masked blocks but still iterate).--clear-idle) #20993 (comment) - do we need a cooldown period? - out of scope of this PR, will create an issue or a draft PR.Related
Requirements