diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 89f884e65..c9a58290d 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -34,6 +34,8 @@ #include #include #include +#include +#include // fix problem with std::min and std::max #if defined(_WIN32) @@ -44,6 +46,16 @@ #include #endif +// POSIX file locking for the cross-process VRAM arbiter (see vram_share_* below) +#if !defined(_WIN32) +#include +#include +#include +#include +#include +#include +#endif + constexpr int HTTP_POLLING_SECONDS = 1; static common_speculative_output_limits server_output_limits(const common_params & params) { @@ -912,7 +924,36 @@ static int encode_mtmd_chunk(const server_slot & slot, mtmd::batch_ptr & mbatch, // TODO @ngxson : move this log line to debug when it become more stable SLT_TRC(slot, "encoding mtmd batch from idx = %zu, n_chunks = %d\n", idx, n_added); + // Bring the vision/audio encoder into VRAM just for this encode. In on-demand mode the + // encoder is normally kept in RAM (its VRAM freed for KV / expert cache). If it does not + // fit, evict the LLM backbone weights first: they are NOT needed while the encoder runs (the + // decode that uses them happens afterwards) and their host shadow is read-only, so this is a + // cheap free (no D2H) and leaves the KV cache / prompt cache untouched. + static const bool mmproj_ondemand = getenv("LLAMA_MMPROJ_ONDEMAND") != nullptr; + bool weights_evicted = false; + if (mctx && !mtmd_restore_device(mctx)) { + if (mmproj_ondemand) { + llama_context_release_device(slot.ctx_tgt, /* evict_kv = */ false); // free backbone, keep KV + weights_evicted = true; + } + if (!mtmd_restore_device(mctx)) { + if (weights_evicted) { llama_context_restore_device(slot.ctx_tgt); } + SLT_ERR(slot, "%s", "failed to bring the multimodal encoder into VRAM for encoding\n"); + return -1; + } + } + res = mtmd_batch_encode(mbatch.get()); + + // release the encoder VRAM again (on-demand), then restore the backbone weights for decode. + // Order matters: free the encoder BEFORE re-uploading the weights so the peak stays within VRAM. + if (mctx && mmproj_ondemand) { + mtmd_release_device(mctx); + } + if (weights_evicted) { + llama_context_restore_device(slot.ctx_tgt); + } + if (res != 0) { SLT_ERR(slot, "failed to encode mtmd batch for chunk idx = %zu, res = %d\n", idx, res); return -1; @@ -1078,6 +1119,8 @@ public: // we don't call it again here to avoid double free destroy(); } + // only once our VRAM is freed (normally vram_share_exit() has done both already) + vram_share_shutdown(); } server_metrics get_metrics() const { @@ -1104,6 +1147,275 @@ private: llama_model * model_dft = nullptr; llama_context * ctx_dft = nullptr; + // Cross-process VRAM arbiter: when LLAMA_SLEEP_VRAM_ONLY is set, several always-loaded + // llama-server processes time-share one GPU. A single flock() on /token.lock is the + // baton: "resident (device buffers in VRAM) iff I hold the token". A model warms up (locks + + // restores) when it wakes for a request, and goes cold (releases + unlocks) when it is idle and + // another process waits for the token, so only one model holds VRAM at a time. The process, its + // context and its prompt cache stay alive, so nothing is re-prefilled. Going cold releases the + // weights; with LLAMA_SLEEP_EVICT_KV it also evicts the KV/recurrent state to a host shadow and + // frees the scheduler and backend scratch. All of it is restored bit-exact on wake. + bool vram_only = false; // release-mode sleep active (LLAMA_SLEEP_VRAM_ONLY) + bool vram_evict_kv = false; // also evict the KV cache to host on release (LLAMA_SLEEP_EVICT_KV) + bool vram_flock = false; // cross-process flock coordination available + std::atomic vram_cold{true}; // weights currently released + int vram_lock_fd = -1; // fd for /token.lock + + // "want" lock: a process that waits for the token holds /want.lock shared, and drops it + // as soon as it owns the token. The holder probes that lock with a non-blocking exclusive + // flock, which fails only while somebody waits. This is level-triggered state owned by the + // kernel, so there is no event to miss and nothing goes stale if a waiter dies. + // The probe needs its own fd: flock() treats two open file descriptions of one file + // independently, so probing on the waiter fd would convert our own lock instead of conflicting. + int vram_want_fd = -1; // waiter side, LOCK_SH while waiting + int vram_want_probe_fd = -1; // probe side, LOCK_EX | LOCK_NB only + bool vram_want_held = false; // only touched by the waiting thread + + // open the shared arena (token.lock + want.lock). Idempotent; sets vram_only/vram_flock. + void vram_arena_open() { + if (getenv("LLAMA_SLEEP_VRAM_ONLY") == nullptr) { + return; + } + vram_only = true; + vram_evict_kv = getenv("LLAMA_SLEEP_EVICT_KV") != nullptr; +#if !defined(_WIN32) + if (vram_lock_fd >= 0) { + return; // already open + } + const char * arena_env = getenv("LLAMA_VRAM_ARENA"); + const std::string arena = arena_env ? arena_env : "/dev/shm/llama-vram"; + mkdir(arena.c_str(), 0777); + const std::string lock_path = arena + "/token.lock"; + vram_lock_fd = open(lock_path.c_str(), O_RDWR | O_CREAT, 0666); + if (vram_lock_fd >= 0) { + vram_flock = true; + const std::string want_path = arena + "/want.lock"; + vram_want_fd = open(want_path.c_str(), O_RDWR | O_CREAT, 0666); + vram_want_probe_fd = open(want_path.c_str(), O_RDWR | O_CREAT, 0666); + if (vram_want_fd < 0 || vram_want_probe_fd < 0) { + SRV_WRN("VRAM arbiter: cannot open %s, the holder will only release on idle\n", want_path.c_str()); + } + SRV_INF("VRAM arbiter: cross-process GPU sharing via %s (want %s)\n", + lock_path.c_str(), want_path.c_str()); + } else { + SRV_WRN("VRAM arbiter: cannot open %s, running VRAM-only sleep without cross-process lock\n", lock_path.c_str()); + } +#endif + } + + // Acquire the VRAM token BEFORE uploading this model's weights, so any model currently resident + // on the GPU releases first and the load uploads into free VRAM instead of racing it (which + // could OOM, e.g. the 4B task model holding VRAM while a large model loads). Blocks until free. + // Called from load_model() right before common_init_from_params(). + void vram_acquire_for_load() { + vram_arena_open(); + if (!vram_only) { + return; + } + if (!vram_take_token()) { + SRV_WRN("%s", "VRAM arbiter: loading weights without the GPU token\n"); + } + vram_cold = false; // we hold the token; weights will be resident after the upload + } + + // Called from init() after the (coordinated) load. The model stays warm (holding the token + // acquired in vram_acquire_for_load) and serves its first request without a re-warm; the queue + // releases it once another model registers on want.lock. + void vram_share_init() { + vram_arena_open(); + if (!vram_only) { + return; + } + vram_cold = false; // resident and holding the token after the coordinated load +#if !defined(_WIN32) + if (vram_flock && vram_want_probe_fd >= 0) { + queue_tasks.on_should_yield([this]{ return vram_should_yield(); }); + } +#endif + } + + // true while another process waits for the token and we still hold it. Called by should_sleep() + // on the start_loop() thread, under mutex_tasks, and only when the queue is idle - so a release + // can never happen underneath an in-flight decode, and there is no event to latch: the answer + // comes from live kernel state at the moment the loop asks. + bool vram_should_yield() { +#if !defined(_WIN32) + if (!vram_flock || vram_cold || vram_want_probe_fd < 0) { + return false; // we hold no token to give away + } + // never blocks: LOCK_NB only, and we drop the probe lock at once if we win it + if (flock(vram_want_probe_fd, LOCK_EX | LOCK_NB) == 0) { + flock(vram_want_probe_fd, LOCK_UN); + return false; // nobody wants the GPU + } + return errno == EWOULDBLOCK || errno == EAGAIN; +#else + return false; +#endif + } + + // register as a waiter, so the current token holder sees us and yields. Shared, so several + // waiters coexist. The kernel drops it if we die, so it can never strand the holder. + void vram_want_acquire() { +#if !defined(_WIN32) + if (vram_want_fd < 0 || vram_want_held) { + return; + } + while (flock(vram_want_fd, LOCK_SH) != 0) { + if (errno != EINTR) { // our signal handlers run without SA_RESTART + SRV_WRN("VRAM arbiter: cannot take want.lock (errno %d)\n", errno); + return; + } + } + vram_want_held = true; +#endif + } + + // stop asking for the token. Must run on every path out of vram_take_token(), or the holder + // yields forever. + void vram_want_release() { +#if !defined(_WIN32) + if (vram_want_fd < 0 || !vram_want_held) { + return; + } + flock(vram_want_fd, LOCK_UN); + vram_want_held = false; +#endif + } + + // take the shared VRAM token: register on want.lock, then wait for token.lock. want.lock is + // level-triggered state, so the holder still learns of us if it is loading or restoring when we + // start to wait. No timeout: the holder can be mid-generation, and decoding without the token + // risks an OOM that kills both processes. Returns false without the token if the server shuts + // down meanwhile (the caller checks queue_tasks.is_stopping()). + bool vram_take_token() { +#if !defined(_WIN32) + if (!vram_flock) { + return true; // no cross-process lock: there is no token to take + } + vram_want_acquire(); + bool logged = false; + while (flock(vram_lock_fd, LOCK_EX | LOCK_NB) != 0) { + if (errno == EWOULDBLOCK || errno == EAGAIN) { + if (!logged) { + SRV_INF("%s", "VRAM arbiter: waiting for the GPU token\n"); + logged = true; + } + // poll, not a blocking flock: terminate() must be able to stop this wait, and it can + // only signal us through an atomic (we hold mutex_tasks here) + if (queue_tasks.is_stopping()) { + SRV_INF("%s", "VRAM arbiter: shutting down, no longer waiting for the GPU token\n"); + vram_want_release(); + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + continue; + } + if (errno == EINTR) { + continue; // our signal handlers run without SA_RESTART + } + SRV_WRN("VRAM arbiter: flock failed (errno %d)\n", errno); + vram_want_release(); + return false; + } + vram_want_release(); + return true; +#else + return true; +#endif + } + + // acquire the VRAM token (blocking) and bring the device buffers back (weights; with + // LLAMA_SLEEP_EVICT_KV also the KV/recurrent state and the scheduler). Called on the loop thread: + // on wake from handle_sleeping_state(false), before update_slots() touches the KV, and again + // right before each decode (a no-op when already warm). It never races compute. Returns false, + // still cold, if the server shuts down first: the caller must not touch the device then. + bool vram_ensure_warm() { + if (!vram_only || !vram_cold) { + return true; + } + if (queue_tasks.is_stopping()) { + return false; // no restore just to exit + } + if (!vram_take_token()) { + if (queue_tasks.is_stopping()) { + return false; + } + SRV_WRN("%s", "VRAM arbiter: restoring weights without the GPU token\n"); + } + llama_context_restore_device(ctx_tgt); + if (ctx_dft != nullptr) { + llama_context_restore_device(ctx_dft); + } + // NOTE: the multimodal (vision/audio) encoder is intentionally NOT restored here. It is + // brought into VRAM just-in-time before an image/audio encode (encode_mtmd_chunk) and, in + // on-demand mode, released again right after - so a warm text-only model holds no encoder + // VRAM (that space is free for KV / expert cache). A cold->warm wake for a *text* request + // therefore leaves the encoder in RAM; an image request restores it at encode time. + // NOTE: keep this AFTER the restore: vram_cold == false means "holding the token AND + // resident". Today the only reader that could give the token away, vram_should_yield(), runs + // on this same loop thread and so cannot run before we return; the order is what kept the + // retired cross-thread doorbell design from yielding mid-restore (FORK.md F6, attempt 1). + // Do not move it without an A/B of ordinary handoff latency. We dropped want.lock when we + // took the token, so the next probe reports only the waiters that are still there. + vram_cold = false; + return true; + } + + // the loop has stopped: free our VRAM and hand the token over now, without waiting for the HTTP + // threads and the teardown. Discarded, not released: no host copy, and the context never decodes + // again. Runs on the loop thread after the loop returned, so nothing else uses the device. + void vram_share_exit() { + if (vram_only && !vram_cold && ctx_tgt != nullptr) { + llama_context_discard_device(ctx_tgt); + if (ctx_dft != nullptr) { + llama_context_discard_device(ctx_dft); + } + if (mctx != nullptr) { + mtmd_release_device(mctx); + } + vram_cold = true; + SRV_INF("%s", "VRAM arbiter: loop stopped, device memory freed, releasing the GPU token\n"); + } + vram_share_shutdown(); + } + + void vram_share_shutdown() { +#if !defined(_WIN32) + vram_want_release(); + if (vram_want_probe_fd >= 0) { close(vram_want_probe_fd); vram_want_probe_fd = -1; } + if (vram_want_fd >= 0) { close(vram_want_fd); vram_want_fd = -1; } + if (vram_lock_fd >= 0) { flock(vram_lock_fd, LOCK_UN); close(vram_lock_fd); vram_lock_fd = -1; } +#endif + } + + // release the device weights (their host shadow is kept; with LLAMA_SLEEP_EVICT_KV also the + // KV/recurrent state, scheduler and backend scratch) and drop the VRAM token so another model + // can warm up. Called on the loop thread from handle_sleeping_state(true): the queue is idle and + // another process waits for the token. + void vram_go_cold() { + if (!vram_only || vram_cold) { + return; + } + llama_context_release_device(ctx_tgt, vram_evict_kv); + if (ctx_dft != nullptr) { + llama_context_release_device(ctx_dft, vram_evict_kv); + } + // also release the multimodal (vision/audio) encoder weights (dead weight while cold; a + // no-op when LLAMA_MMPROJ_ONDEMAND already keeps them out). Their read-only host shadow is + // captured once. vram_ensure_warm() does not bring them back: encode_mtmd_chunk() restores + // the encoder only for the duration of an encode. + if (mctx != nullptr) { + mtmd_release_device(mctx); + } +#if !defined(_WIN32) + if (vram_flock) { + flock(vram_lock_fd, LOCK_UN); + } +#endif + vram_cold = true; + } + common_speculative_init_result_ptr spec_init; common_context_seq_rm_type ctx_tgt_seq_rm_type = COMMON_CONTEXT_SEQ_RM_TYPE_NO; @@ -1171,6 +1483,32 @@ private: void handle_sleeping_state(bool new_state) { GGML_ASSERT(sleeping != new_state); + + // Lightweight VRAM-only sleep: instead of a full unload/reload (which frees RAM and the + // KV cache and pays a full reload on wake), just release the model's device (VRAM) buffers + // to a host shadow (keeping the context, the prompt cache and the host weights; the KV stays + // on the device unless LLAMA_SLEEP_EVICT_KV is set) and drop the shared VRAM token. Waking + // restores eagerly, on the wake transition below: vram_ensure_warm() re-acquires the token + // and restores before update_slots() runs. A single GPU is so time-shared between models + // with no re-prefill. + if (vram_only && ctx_tgt != nullptr) { + if (new_state) { + SRV_INF("server entering sleeping state (VRAM-only: releasing device weights, %s)\n", + vram_evict_kv ? "evicting KV cache to host" : "keeping KV cache in VRAM"); + vram_go_cold(); + } else { + SRV_INF("%s", "server exiting sleeping state (VRAM-only: restoring device weights/KV)\n"); + // Restore NOW, on wake, before update_slots runs. update_slots touches the KV cache + // (e.g. SWA checkpoint creation reads it via ggml_backend_tensor_get) before the + // decode-time vram_ensure_warm(), so with KV eviction the KV must already be resident + // here or those reads hit a freed (null) buffer. + // false (still cold) only on shutdown: the loop then exits before update_slots + vram_ensure_warm(); + } + sleeping = new_state; + return; + } + if (new_state) { if (callback_state) { callback_state(SERVER_STATE_SLEEPING, {}); @@ -1323,6 +1661,11 @@ private: params_base.load_progress_callback_user_data = &load_progress_text; } + // VRAM arbiter: acquire the GPU token before uploading weights, so any resident model (e.g. + // the warm 4B task model) releases first and this load uploads into free VRAM instead of + // racing it and OOM-ing. No-op unless LLAMA_SLEEP_VRAM_ONLY is set. + vram_acquire_for_load(); + llama_init = common_init_from_params(params_base); model_tgt = llama_init->model(); @@ -1422,6 +1765,13 @@ private: init_opt.video_params.ffmpeg_bin_dir = params_base.video_ffmpeg_bin_dir.empty() ? nullptr : params_base.video_ffmpeg_bin_dir.c_str(); + // on-demand encoder: keep the vision/audio encoder weights in RAM (out of VRAM) until an + // image/audio actually needs encoding, freeing that VRAM for KV / expert cache on the + // common text-only path. encode_mtmd_chunk() brings the encoder in just-in-time. + if (getenv("LLAMA_MMPROJ_ONDEMAND") != nullptr) { + mtmd_release_device(mctx); + } + if (params_base.ctx_shift) { params_base.ctx_shift = false; SRV_WRN("%s\n", "ctx_shift is not supported by multimodal, it will be disabled"); @@ -1679,6 +2029,11 @@ private: handle_sleeping_state(sleeping); }); + // VRAM arbiter: arm the yield probe. The load was coordinated (vram_acquire_for_load + // grabbed the token before uploading), so we stay warm holding the token and serve the + // first request without a re-warm; the loop releases it when another model waits for it. + vram_share_init(); + metrics.init(); if (params_base.cache_idle_slots) { @@ -4635,6 +4990,13 @@ private: has_output |= batch.tokens[i].output; } + // VRAM arbiter: make sure our weights are resident (acquiring the shared GPU token first) + // before we decode. Runs on the loop thread before entering yield_to_queue(), so it never + // races an in-flight decode. + if (!vram_ensure_warm()) { + throw std::runtime_error("server is shutting down"); + } + // yield to the queue, so we can still handle metrics tasks while decoding // note: the sync is done here too, so that the wait is also covered by the yield int ret = 0; @@ -5152,9 +5514,12 @@ bool server_context::load_model(common_params & params) { void server_context::start_loop() { auto & params = impl->params_base; impl->queue_tasks.start_loop(params.sleep_idle_seconds * 1000); + impl->vram_share_exit(); } void server_context::terminate() { + // wake the HTTP threads waiting for results first: the loop will not produce them any more + impl->queue_results.terminate(); impl->queue_tasks.terminate(); } @@ -5231,8 +5596,12 @@ struct server_res_generator : server_res_spipe { server_queue * queue_awake = nullptr; // set while this response keeps the server awake server_res_generator(server_queue & queue_tasks, server_response & queue_results, int sleep_idle_seconds, bool bypass_sleep = false) : rd(queue_tasks, queue_results, HTTP_POLLING_SECONDS) { - // fast path in case sleeping is disabled - bypass_sleep |= sleep_idle_seconds < 0; + // fast path in case sleeping is disabled. Note: the VRAM arbiter (LLAMA_SLEEP_VRAM_ONLY) + // can put the server to sleep to hand over the GPU token even when idle-sleep is disabled + // (sleep_idle_seconds < 0), so in that case requests must still wake it - otherwise an + // arbiter-slept server would hang, never returning from a request. + static const bool vram_arbiter = getenv("LLAMA_SLEEP_VRAM_ONLY") != nullptr; + bypass_sleep |= (sleep_idle_seconds < 0 && !vram_arbiter); if (!bypass_sleep) { queue_tasks.wait_until_no_sleep(); queue_awake = &queue_tasks; diff --git a/tools/server/server-queue.cpp b/tools/server/server-queue.cpp index 75daebb0d..17f3d9104 100644 --- a/tools/server/server-queue.cpp +++ b/tools/server/server-queue.cpp @@ -114,16 +114,17 @@ void server_queue::pop_deferred_task(int id_slot) { void server_queue::wait_until_no_sleep() { std::unique_lock 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 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 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 lock(mutex_results); running = false; condition_results.notify_all(); } @@ -557,6 +579,14 @@ server_task_result_ptr server_response_reader::next(const std::function 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(); + res->err_type = ERROR_TYPE_UNAVAILABLE; + res->err_msg = "server is shutting down"; + return res; + } // timeout, check stop condition if (should_stop()) { return nullptr; diff --git a/tools/server/server-queue.h b/tools/server/server-queue.h index f9d66be64..e40148fc8 100644 --- a/tools/server/server-queue.h +++ b/tools/server/server-queue.h @@ -2,6 +2,7 @@ #include "server-task.h" +#include #include #include #include @@ -16,6 +17,9 @@ struct server_queue { private: int id = 0; bool running = false; + // set by terminate() before it takes mutex_tasks, so a loop blocked under that mutex (e.g. in a + // VRAM arbiter token wait) can see the shutdown and bail out + std::atomic stopping{false}; bool sleeping = false; bool req_stop_sleeping = false; int64_t time_last_task = 0; @@ -46,6 +50,7 @@ private: std::function callback_new_task; std::function callback_update_slots; std::vector> callback_sleeping_state; + std::function should_yield_cb; public: ~server_queue() { worker_stop(); } @@ -82,6 +87,11 @@ public: // end the start_loop routine void terminate(); + // true once terminate() was called; safe from any thread, including under mutex_tasks + bool is_stopping() const { + return stopping.load(); + } + /** * Main loop consists of these steps: * - Wait until a new task arrives @@ -132,6 +142,14 @@ public: callback_update_slots = std::move(callback); } + // Register a predicate asking the loop to sleep (release VRAM) as soon as it is idle - used by + // the VRAM arbiter to check whether another process waits for the GPU token. + // Called on the start_loop() thread while holding mutex_tasks, so it must not block or post + // tasks. While it is set, the idle wait polls faster, so the loop reacts without a notify. + void on_should_yield(std::function callback) { + should_yield_cb = std::move(callback); + } + // Register callback for sleeping state change; multiple callbacks are allowed // for example: register order cb0, cb1, cb2 // entering sleep: queue.sleeping = true --> cb0(true) --> cb1(true) --> cb2(true) @@ -198,8 +216,13 @@ public: // (used by router mode) void broadcast(server_task_result_ptr && result); - // terminate the waiting loop + // terminate the waiting loop: pending and later readers get an error instead of a result void terminate(); + + bool is_running() { + std::unique_lock lock(mutex_results); + return running; + } }; // RAII wrapper to make working with server_queue and server_response easier diff --git a/tools/server/server.cpp b/tools/server/server.cpp index e022355dc..83ecfd66d 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -24,11 +25,22 @@ #if defined(_WIN32) #include +#else +#include +#include #endif static std::function shutdown_handler; static std::atomic_flag is_terminating = ATOMIC_FLAG_INIT; +#if !defined(_WIN32) +// The handler can interrupt the start_loop() thread while it holds server_queue::mutex_tasks (e.g. +// in the sleeping callbacks, during a VRAM arbiter release or token wait), so it must not run +// shutdown_handler itself: terminate() takes that mutex and the thread would deadlock on itself. +// It only writes the signal number here; shutdown_handler runs on a dedicated thread. +static int shutdown_pipe[2] = { -1, -1 }; +#endif + static inline void signal_handler(int signal) { if (is_terminating.test_and_set()) { // in case it hangs, we can force terminate the server by hitting Ctrl+C twice @@ -37,9 +49,48 @@ static inline void signal_handler(int signal) { exit(1); } +#if !defined(_WIN32) + if (shutdown_pipe[1] >= 0) { + const char sig = (char) signal; + const ssize_t res = write(shutdown_pipe[1], &sig, 1); // async-signal-safe + (void) res; + return; + } +#endif shutdown_handler(signal); } +#if !defined(_WIN32) +// runs shutdown_handler for signal_handler; joined (after a 0 byte) when the instance returns +struct shutdown_thread { + std::thread thread; + + void start() { + if (pipe(shutdown_pipe) != 0) { + return; // fall back to calling shutdown_handler from the signal handler + } + fcntl(shutdown_pipe[0], F_SETFD, FD_CLOEXEC); // not inherited by spawned tools / MCP servers + fcntl(shutdown_pipe[1], F_SETFD, FD_CLOEXEC); + thread = std::thread([]() { + char sig = 0; + while (read(shutdown_pipe[0], &sig, 1) < 0 && errno == EINTR) {} + if (sig != 0) { + shutdown_handler(sig); + } + }); + } + + ~shutdown_thread() { + if (thread.joinable()) { + const char sig = 0; + const ssize_t res = write(shutdown_pipe[1], &sig, 1); + (void) res; + thread.join(); + } + } +}; +#endif + // how the server is run; everything is on when it is the llama-server binary struct server_run_opts { bool install_signal_handlers = true; // off when embedded in llama-cli, which handles them itself @@ -776,7 +827,13 @@ static int server_run_instance(common_params & params, server_role & role, commo ctx_server.terminate(); }; +#if !defined(_WIN32) + shutdown_thread sig_thread; // declared after ctx_server & co, so joined before they are destroyed +#endif if (opts.install_signal_handlers) { +#if !defined(_WIN32) + sig_thread.start(); +#endif server_install_signal_handlers(); }