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 (was cb489f336)

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) (was 3b410b905)

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 (was da03d4c1f)

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 (was b9c57d1c2)

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 (was e457c2fd6)

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 (was 3f61190fd)

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 (was aa1c2b456)

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 (was 33f8b89f9)

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 (was 83cc51c9d)

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 (was fcfadfbbd)

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:
LumpiastyandClaude Opus 5.5 committed 2026-11-23 11:54:10 +01:00
1 parent 08a1743c5d
commit fed49aea5c
4 files changed
+497 -18

No files matched your search

+371 -2
View File
@@ -34,6 +34,8 @@
#include <random>
#include <utility>
#include <fstream>
#include <thread>
#include <atomic>
// fix problem with std::min and std::max
#if defined(_WIN32)
@@ -44,6 +46,16 @@
#include <windows.h>
#endif
// POSIX file locking for the cross-process VRAM arbiter (see vram_share_* below)
#if !defined(_WIN32)
#include <sys/file.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <poll.h>
#include <cerrno>
#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 <arena>/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<bool> vram_cold{true}; // weights currently released
int vram_lock_fd = -1; // fd for <arena>/token.lock
// "want" lock: a process that waits for the token holds <arena>/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;