server: cross-process VRAM arbiter, sleep/wake, on-demand mmproj and shutdown paths (F5, F6, F7)
Server side of the on-demand VRAM time-sharing (LLAMA_SLEEP_VRAM_ONLY, LLAMA_VRAM_ARENA, LLAMA_SLEEP_EVICT_KV, LLAMA_MMPROJ_ONDEMAND). This commit holds the tools/server parts of the commits below; their library parts are in the F4/F8 commit. Squashed from 10 fork commits (original subjects and messages below). ---- server: on-demand VRAM sharing to time-share one GPU between models (wascb489f336) Add release/restore of a model's GPU weight buffers (keeping a host shadow and the KV cache) so several always-loaded llama-server processes can time-share a single GPU without reloading or losing the prompt cache. - llama-model: release_device_weights()/restore_device_weights() capture a compact host shadow (stable iteration order, view-skipping) and free then realloc the device weight buffers; weights_resident() query. - llama-context: release_device()/restore_device() wrappers; decode() auto- restores; public C API llama_context_release_device/restore_device. - server: LLAMA_SLEEP_VRAM_ONLY makes idle-sleep release only the VRAM weights (not a full unload/reload). A cross-process flock token in LLAMA_VRAM_ARENA enforces "resident iff holds token"; an inotify doorbell forces the holder to release on contention. The warden thread only touches the task queue, so releases run on the loop thread and never race a decode. Validated on RX 580 (Vulkan): two models share 8GB, never both resident, correct output under contention, KV cache preserved (no re-prefill). ---- server: optionally evict the KV cache too (Phase 2 of VRAM sharing) (was3b410b905) Extend on-demand device residency to the KV cache so that when a model's KV plus another model would not fit in VRAM, the KV can also be evicted to a host shadow (D2H on release, H2D on restore) instead of only the weights. - llama_memory_i: add release_device_buffers()/restore_device_buffers() (default no-op). Implemented in llama_kv_cache (D2H shadow of the live ctxs_bufs, freed and reallocated like the weights); llama_memory_hybrid and llama_kv_cache_iswa delegate to their child caches. - llama_context::release_device(evict_kv): also evict the memory's device buffers when requested; restore_device() rebuilds them. Public API llama_context_release_device gains an evict_kv flag. - server: LLAMA_SLEEP_EVICT_KV=1 enables it. Off by default (weights-only), since the KV shadow adds a D2H/H2D copy of the live cache each cycle. Validated on RX 580 (Vulkan), 4B @ 32k ctx: weights-only cold VRAM 1750 MB (KV stays); weights+KV cold VRAM 726 MB (KV freed, ~1 GB reclaimed). KV survives the round-trip: prompt cache reused after the cycle (prompt_n 4 vs 42), correct output. ---- server: keep the sleep-wake path active when the VRAM arbiter is enabled (wasda03d4c1f) The request handler only calls wait_until_no_sleep() (which wakes a server out of its sleeping state) when sleep_idle_seconds >= 0. But the VRAM arbiter's cross-process doorbell can put a server to sleep even when idle-sleep is disabled, so without this a doorbell-slept server would never wake and requests to it would hang until timeout. Do not bypass the wake path when LLAMA_SLEEP_VRAM_ONLY is set, so the arbiter no longer depends on --sleep-idle-seconds being configured. ---- server: coordinate model load with the VRAM arbiter to avoid load-time OOM (wasb9c57d1c2) Before uploading a model's weights, acquire the shared VRAM token (ring the doorbell so any resident model releases first). Previously load uploaded weights to VRAM before the arbiter was active, so loading a large model while another (e.g. the warm 4B task model) held VRAM could exceed the budget and OOM. - add vram_arena_open() (idempotent flock/doorbell setup) and vram_acquire_for_load(), called from load_model() before common_init_from_params(). - a coordinated load now stays warm holding the token and serves its first request without a re-warm (drop the init-time go_cold cold-start). ---- server: restore weights/KV on wake, not at decode, so KV eviction is safe (wase457c2fd6) With LLAMA_SLEEP_EVICT_KV the KV cache device buffers are freed when a model goes cold. update_slots() touches the KV before the decode-time vram_ensure_warm (e.g. SWA models create a checkpoint that reads the KV via ggml_backend_tensor_get), so the KV must already be resident by then. Move the restore to the sleep-wake handler (handle_sleeping_state(false)), which runs before update_slots, fixing a GGML_ASSERT(buffer) crash on iSWA models (gemma) when KV eviction is enabled. ---- server: on-demand mmproj - free encoder VRAM on the text path (was3f61190fd) The vision encoder sits idle in VRAM on every text request. With LLAMA_MMPROJ_ONDEMAND=1 the server keeps the encoder in RAM (released after load) and brings it into VRAM just-in-time before mtmd_batch_encode, releasing it again afterwards - so the encoder's VRAM is free for KV / expert cache on the common text-only path. When the encoder does not fit (that VRAM has been claimed), evict the LLM backbone weights first: they are not needed while the encoder runs (the decode that uses them happens afterwards), their host shadow is read-only (cheap free, no D2H), and the KV / prompt cache is left untouched. Order on the way back matters: free the encoder before re-uploading the weights so the peak stays within VRAM. Also wire the encoder release/restore into the VRAM arbiter: vram_go_cold releases it; the just-in-time encode-path restore replaces the previous restore in vram_ensure_warm. ---- server: replace the VRAM doorbell with a want-lock (wasaa1c2b456) The doorbell was edge-triggered: a waiter wrote <arena>/doorbell/<pid> and the holder's warden turned the inotify event into a queue flag. A ring carried no notion of "still wanted", so it was lost whenever the holder was not already warm and listening - during its model load (the watch does not exist yet, and the kernel does not queue events for a watch that is not there) or inside restore_device - and any ring that survived past the point its sender had been satisfied caused a spurious release. Lost rings wedged the waiter permanently, because flock(LOCK_EX) never times out and, with idle-sleep disabled, the holder had no other reason to release. The wait blocks under mutex_tasks, so the whole server stopped answering while /health still returned 200. Express the request as kernel state instead. A waiter holds <arena>/want.lock shared while it waits and drops it once it owns the token; the sleep decision probes that lock non-blocking and releases the GPU while anyone is waiting. The probe needs its own fd - flock treats two open file descriptions of one file independently, so probing on the waiter's fd would convert our own lock rather than conflict with it. Nothing can be missed, nothing goes stale, and a waiter that dies is cleaned up by the kernel. Probe from should_sleep() on the loop thread rather than from a warden thread. Routing it through a flag is what made the first attempts fail: start_loop() holds mutex_tasks from should_sleep() through the callbacks to the wait, so a warden's request_yield() blocks on that mutex and is admitted only after the flag has been consumed, latching a release for the next wake. Reading live state where the decision is made has no edge to latch, and drops the warden's poll latency. Two sleep-path bugs this exposed: wait_until_no_sleep() waited on !sleeping but the loop clears req_stop_sleeping on the way in, so a loop that slept again before the waiter ran stranded it forever - re-ask on every wake. And a task queued after the waiter saw us awake could not wake us by itself, so sleep now also breaks on a non-empty queue. Hold the GPU for 100 ms after a wake: the request that woke us is not queued yet, and yielding at once only sends it round again. Measured on the RX 580 pod, two servers contending, 60 alternating handoffs: 0 stranded, median 0.309 s against the doorbell's 0.314 s. ---- server: run the shutdown handler off the signal-interrupted thread (was33f8b89f9) A SIGTERM that lands while the start_loop() thread is inside a sleeping callback deadlocks the server. The callbacks run under server_queue::mutex_tasks, and the kernel delivers the signal to that same thread; the handler calls terminate(), which locks mutex_tasks again, and the thread waits on itself forever. With the VRAM arbiter that window is wide - a whole device release, or a blocking wait for the GPU token - and llama-swap sends SIGTERM to evict models, so it hit production: an evicted model wedged mid-release, never released token.lock, and every other model queued behind it. SIGTERM could not stop it either; only SIGKILL did. Make the handler only write the signal number to a self-pipe, which is async-signal-safe, and run shutdown_handler on a dedicated thread. terminate() there simply waits until the loop thread drops mutex_tasks, after which the loop exits normally. The thread is joined before the objects the handler uses are destroyed. If pipe() fails the old direct call is kept. Reproduced 6/6 off production (SIGTERM during release and during the token wait); with the fix 8/8 clean exits, and handoffs, image requests and greedy output are unchanged. ---- server: release the GPU token promptly on shutdown (was83cc51c9d) Two ways a shutting-down server kept the VRAM arbiter's token, stalling every other model: - SIGTERM with a request in flight: terminate() stopped only the task queue. The HTTP handler kept waiting for results the loop would never send, the main thread blocked joining it, and the token was released only in the destructor after that join - i.e. never, until the client went away. Terminate the result queue too (readers now get "server is shutting down": a 503, or an SSE error event), and let wait_until_no_sleep give up once stopping. - SIGTERM while waiting for the token: the loop thread sat in a blocking flock inside the wake callback, holding mutex_tasks, so terminate() waited for the current holder to finish and then for a pointless restore of our weights. Poll the lock non-blocking and abort the wait on shutdown; the aborted wake stays cold, skips the restore, and the loop exits before update_slots. Also release the token right after start_loop() returns rather than in the destructor, and only after the device buffers are actually freed: the old order unlocked before destroy(), so the next model could start uploading into VRAM that was still occupied. Freeing at exit uses a new llama_context_discard_device(), which drops weights, KV, MoE cache and scratch without capturing host shadows first. Off production: SIGTERM mid-generation or mid-wait now exits in ~0.2 s with exit 0 and frees the token within 5-70 ms (previously never / after the holder's whole generation). Handoff latency and greedy output are unchanged. ---- server: fix stale VRAM-arbiter comments and the sleep log line (wasfcfadfbbd) Comments only, plus one log string: - the arbiter block comment said the KV cache is never evicted; with LLAMA_SLEEP_EVICT_KV it is (and the scheduler and scratch with it) - vram_go_cold said vram_ensure_warm() rebuilds the encoder; only encode_mtmd_chunk() restores it, and only for an encode - vram_ensure_warm and the mtmd init block named process_mtmd_chunk; the restore lives in encode_mtmd_chunk - handle_sleeping_state said waking happens lazily before decode; it restores eagerly on the wake transition, before update_slots() - the vram_cold ordering note now says why it still holds with the inline want-lock probe - the sleep log line said "keeping KV cache" even when LLAMA_SLEEP_EVICT_KV evicts it; it now names what actually happens (the prefix "server entering sleeping state" that fork-validate.sh counts is kept) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PZz44SLQvTXMyWGio6t9DZ
This commit is contained in:
1 parent
08a1743c5d
commit
fed49aea5c
4 files changed
+497
-18
No files matched your search
@@ -114,16 +114,17 @@ void server_queue::pop_deferred_task(int id_slot) {
|
||||
|
||||
void server_queue::wait_until_no_sleep() {
|
||||
std::unique_lock<std::mutex> lock(mutex_tasks);
|
||||
if (sleeping) {
|
||||
// re-ask on every wake: the loop clears req_stop_sleeping on the way into sleep, so a loop that
|
||||
// goes back to sleep before we run would strand us here forever
|
||||
// a loop that terminates while asleep never wakes: give up then, the reader reports the shutdown
|
||||
while (sleeping && !stopping) {
|
||||
if (!req_stop_sleeping) {
|
||||
QUE_DBG("%s", "requesting to stop sleeping\n");
|
||||
req_stop_sleeping = true;
|
||||
condition_tasks.notify_one(); // only main thread is waiting on this
|
||||
condition_tasks.notify_all(); // other threads may wait on this too
|
||||
}
|
||||
QUE_DBG("%s", "waiting until no sleep\n");
|
||||
condition_tasks.wait(lock, [&]{
|
||||
return !sleeping;
|
||||
});
|
||||
condition_tasks.wait(lock);
|
||||
}
|
||||
n_inflight++;
|
||||
}
|
||||
@@ -135,6 +136,7 @@ void server_queue::release_inflight() {
|
||||
}
|
||||
|
||||
void server_queue::terminate() {
|
||||
stopping = true; // before the lock: the loop may hold it while it waits for the VRAM token
|
||||
std::unique_lock<std::mutex> lock(mutex_tasks);
|
||||
running = false;
|
||||
condition_tasks.notify_all();
|
||||
@@ -143,7 +145,7 @@ void server_queue::terminate() {
|
||||
bool server_queue::process_new_tasks(bool is_yielding) {
|
||||
while (true) {
|
||||
std::unique_lock<std::mutex> lock(mutex_tasks);
|
||||
if (!running) {
|
||||
if (!running || stopping) {
|
||||
QUE_DBG("%s", "terminate\n");
|
||||
return true;
|
||||
}
|
||||
@@ -291,10 +293,22 @@ void server_queue::start_loop(int64_t idle_sleep_ms) {
|
||||
worker.yielding = false;
|
||||
worker.thread = std::thread([this]() { worker_loop(); });
|
||||
|
||||
constexpr auto max_wait_time = std::chrono::seconds(1);
|
||||
// the arbiter predicate is read from live state, so this timeout bounds how fast we notice a
|
||||
// process waiting for the VRAM token
|
||||
const auto max_wait_time = should_yield_cb ? std::chrono::milliseconds(10) : std::chrono::milliseconds(1000);
|
||||
// after a wake, keep the VRAM for at least this long: the request that woke us is not in the
|
||||
// queue yet, so yielding at once would only send it through another wake
|
||||
constexpr int64_t yield_grace_ms = 100;
|
||||
int64_t time_last_wake = 0;
|
||||
auto should_sleep = [&]() -> bool {
|
||||
// caller must hold mutex_tasks
|
||||
if (idle_sleep_ms < 0 || n_inflight > 0) {
|
||||
if (n_inflight > 0) {
|
||||
return false;
|
||||
}
|
||||
if (should_yield_cb && ggml_time_ms() - time_last_wake >= yield_grace_ms && should_yield_cb()) {
|
||||
return true; // another process waits for the VRAM token - release now
|
||||
}
|
||||
if (idle_sleep_ms < 0) {
|
||||
return false;
|
||||
}
|
||||
int64_t now = ggml_time_ms();
|
||||
@@ -337,9 +351,11 @@ void server_queue::start_loop(int64_t idle_sleep_ms) {
|
||||
cb(true);
|
||||
}
|
||||
req_stop_sleeping = false;
|
||||
// wait until we are requested to exit sleeping state
|
||||
// wait until we are requested to exit sleeping state, or a task arrives: post() only
|
||||
// notifies, so a task queued right after wait_until_no_sleep() saw us awake must be
|
||||
// able to wake us by itself, else it waits here for an unrelated request
|
||||
condition_tasks.wait(lock, [&]{
|
||||
return (!running || req_stop_sleeping);
|
||||
return (!running || req_stop_sleeping || !queue_tasks.empty());
|
||||
});
|
||||
if (!running) { // may changed during sleep
|
||||
break; // terminate
|
||||
@@ -352,17 +368,21 @@ void server_queue::start_loop(int64_t idle_sleep_ms) {
|
||||
}
|
||||
sleeping = false;
|
||||
time_last_task = ggml_time_ms();
|
||||
time_last_wake = time_last_task;
|
||||
condition_tasks.notify_all(); // notify wait_until_no_sleep()
|
||||
break; // process new tasks
|
||||
} else {
|
||||
// wait for new tasks or timeout for checking sleeping condition
|
||||
// wait for new tasks, or timeout for checking sleeping condition
|
||||
bool res = condition_tasks.wait_for(lock, max_wait_time, [&]{
|
||||
return (!queue_tasks.empty() || !running);
|
||||
});
|
||||
if (res) {
|
||||
if (res && !queue_tasks.empty()) {
|
||||
break; // new task arrived or terminate
|
||||
}
|
||||
// otherwise, loop again to check sleeping condition
|
||||
if (!running) {
|
||||
break;
|
||||
}
|
||||
// otherwise (timeout), loop again to re-check should_sleep
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -465,11 +485,12 @@ server_task_result_ptr server_response::recv_with_timeout(const std::unordered_s
|
||||
}
|
||||
}
|
||||
|
||||
std::cv_status cr_res = condition_results.wait_until(lock, deadline);
|
||||
if (!running) {
|
||||
RES_DBG("%s : queue result stop\n", __func__);
|
||||
std::terminate(); // we cannot return here since the caller is HTTP code
|
||||
return nullptr; // the caller checks is_running()
|
||||
}
|
||||
|
||||
std::cv_status cr_res = condition_results.wait_until(lock, deadline);
|
||||
if (cr_res == std::cv_status::timeout) {
|
||||
return nullptr;
|
||||
}
|
||||
@@ -510,6 +531,7 @@ void server_response::broadcast(server_task_result_ptr && result) {
|
||||
}
|
||||
|
||||
void server_response::terminate() {
|
||||
std::unique_lock<std::mutex> lock(mutex_results);
|
||||
running = false;
|
||||
condition_results.notify_all();
|
||||
}
|
||||
@@ -557,6 +579,14 @@ server_task_result_ptr server_response_reader::next(const std::function<bool()>
|
||||
while (true) {
|
||||
server_task_result_ptr result = queue_results.recv_with_timeout(id_tasks, polling_interval_seconds);
|
||||
if (result == nullptr) {
|
||||
if (!queue_results.is_running()) {
|
||||
// the server is shutting down: no result will ever come
|
||||
stop();
|
||||
auto res = std::make_unique<server_task_result_error>();
|
||||
res->err_type = ERROR_TYPE_UNAVAILABLE;
|
||||
res->err_msg = "server is shutting down";
|
||||
return res;
|
||||
}
|
||||
// timeout, check stop condition
|
||||
if (should_stop()) {
|
||||
return nullptr;
|
||||
|
||||
Reference in new issue
Block a user