llama, ggml: release and restore everything a context holds in VRAM on demand (F4, F8)
Library side of the on-demand VRAM time-sharing: weights, KV/recurrent state, MoE cache, scheduler and backend scratch (ggml_backend_free_scratch); guards for released buffers and cold teardown. This commit holds the src/, ggml/ and include/ parts of the commits below; their tools/mtmd and tools/server parts are in the next two commits. Squashed from 11 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. ---- llama: guard buffer iteration against released device buffers (was9119ec6e8) release_device_weights()/release_device_buffers() leave a null buffer in ctxs_bufs while the device memory is released for on-demand VRAM sharing. The memory-breakdown / total_size / clear paths iterated these and called ggml_backend_buffer_get_size()/get_type()/clear() on the null buffer, tripping GGML_ASSERT(buffer) and aborting on shutdown of a cold model. Skip null buffers in llama_model::memory_breakdown and llama_kv_cache::{memory_breakdown, total_size,clear}. ---- server: also free the compute-graph scheduler on KV eviction (was298da30d9) Under LLAMA_SLEEP_EVICT_KV a cold model still held the scheduler's worst-case compute buffer (hundreds of MiB, e.g. ~700 MiB for gemma-26B) plus the resident experts. release_device(evict_kv) now also frees the sched (sched.reset() + sched_need_reserve), and restore_device() rebuilds it via sched_reserve(), so a fully-evicted model holds essentially no VRAM (gemma cold: 7147 -> 51 MiB). Trades a heavier re-warm (weights+KV H2D + sched reserve) for the freed VRAM; weights-only mode is unchanged (fast switch, keeps KV+compute). ---- llama: evict recurrent/SSM state on device release (wasb4a09407a) The recurrent (SSM/conv) state of hybrid models (e.g. Qwen3.5) was left resident when a model's device buffers were released for on-demand VRAM sharing - llama_memory_recurrent::release_device_buffers() was a no-op default. Implement it (and restore_device_buffers) with the same capture-host-shadow / free / reallocate pattern as llama_kv_cache, so llama_memory_hybrid now evicts both its attention KV and its recurrent state. The state is read-write, so its shadow is recaptured on every release. ---- ggml: add ggml_backend_free_scratch to drop Vulkan compute prealloc (was7992a094d) Add an optional backend interface method free_scratch (with a public ggml_backend_free_scratch wrapper) that frees transient/scratch device memory a backend holds outside of any allocated buffer, keeping the backend usable - the scratch is reallocated lazily on the next compute. Implement it for the Vulkan backend (ggml_backend_vk_free_scratch): free the prealloc_x/y/split_k/add_rms_partials and sync_staging device buffers and reset their sizes, so an idle/cold model does not hold the vision or matmul compute preallocations in VRAM. All other backends leave the hook null (no-op). ---- llama: free backend compute scratch on cold; guard memory_breakdown (was392787dee) On device release with KV eviction, also call ggml_backend_free_scratch() on each backend so a cold model drops its Vulkan compute preallocations (reallocated lazily on the next compute via restore). Also guard llama_context::memory_breakdown() against a freed scheduler: evict_kv release resets sched to null, so a cold model that is then torn down (e.g. terminated by the process manager) hit GGML_ASSERT(sched) in ggml_backend_sched_get_buffer_type. Skip the compute-buffer accounting when sched is null. ---- llama: skip the compute-buffer size check when the context is cold (was9df58a961) release_device(evict_kv) drops the scheduler, so a context evicted by the VRAM arbiter and then destroyed reaches the destructor with a null sched. The upstream "compute buffer size matches expectation" loop calls ggml_backend_sched_get_buffer_size() unconditionally, whose GGML_ASSERT(sched) then aborts: the server exits 134 instead of 0 on every shutdown taken while cold, which under llama-swap makes an ordinary stop look like a crashed child and leaves a ggml backtrace in the log each time. It also skipped the rest of the destructor, so the cold teardown path had never actually run to completion. Guard at the call site rather than relaxing the assert - the assert is right, and every other caller reserves the scheduler first. Same shape as the null guards in synchronize(), memory_breakdown() and the released-buffer iteration. The loop is a diagnostic size comparison, already reported by sched_reserve() at load, so skipping it when cold loses nothing. ---- llama: release/restore the MoE cache with the device weights (was1ee9747e1) The MoE cache (--moe-cache-mib, #29887) keeps the most recently used host experts in device banks. The on-demand VRAM path (release_device / restore_device, used by the server VRAM arbiter and the on-demand mmproj path) did not know about it, so its banks were never freed on handoff. Restoring them by reallocation alone would also be wrong: the banks come back zeroed while the slot maps still mark experts as cached, so the model would silently read zero weights. Free the banks on release and empty the cache instead of shadowing it: re-init every LRU, re-point its slot-map pointers at the host slot maps and clear those to -1. The banks are reallocated (which also re-inits their views) and cleared on restore, before the scheduler is rebuilt, and the cache refills from the host experts as before. Release runs in both modes, weights-only and evict_kv. device_resident() now covers the cache too, for the early returns in release/restore, the auto-restore in decode() and llama_context_weights_resident(). ---- 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. ---- llama: do not release CPU extra buffers (CPU_REPACK) on device release (was724a5d637) A model with weights on the CPU device (-dev none / -ngl 0) segfaulted in llama_model::release_device_weights() the first time the VRAM arbiter put it to sleep: CPU_REPACK buffers are not host buffers, so load_tensors marked them releasable, and capturing the shadow called their NULL get_tensor. Reproduced with the production build2fc9f9c35(Qwen3.5-0.8B, -dev none -ngl 0, LLAMA_SLEEP_VRAM_ONLY=1 LLAMA_SLEEP_EVICT_KV=1, force a yield with a waiter on want.lock): exit 139 at the release, before any SIGTERM. The faulting call (rip 0) returned into release_device_weights. Only buffers on a non-CPU device are releasable now. These buffers are in RAM already, so there is nothing to free. Production is not affected: every arbiter model there has its weights on the GPU, and a releasable CPU_REPACK buffer would have crashed it. Found by the --diskcache check, which runs its arbiter cases CPU only. 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
f9e7af6e72
commit
7065a34302
21 files changed
+667
-18
No files matched your search
+129
-1
@@ -1388,6 +1388,16 @@ struct llama_model::impl {
|
||||
// contexts where the model tensors metadata is stored as well as the corresponding buffers:
|
||||
std::vector<std::pair<ggml_context_ptr, std::vector<ggml_backend_buffer_ptr>>> ctxs_bufs;
|
||||
|
||||
// on-demand device (VRAM) weight residency: per-ctxs_bufs slot describing whether the
|
||||
// device weight buffer can be freed and rebuilt from a host shadow (see release/restore_device_weights)
|
||||
struct weight_release_slot {
|
||||
ggml_backend_buffer_type_t buft = nullptr; // buffer type to reallocate on restore
|
||||
bool releasable = false; // single-buffer alloc-path device (VRAM) buffer
|
||||
bool resident = true; // currently allocated on device
|
||||
std::vector<uint8_t> shadow; // host copy, captured lazily on first release
|
||||
};
|
||||
std::vector<weight_release_slot> weight_release; // parallel to ctxs_bufs
|
||||
|
||||
buft_list_t cpu_buft_list;
|
||||
std::map<ggml_backend_dev_t, buft_list_t> gpu_buft_list;
|
||||
|
||||
@@ -2129,8 +2139,9 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
|
||||
|
||||
// a lazy context is mapped whatever the load mode, but the memory-fit pass maps nothing
|
||||
const bool is_lazy_mapped = ctx_key.lazy && !ml.no_alloc;
|
||||
const bool host_ptr_path = (ml.use_mmap || is_lazy_mapped) && use_mmap_buffer && buffer_from_host_ptr_supported && is_default_buft;
|
||||
|
||||
if ((ml.use_mmap || is_lazy_mapped) && use_mmap_buffer && buffer_from_host_ptr_supported && is_default_buft) {
|
||||
if (host_ptr_path) {
|
||||
GGML_ASSERT(!ml.no_alloc);
|
||||
const size_t max_size = ggml_get_max_tensor_size(ctx);
|
||||
|
||||
@@ -2195,6 +2206,25 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
|
||||
|
||||
pimpl->ctxs_bufs.emplace_back(std::move(ctx_ptr), std::move(bufs));
|
||||
|
||||
// record on-demand release metadata (parallel to ctxs_bufs). Only the single-buffer
|
||||
// alloc path on a device (non-host) buffer can be freed and rebuilt from a host shadow;
|
||||
// the host_ptr path (mmap / lazy), the no_alloc dummy buffers and host (CPU) buffers are
|
||||
// left resident.
|
||||
{
|
||||
llama_model::impl::weight_release_slot slot;
|
||||
auto & last_bufs = pimpl->ctxs_bufs.back().second;
|
||||
if (!host_ptr_path && !ml.no_alloc && last_bufs.size() == 1) {
|
||||
ggml_backend_buffer_t b = last_bufs[0].get();
|
||||
// CPU extra buffers (CPU_REPACK) are not host buffers, but they are in RAM and have no get_tensor
|
||||
ggml_backend_dev_t buft_dev = ggml_backend_buft_get_device(buft);
|
||||
if (b != nullptr && !ggml_backend_buffer_is_host(b) && (buft_dev == nullptr || ggml_backend_dev_type(buft_dev) != GGML_BACKEND_DEVICE_TYPE_CPU)) {
|
||||
slot.releasable = true;
|
||||
slot.buft = buft;
|
||||
}
|
||||
}
|
||||
pimpl->weight_release.push_back(std::move(slot));
|
||||
}
|
||||
|
||||
ctx_bufs.emplace_back(ctx, std::move(buf_ptrs));
|
||||
}
|
||||
|
||||
@@ -2523,6 +2553,7 @@ void llama_model_base::load_tensors_hadamard() {
|
||||
std::vector<ggml_backend_buffer_ptr> buffers;
|
||||
buffers.emplace_back(std::move(buffer));
|
||||
pimpl->ctxs_bufs.emplace_back(std::move(ctx), std::move(buffers));
|
||||
pimpl->weight_release.emplace_back(); // small, left resident
|
||||
rotations.push_back({ block_size, buft, rotation });
|
||||
it = std::prev(rotations.end());
|
||||
}
|
||||
@@ -2568,6 +2599,7 @@ void llama_model_base::load_tensors_hadamard() {
|
||||
std::vector<ggml_backend_buffer_ptr> buffers;
|
||||
buffers.emplace_back(std::move(buffer));
|
||||
pimpl->ctxs_bufs.emplace_back(std::move(ctx), std::move(buffers));
|
||||
pimpl->weight_release.emplace_back(); // small, left resident
|
||||
st = sign_tensors.emplace(key, signs).first;
|
||||
}
|
||||
sign_tensor = st->second;
|
||||
@@ -2598,6 +2630,97 @@ ggml_tensor * llama_model_base::create_tensor(llama_model_loader & ml, const LLM
|
||||
tn, ne, flags);
|
||||
}
|
||||
|
||||
void llama_model::release_device_weights(bool keep_shadow) const {
|
||||
// NOTE: the caller is responsible for synchronizing the backend scheduler first, so that no
|
||||
// compute is in flight referencing these buffers when they are freed.
|
||||
size_t freed = 0;
|
||||
for (size_t i = 0; i < pimpl->ctxs_bufs.size(); ++i) {
|
||||
auto & slot = pimpl->weight_release[i];
|
||||
if (!slot.releasable || !slot.resident) {
|
||||
continue;
|
||||
}
|
||||
ggml_context * ctx = pimpl->ctxs_bufs[i].first.get();
|
||||
ggml_backend_buffer_t buf = pimpl->ctxs_bufs[i].second[0].get();
|
||||
const size_t sz = ggml_backend_buffer_get_size(buf);
|
||||
|
||||
// lazily capture a host shadow of the weights (read-only, so captured only once).
|
||||
// Store tensor bytes compactly in stable iteration order (independent of buffer layout /
|
||||
// alignment padding) so restore does not depend on the re-allocated offsets matching.
|
||||
// View tensors alias their base, so they are skipped (restored implicitly via their base).
|
||||
if (keep_shadow && slot.shadow.empty()) {
|
||||
size_t total = 0;
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
|
||||
if (t->view_src != nullptr) continue;
|
||||
total += ggml_nbytes(t);
|
||||
}
|
||||
slot.shadow.resize(total);
|
||||
size_t off = 0;
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
|
||||
if (t->view_src != nullptr) continue;
|
||||
const size_t n = ggml_nbytes(t);
|
||||
ggml_backend_tensor_get(t, slot.shadow.data() + off, 0, n);
|
||||
off += n;
|
||||
}
|
||||
}
|
||||
|
||||
// free the device (VRAM) buffer and clear the now-dangling tensor pointers so that
|
||||
// ggml_backend_alloc_ctx_tensors_from_buft reallocates them cleanly on restore
|
||||
pimpl->ctxs_bufs[i].second[0].reset();
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
|
||||
t->buffer = nullptr;
|
||||
t->data = nullptr;
|
||||
}
|
||||
slot.resident = false;
|
||||
freed += sz;
|
||||
}
|
||||
if (freed > 0) {
|
||||
LLAMA_LOG_INFO("%s: released %.2f MiB of device weights\n", __func__, freed / 1024.0 / 1024.0);
|
||||
}
|
||||
}
|
||||
|
||||
bool llama_model::restore_device_weights() const {
|
||||
size_t restored = 0;
|
||||
for (size_t i = 0; i < pimpl->ctxs_bufs.size(); ++i) {
|
||||
auto & slot = pimpl->weight_release[i];
|
||||
if (!slot.releasable || slot.resident) {
|
||||
continue;
|
||||
}
|
||||
ggml_context * ctx = pimpl->ctxs_bufs[i].first.get();
|
||||
ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, slot.buft);
|
||||
if (buf == nullptr) {
|
||||
LLAMA_LOG_ERROR("%s: failed to reallocate device weight buffer (out of VRAM?)\n", __func__);
|
||||
return false;
|
||||
}
|
||||
ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
|
||||
|
||||
// re-upload weights from the compact host shadow, using the same stable iteration order
|
||||
// and view-skipping as the capture above
|
||||
size_t off = 0;
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
|
||||
if (t->view_src != nullptr) continue;
|
||||
const size_t n = ggml_nbytes(t);
|
||||
ggml_backend_tensor_set(t, slot.shadow.data() + off, 0, n);
|
||||
off += n;
|
||||
}
|
||||
pimpl->ctxs_bufs[i].second[0].reset(buf);
|
||||
slot.resident = true;
|
||||
restored += ggml_backend_buffer_get_size(buf);
|
||||
}
|
||||
if (restored > 0) {
|
||||
LLAMA_LOG_INFO("%s: restored %.2f MiB of device weights\n", __func__, restored / 1024.0 / 1024.0);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool llama_model::weights_resident() const {
|
||||
for (const auto & slot : pimpl->weight_release) {
|
||||
if (slot.releasable && !slot.resident) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string llama_model::arch_name() const {
|
||||
return llm_arch_name(arch);
|
||||
}
|
||||
@@ -2659,6 +2782,11 @@ std::map<ggml_backend_buffer_type_t, size_t> llama_model::memory_breakdown() con
|
||||
ret[buft] += ggml_backend_alloc_ctx_tensors_from_buft_size(ctx.get(), buft);
|
||||
} else {
|
||||
for (const auto & buf : bufs) {
|
||||
// buf may be null if the device weights were released for on-demand VRAM sharing
|
||||
// (see release_device_weights); skip it in the breakdown
|
||||
if (!buf) {
|
||||
continue;
|
||||
}
|
||||
// GGML_ASSERT(ggml_backend_buffer_get_base(buf.get()) != nullptr); // multi_buffer does not have a defined base
|
||||
ret[ggml_backend_buffer_get_type(buf.get())] += ggml_backend_buffer_get_size(buf.get());
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user