diff --git a/ggml/include/ggml-backend.h b/ggml/include/ggml-backend.h index afb86338a..99650fe06 100644 --- a/ggml/include/ggml-backend.h +++ b/ggml/include/ggml-backend.h @@ -109,6 +109,11 @@ extern "C" { GGML_API enum ggml_status ggml_backend_graph_compute (ggml_backend_t backend, struct ggml_cgraph * cgraph); GGML_API enum ggml_status ggml_backend_graph_compute_async(ggml_backend_t backend, struct ggml_cgraph * cgraph); + // Free transient/scratch device memory the backend holds outside of any allocated buffer + // (compute preallocations, staging buffers). No-op if the backend does not implement it. + // The backend remains usable; scratch is reallocated lazily on the next compute. + GGML_API void ggml_backend_free_scratch(ggml_backend_t backend); + // NOTE: will be removed, use device version instead GGML_API bool ggml_backend_supports_op(ggml_backend_t backend, const struct ggml_tensor * op); GGML_API bool ggml_backend_supports_buft(ggml_backend_t backend, ggml_backend_buffer_type_t buft); diff --git a/ggml/src/ggml-backend-impl.h b/ggml/src/ggml-backend-impl.h index 545880b06..6dd669388 100644 --- a/ggml/src/ggml-backend-impl.h +++ b/ggml/src/ggml-backend-impl.h @@ -162,6 +162,11 @@ extern "C" { // (optional) sort/optimize the nodes in the graph void (*graph_optimize) (ggml_backend_t backend, struct ggml_cgraph * cgraph, struct ggml_backend_graph_optimize_params * params); + + // (optional) free transient/scratch device memory the backend holds outside of any buffer + // (e.g. compute preallocations and staging buffers). The backend stays usable; the scratch + // is reallocated lazily on the next compute. Used to shrink an idle model's device footprint. + void (*free_scratch) (ggml_backend_t backend); }; struct ggml_backend { diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index d598ca3d8..7d69aedc4 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -775,6 +775,15 @@ void ggml_backend_synchronize(ggml_backend_t backend) { backend->iface.synchronize(backend); } +void ggml_backend_free_scratch(ggml_backend_t backend) { + GGML_ASSERT(backend); + if (backend->iface.free_scratch == NULL) { + return; + } + + backend->iface.free_scratch(backend); +} + ggml_backend_graph_plan_t ggml_backend_graph_plan_create(ggml_backend_t backend, struct ggml_cgraph * cgraph) { GGML_ASSERT(backend); GGML_ASSERT(backend->iface.graph_plan_create != NULL); diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 8ff376a3a..41103e5e7 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -14410,6 +14410,35 @@ static const char * ggml_backend_vk_name(ggml_backend_t backend) { return ctx->name.c_str(); } +// Free the compute-scratch device buffers (prealloc_* and the transfer staging buffer) without +// tearing down the backend (pipelines, command pools, fences and device stay alive). These buffers +// are reallocated lazily by ggml_vk_preallocate_buffers() on the next compute, so this just shrinks +// an idle model's device footprint. Mirrors the buffer-freeing subset of ggml_vk_cleanup(). +static void ggml_backend_vk_free_scratch(ggml_backend_t backend) { + ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; + VK_LOG_DEBUG("ggml_backend_vk_free_scratch(" << ctx->name << ")"); + + // discard any unsubmitted command buffer and wait for in-flight work before freeing + ctx->compute_ctx.reset(); + ggml_vk_synchronize(ctx); + + ggml_vk_destroy_buffer(ctx->prealloc_x); + ggml_vk_destroy_buffer(ctx->prealloc_y); + ggml_vk_destroy_buffer(ctx->prealloc_split_k); + ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials); + ggml_vk_destroy_buffer(ctx->sync_staging); + + ctx->prealloc_y_last_pipeline_used = nullptr; + ctx->prealloc_y_last_tensor_used = nullptr; + ctx->prealloc_y_last_k_padded = false; + + ctx->prealloc_size_x = 0; + ctx->prealloc_size_y = 0; + ctx->prealloc_size_split_k = 0; + ctx->prealloc_size_add_rms_partials = 0; + ctx->prealloc_size_add_rms_partials_offset = 0; +} + void ggml_backend_vk_free(ggml_backend_t backend) { ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")"); @@ -16429,6 +16458,7 @@ static ggml_backend_i ggml_backend_vk_interface = { /* .event_record = */ ggml_backend_vk_event_record, /* .event_wait = */ ggml_backend_vk_event_wait, /* .graph_optimize = */ ggml_vk_graph_optimize, + /* .free_scratch = */ ggml_backend_vk_free_scratch, }; static ggml_guid_t ggml_backend_vk_guid() { diff --git a/include/llama.h b/include/llama.h index 7122143e5..0a5b0b794 100644 --- a/include/llama.h +++ b/include/llama.h @@ -582,6 +582,19 @@ extern "C" { LLAMA_API const struct llama_model * llama_get_model (const struct llama_context * ctx); LLAMA_API llama_memory_t llama_get_memory (const struct llama_context * ctx); + + // On-demand device (VRAM) residency: free the model's GPU weight buffers (keeping a host + // shadow so no reload is needed) to hand VRAM to another model, and rebuild them on demand. + // Any subsequent llama_decode auto-restores. If evict_kv is true, the KV cache device buffers + // are also evicted to a host shadow (for when the KV would not fit alongside the other model), + // at the cost of a D2H/H2D copy of the live KV each cycle; otherwise the KV stays resident. + // Intended for time-sharing a single GPU between several always-loaded models. + LLAMA_API void llama_context_release_device(struct llama_context * ctx, bool evict_kv); + LLAMA_API void llama_context_restore_device(struct llama_context * ctx); + // Free all device buffers (weights, KV, compute) for good, without host copies, e.g. to hand + // the VRAM to another process before exit. The context must not be used for compute afterwards. + LLAMA_API void llama_context_discard_device(struct llama_context * ctx); + LLAMA_API bool llama_context_weights_resident(const struct llama_context * ctx); LLAMA_API enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx); // TODO: rename to llama_get_pooling_type LLAMA_API const struct llama_vocab * llama_model_get_vocab(const struct llama_model * model); diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 07a0dbafc..7b0547cb9 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -635,7 +635,8 @@ llama_context::~llama_context() { synchronize(); // when training, ggml_opt allocates extra buffers through the scheduler, so the sizes no longer match the expectation - if (!model.no_alloc() && !opt_ctx) { + // the scheduler is also gone if the context is destroyed while cold (on-demand VRAM eviction, see release_device) + if (sched && !model.no_alloc() && !opt_ctx) { for (size_t i = 0; i < backend_ptrs.size(); ++i) { ggml_backend_t backend = backend_ptrs[i]; ggml_backend_buffer_type_t buft = backend_buft[i]; @@ -980,6 +981,78 @@ void llama_context::synchronize() { t_compute_start_us = 0; } +bool llama_context::device_resident() const { + return model.weights_resident() && (!moe_cache || moe_cache->resident()); +} + +void llama_context::release_device(bool evict_kv) { + if (!device_resident() && !(evict_kv && !kv_device_evicted)) { + return; + } + // ensure no compute is in flight before freeing the device buffers + synchronize(); + model.release_device_weights(); + // the banks are emptied, not shadowed: restored slot maps must not point at zeroed experts + if (moe_cache) { + moe_cache->release_device(); + } + if (evict_kv && memory && !kv_device_evicted) { + memory->release_device_buffers(); + kv_device_evicted = true; + // also free the scheduler and its worst-case compute buffer (hundreds of MiB) so a cold + // model holds essentially no VRAM. Rebuilt lazily by sched_reserve() on restore. + sched.reset(); + sched_need_reserve = true; + // finally, free each backend's own compute-scratch (Vulkan prealloc/staging buffers, which + // are owned by the backend and survive sched.reset()). Reallocated lazily on next compute. + for (auto & backend : backends) { + ggml_backend_free_scratch(backend.get()); + } + } +} + +void llama_context::discard_device() { + // same as release_device(true), minus the host copies of the weights and the KV + synchronize(); + model.release_device_weights(/*keep_shadow =*/ false); + if (moe_cache) { + moe_cache->release_device(); + } + if (memory) { + memory->release_device_buffers(/*keep_shadow =*/ false); + } + kv_device_evicted = true; + device_discarded = true; + sched.reset(); + sched_need_reserve = true; + for (auto & backend : backends) { + ggml_backend_free_scratch(backend.get()); + } +} + +void llama_context::restore_device() { + GGML_ASSERT(!device_discarded && "device buffers were discarded"); + if (device_resident() && !kv_device_evicted && sched) { + return; + } + model.restore_device_weights(); + if (moe_cache) { + moe_cache->restore_device(); + } + if (kv_device_evicted && memory) { + memory->restore_device_buffers(); + kv_device_evicted = false; + } + // rebuild the scheduler + compute buffer if they were freed on release (evict_kv mode) + if (!sched) { + sched_reserve(); + } + // make sure all weight/KV uploads have completed before any compute reads them + if (sched) { + ggml_backend_sched_synchronize(sched.get()); + } +} + const llama_model & llama_context::get_model() const { return model; } @@ -2164,6 +2237,12 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { return -1; } + // on-demand VRAM: if the weights were released while this model was idle, bring them back + // to the device before building the compute graph + if (!device_resident()) { + restore_device(); + } + const auto & vocab = model.vocab; const auto & hparams = model.hparams; @@ -4130,17 +4209,21 @@ llama_memory_breakdown llama_context::memory_breakdown() const { ret[buft].context += size; } } - if (model.no_alloc()) { - for (size_t i = 0; i < backends.size(); ++i) { - ggml_backend_t backend = backends[i].get(); - ggml_backend_buffer_type_t buft = ggml_backend_sched_get_buffer_type(sched.get(), backend); - ret[buft].compute += backend_buf_exp_size[i]; - } - } else { - for (const auto & backend_ptr : backends) { - ggml_backend_t backend = backend_ptr.get(); - ggml_backend_buffer_type_t buft = ggml_backend_sched_get_buffer_type(sched.get(), backend); - ret[buft].compute += ggml_backend_sched_get_buffer_size(sched.get(), backend); + // the scheduler (and its compute buffers) may have been freed while the model is cold + // (on-demand VRAM eviction, see release_device); it contributes no compute VRAM then. + if (sched) { + if (model.no_alloc()) { + for (size_t i = 0; i < backends.size(); ++i) { + ggml_backend_t backend = backends[i].get(); + ggml_backend_buffer_type_t buft = ggml_backend_sched_get_buffer_type(sched.get(), backend); + ret[buft].compute += backend_buf_exp_size[i]; + } + } else { + for (const auto & backend_ptr : backends) { + ggml_backend_t backend = backend_ptr.get(); + ggml_backend_buffer_type_t buft = ggml_backend_sched_get_buffer_type(sched.get(), backend); + ret[buft].compute += ggml_backend_sched_get_buffer_size(sched.get(), backend); + } } } return ret; @@ -4658,6 +4741,22 @@ void llama_synchronize(llama_context * ctx) { ctx->synchronize(); } +void llama_context_release_device(llama_context * ctx, bool evict_kv) { + ctx->release_device(evict_kv); +} + +void llama_context_restore_device(llama_context * ctx) { + ctx->restore_device(); +} + +void llama_context_discard_device(llama_context * ctx) { + ctx->discard_device(); +} + +bool llama_context_weights_resident(const llama_context * ctx) { + return ctx->device_resident(); +} + float * llama_get_logits(llama_context * ctx) { ctx->synchronize(); diff --git a/src/llama-context.h b/src/llama-context.h index 3e3921c7d..23345b9cf 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -60,6 +60,20 @@ struct llama_context { void synchronize(); + // on-demand device (VRAM) residency: free / rebuild the model's GPU weight buffers so that + // VRAM can be time-shared with another model. release_device() synchronizes first; decode() + // auto-restores when it finds the weights have been released. If evict_kv is set, the KV cache + // device buffers are also evicted to a host shadow (for when the KV would not fit alongside the + // other model) - this adds a D2H/H2D copy of the live KV on each cycle. + void release_device(bool evict_kv = false); + void restore_device(); + // free every device buffer for good, without host copies (before exit). The context must not + // compute again: restore_device() aborts. + void discard_device(); + + // the model weights and the MoE cache are on the device + bool device_resident() const; + const llama_model & get_model() const; const llama_cparams & get_cparams() const; @@ -431,6 +445,11 @@ private: int32_t n_reallocs_same = 0; int32_t n_reallocs_diff = 0; + // on-demand device residency: true while the KV cache device buffers have been evicted to host + bool kv_device_evicted = false; + // set by discard_device(): the device buffers are gone and cannot be restored + bool device_discarded = false; + ggml_backend_t backend_cpu = nullptr; std::vector backends; diff --git a/src/llama-kv-cache-iswa.cpp b/src/llama-kv-cache-iswa.cpp index 8ce8e0165..c4d0d63e2 100644 --- a/src/llama-kv-cache-iswa.cpp +++ b/src/llama-kv-cache-iswa.cpp @@ -264,6 +264,17 @@ void llama_kv_cache_iswa::state_read(llama_io_read_i & io, llama_seq_id seq_id, kv_swa ->state_read(io, seq_id, flags); } +void llama_kv_cache_iswa::release_device_buffers(bool keep_shadow) { + kv_base->release_device_buffers(keep_shadow); + kv_swa->release_device_buffers(keep_shadow); +} + +bool llama_kv_cache_iswa::restore_device_buffers() { + bool ok = kv_base->restore_device_buffers(); + ok = kv_swa->restore_device_buffers() && ok; + return ok; +} + llama_kv_cache * llama_kv_cache_iswa::get_base() const { return kv_base.get(); } diff --git a/src/llama-kv-cache-iswa.h b/src/llama-kv-cache-iswa.h index 65aba2af7..538bcff9a 100644 --- a/src/llama-kv-cache-iswa.h +++ b/src/llama-kv-cache-iswa.h @@ -83,6 +83,9 @@ public: void state_write(llama_io_write_i & io, llama_seq_id seq_id = -1, llama_state_seq_flags flags = 0) const override; void state_read (llama_io_read_i & io, llama_seq_id seq_id = -1, llama_state_seq_flags flags = 0) override; + void release_device_buffers(bool keep_shadow = true) override; + bool restore_device_buffers() override; + // // llama_kv_cache_iswa specific API // diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index fbe422a27..6e4be3771 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -429,7 +429,9 @@ void llama_kv_cache::clear(bool data) { if (data) { for (auto & [_, buf] : ctxs_bufs) { - ggml_backend_buffer_clear(buf.get(), 0); + if (buf) { // may be null if evicted for on-demand VRAM sharing + ggml_backend_buffer_clear(buf.get(), 0); + } } } } @@ -2084,12 +2086,90 @@ size_t llama_kv_cache::total_size() const { size_t size = 0; for (const auto & [_, buf] : ctxs_bufs) { - size += ggml_backend_buffer_get_size(buf.get()); + if (buf) { // may be null if evicted for on-demand VRAM sharing + size += ggml_backend_buffer_get_size(buf.get()); + } } return size; } +void llama_kv_cache::release_device_buffers(bool keep_shadow) { + // NOTE: the caller must have synchronized the backend so nothing references these buffers. + // The KV cache is read-write, so its host shadow is (re)captured fresh on every release. + if (dev_released) { + return; + } + dev_shadows.assign(ctxs_bufs.bufs.size(), device_buffer_shadow{}); + size_t freed = 0; + for (size_t i = 0; i < ctxs_bufs.bufs.size(); ++i) { + ggml_context * ctx = ctxs_bufs.bufs[i].first.get(); + ggml_backend_buffer_t buf = ctxs_bufs.bufs[i].second.get(); + if (buf == nullptr || ggml_backend_buffer_is_host(buf) || ggml_backend_buffer_get_size(buf) == 0) { + continue; // only real device (VRAM) buffers are evictable + } + auto & sh = dev_shadows[i]; + sh.releasable = true; + sh.buft = ggml_backend_buffer_get_type(buf); + + // capture live contents compactly in stable iteration order (skip views, which alias a base) + if (keep_shadow) { + 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) { total += ggml_nbytes(t); } + } + sh.data.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, sh.data.data() + off, 0, n); + off += n; + } + } + + freed += ggml_backend_buffer_get_size(buf); + ctxs_bufs.bufs[i].second.reset(); // free the device buffer + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { + t->buffer = nullptr; + t->data = nullptr; + } + } + dev_released = true; + if (freed > 0) { + LLAMA_LOG_INFO("%s: released %.2f MiB of KV cache from device\n", __func__, freed / 1024.0 / 1024.0); + } +} + +bool llama_kv_cache::restore_device_buffers() { + if (!dev_released) { + return true; + } + for (size_t i = 0; i < ctxs_bufs.bufs.size(); ++i) { + auto & sh = dev_shadows[i]; + if (!sh.releasable) { + continue; + } + ggml_context * ctx = ctxs_bufs.bufs[i].first.get(); + ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, sh.buft); + if (buf == nullptr) { + LLAMA_LOG_ERROR("%s: failed to reallocate KV cache device buffer (out of VRAM?)\n", __func__); + return false; + } + 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, sh.data.data() + off, 0, n); + off += n; + } + ctxs_bufs.bufs[i].second.reset(buf); + } + dev_released = false; + dev_shadows.clear(); // recaptured on next release + return true; +} + size_t llama_kv_cache::size_k_bytes() const { size_t size_k_bytes = 0; diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 1b40f6fc4..59c71d6ec 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -153,6 +153,10 @@ public: void state_write(llama_io_write_i & io, llama_seq_id seq_id = -1, llama_state_seq_flags flags = 0) const override; void state_read (llama_io_read_i & io, llama_seq_id seq_id = -1, llama_state_seq_flags flags = 0) override; + // on-demand device (VRAM) residency (see llama_memory_i) + void release_device_buffers(bool keep_shadow = true) override; + bool restore_device_buffers() override; + // // llama_kv_cache specific API // @@ -320,6 +324,16 @@ private: // ggml contexts for the KV cache along with the allocated backend buffers: llama_memory_bufs ctxs_bufs; + // on-demand device eviction: host shadow of each device buffer's live contents (re-captured on + // every release since the KV is read-write), plus the buffer type needed to reallocate it. + struct device_buffer_shadow { + ggml_backend_buffer_type_t buft = nullptr; + bool releasable = false; // device (VRAM) buffer that was freed + std::vector data; // captured tensor bytes (compact, iteration order) + }; + std::vector dev_shadows; // parallel to ctxs_bufs + bool dev_released = false; + // the current index from where we start searching for a free slot in the ring buffer of KV cells (see find_slot()) // note: this is not part of the KV state and it's only used to speed-up the find_slot() method std::vector v_heads; diff --git a/src/llama-memory-hybrid.cpp b/src/llama-memory-hybrid.cpp index 7d3b27908..18a1b01bd 100644 --- a/src/llama-memory-hybrid.cpp +++ b/src/llama-memory-hybrid.cpp @@ -206,6 +206,18 @@ void llama_memory_hybrid::state_read(llama_io_read_i & io, llama_seq_id seq_id, } } +void llama_memory_hybrid::release_device_buffers(bool keep_shadow) { + // evict both the attention KV (grows with context) and the recurrent/SSM state + mem_attn->release_device_buffers(keep_shadow); + mem_recr->release_device_buffers(keep_shadow); +} + +bool llama_memory_hybrid::restore_device_buffers() { + bool ok = mem_attn->restore_device_buffers(); + ok = mem_recr->restore_device_buffers() && ok; + return ok; +} + llama_kv_cache * llama_memory_hybrid::get_mem_attn() const { return mem_attn.get(); } diff --git a/src/llama-memory-hybrid.h b/src/llama-memory-hybrid.h index 2b4d1269c..c5b66e304 100644 --- a/src/llama-memory-hybrid.h +++ b/src/llama-memory-hybrid.h @@ -76,6 +76,9 @@ public: void state_write(llama_io_write_i & io, llama_seq_id seq_id = -1, llama_state_seq_flags flags = 0) const override; void state_read (llama_io_read_i & io, llama_seq_id seq_id = -1, llama_state_seq_flags flags = 0) override; + void release_device_buffers(bool keep_shadow = true) override; + bool restore_device_buffers() override; + // // llama_memory_hybrid specific API // diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index 2bb8ef18c..7ad79c48a 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -156,7 +156,9 @@ void llama_memory_recurrent::clear(bool data) { if (data) { for (auto & [_, buf] : ctxs_bufs) { - ggml_backend_buffer_clear(buf.get(), 0); + if (buf) { // may be null if evicted for on-demand VRAM sharing + ggml_backend_buffer_clear(buf.get(), 0); + } } } @@ -738,12 +740,89 @@ bool llama_memory_recurrent::is_empty() const { size_t llama_memory_recurrent::total_size() const { size_t size = 0; for (const auto & [_, buf] : ctxs_bufs) { - size += ggml_backend_buffer_get_size(buf.get()); + if (buf) { // may be null if evicted for on-demand VRAM sharing + size += ggml_backend_buffer_get_size(buf.get()); + } } return size; } +void llama_memory_recurrent::release_device_buffers(bool keep_shadow) { + // Same mechanism as llama_kv_cache: the recurrent (SSM/conv) state is read-write, so its host + // shadow is (re)captured on every release. The caller must have synchronized the backend. + if (dev_released) { + return; + } + dev_shadows.assign(ctxs_bufs.bufs.size(), device_buffer_shadow{}); + size_t freed = 0; + for (size_t i = 0; i < ctxs_bufs.bufs.size(); ++i) { + ggml_context * ctx = ctxs_bufs.bufs[i].first.get(); + ggml_backend_buffer_t buf = ctxs_bufs.bufs[i].second.get(); + if (buf == nullptr || ggml_backend_buffer_is_host(buf) || ggml_backend_buffer_get_size(buf) == 0) { + continue; + } + auto & sh = dev_shadows[i]; + sh.releasable = true; + sh.buft = ggml_backend_buffer_get_type(buf); + + if (keep_shadow) { + 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) { total += ggml_nbytes(t); } + } + sh.data.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, sh.data.data() + off, 0, n); + off += n; + } + } + + freed += ggml_backend_buffer_get_size(buf); + ctxs_bufs.bufs[i].second.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; + } + } + dev_released = true; + if (freed > 0) { + LLAMA_LOG_INFO("%s: released %.2f MiB of recurrent state from device\n", __func__, freed / 1024.0 / 1024.0); + } +} + +bool llama_memory_recurrent::restore_device_buffers() { + if (!dev_released) { + return true; + } + for (size_t i = 0; i < ctxs_bufs.bufs.size(); ++i) { + auto & sh = dev_shadows[i]; + if (!sh.releasable) { + continue; + } + ggml_context * ctx = ctxs_bufs.bufs[i].first.get(); + ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, sh.buft); + if (buf == nullptr) { + LLAMA_LOG_ERROR("%s: failed to reallocate recurrent device buffer (out of VRAM?)\n", __func__); + return false; + } + 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, sh.data.data() + off, 0, n); + off += n; + } + ctxs_bufs.bufs[i].second.reset(buf); + } + dev_released = false; + dev_shadows.clear(); + return true; +} + size_t llama_memory_recurrent::size_r_bytes() const { size_t size_r_bytes = 0; diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h index 6442fc1c1..924c29e62 100644 --- a/src/llama-memory-recurrent.h +++ b/src/llama-memory-recurrent.h @@ -67,6 +67,10 @@ public: void state_write(llama_io_write_i & io, llama_seq_id seq_id = -1, llama_state_seq_flags flags = 0) const override; void state_read (llama_io_read_i & io, llama_seq_id seq_id = -1, llama_state_seq_flags flags = 0) override; + // on-demand device (VRAM) residency (see llama_memory_i) + void release_device_buffers(bool keep_shadow = true) override; + bool restore_device_buffers() override; + uint32_t head = 0; // the location where the batch will be placed in the cache (see find_slot()) uint32_t size = 0; // total number of cells, shared across all sequences uint32_t used = 0; // used cells (i.e. at least one seq_id) @@ -131,6 +135,16 @@ private: // true if no layers - can happen if the layer filter removes all layers bool is_empty() const; + // on-demand device eviction (see release_device_buffers): host shadow of each device buffer's + // live contents (recaptured on every release since the recurrent state is read-write) + struct device_buffer_shadow { + ggml_backend_buffer_type_t buft = nullptr; + bool releasable = false; + std::vector data; + }; + std::vector dev_shadows; // parallel to ctxs_bufs + bool dev_released = false; + size_t total_size() const; size_t size_r_bytes() const; diff --git a/src/llama-memory.cpp b/src/llama-memory.cpp index 80099e76a..27528eea4 100644 --- a/src/llama-memory.cpp +++ b/src/llama-memory.cpp @@ -100,6 +100,9 @@ ggml_backend_buffer_t llama_memory_bufs::emplace(ggml_context_ptr ctx, ggml_back std::map llama_memory_bufs::memory_breakdown() const { std::map ret; for (const auto & [ctx, buf] : bufs) { + if (!buf) { // may be null if evicted for on-demand VRAM sharing + continue; + } ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(buf.get()); if (no_alloc) { diff --git a/src/llama-memory.h b/src/llama-memory.h index 37d01ed11..c3ea12aeb 100644 --- a/src/llama-memory.h +++ b/src/llama-memory.h @@ -156,6 +156,17 @@ struct llama_memory_i { virtual void state_write(llama_io_write_i & io, llama_seq_id seq_id = -1, llama_state_seq_flags flags = 0) const = 0; virtual void state_read (llama_io_read_i & io, llama_seq_id seq_id = -1, llama_state_seq_flags flags = 0) = 0; + + // + // on-demand device (VRAM) residency + // + + // Free this memory's device (VRAM) buffers to a host shadow and rebuild them on demand, to + // hand VRAM to another model while keeping the cached data (no re-prefill). The caller must + // have synchronized the backend first. Default: no-op (the memory stays resident). + // keep_shadow = false frees the buffers for good (before exit): no host copy, no restore. + virtual void release_device_buffers(bool /*keep_shadow*/ = true) {} + virtual bool restore_device_buffers() { return true; } }; using llama_memory_ptr = std::unique_ptr; diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 06eb7c929..45610c765 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -1388,6 +1388,16 @@ struct llama_model::impl { // contexts where the model tensors metadata is stored as well as the corresponding buffers: std::vector>> 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 shadow; // host copy, captured lazily on first release + }; + std::vector weight_release; // parallel to ctxs_bufs + buft_list_t cpu_buft_list; std::map 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 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 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 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()); } diff --git a/src/llama-model.h b/src/llama-model.h index eae5c6848..87023c1f7 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -1055,6 +1055,14 @@ struct llama_model { // same, for the keys of the lightning indexer virtual llama_rope_params get_rope_params_indexer(const llama_cparams & cparams, int il) const; + // on-demand device (VRAM) weight residency: free the GPU weight buffers (keeping a host + // shadow) and rebuild them on demand. Used to time-share VRAM between models without + // reloading or losing the KV cache. release_device_weights() requires the caller to have + // synchronized the backend scheduler first. + void release_device_weights(bool keep_shadow = true) const; + bool restore_device_weights() const; + bool weights_resident() const; + float get_rope_freq_base (const llama_cparams & cparams, int il) const; float get_rope_freq_scale(const llama_cparams & cparams, int il) const; diff --git a/src/llama-moe-cache.cpp b/src/llama-moe-cache.cpp index ba35af021..7fffd4ff4 100644 --- a/src/llama-moe-cache.cpp +++ b/src/llama-moe-cache.cpp @@ -369,6 +369,7 @@ struct llama_moe_cache::impl { static constexpr int64_t max_batch = 32; int32_t n_expert_used; + bool no_alloc; stats stats_small; // up to 8 tokens per ubatch stats stats_large; @@ -400,7 +401,7 @@ struct llama_moe_cache::impl { ggml_context_ptr ctx_views; impl(const llama_model & model, bool no_alloc, const std::vector & backends, const std::vector & bufts, size_t size, float cpu_share) : - n_expert_used(model.hparams.n_expert_used_max()), layers(model.layers.size()), cpu_share(std::clamp(cpu_share, 0.0f, 1.0f)) { + n_expert_used(model.hparams.n_expert_used_max()), no_alloc(no_alloc), layers(model.layers.size()), cpu_share(std::clamp(cpu_share, 0.0f, 1.0f)) { for (size_t i = 0; i < backends.size(); ++i) { const auto dev_type = ggml_backend_dev_type(ggml_backend_get_device(backends[i])); if (dev_type == GGML_BACKEND_DEVICE_TYPE_GPU || dev_type == GGML_BACKEND_DEVICE_TYPE_IGPU) { @@ -861,6 +862,90 @@ struct llama_moe_cache::impl { return true; } + // on-demand VRAM: free the banks and forget the cached experts, the slot maps all read -1 again + void release_device() { + if (no_alloc) { + return; + } + size_t freed = 0; + for (device & d : devices) { + if (!d.buf) { + continue; + } + freed += ggml_backend_buffer_get_size(d.buf.get()); + d.buf.reset(); + for (ggml_tensor * t = ggml_get_first_tensor(d.ctx.get()); t != nullptr; t = ggml_get_next_tensor(d.ctx.get(), t)) { + t->buffer = nullptr; + t->data = nullptr; + } + } + invalidate(); + if (freed > 0) { + LLAMA_LOG_INFO("%s: released %.2f MiB of MoE cache\n", __func__, freed/1024.0/1024.0); + } + } + + // the banks come back empty, so the slot maps stay invalidated + bool restore_device() { + if (no_alloc) { + return true; + } + size_t restored = 0; + for (device & d : devices) { + if (!d.ctx || d.buf) { + continue; + } + // also re-inits the views of the banks + d.buf.reset(ggml_backend_alloc_ctx_tensors_from_buft(d.ctx.get(), d.buft)); + if (!d.buf) { + LLAMA_LOG_ERROR("%s: failed to reallocate the MoE cache buffer (out of VRAM?)\n", __func__); + return false; + } + ggml_backend_buffer_clear(d.buf.get(), 0); + ggml_backend_buffer_set_usage(d.buf.get(), GGML_BACKEND_BUFFER_USAGE_WEIGHTS); + d.buf_size = ggml_backend_buffer_get_size(d.buf.get()); + restored += d.buf_size; + } + if (restored > 0) { + LLAMA_LOG_INFO("%s: restored %.2f MiB of MoE cache\n", __func__, restored/1024.0/1024.0); + } + return true; + } + + bool resident() const { + for (const device & d : devices) { + if (d.ctx && !d.buf) { + return false; + } + } + return true; + } + + // empty every LRU and mark all experts as not cached + void invalidate() { + if (buf_host) { + ggml_backend_buffer_clear(buf_host.get(), 0xff); // the CPU maps and the unused slot maps are -1 + } + for (group & g : groups) { + if (g.n_slots == 0) { + continue; + } + // start from a fresh LRU: init() does not reset all of its state (n_filled, the scratch vectors) + g.lru = moe_cache_lru(); + g.lru.init((int32_t) layers.size(), (int32_t) g.ref[0]->ne[2], g.n_slots); + for (int32_t il : g.layers) { + layer & l = layers[il]; + if (l.slot_map != nullptr) { + int32_t * slots = (int32_t *) l.slot_map->data; + std::fill(slots, slots + l.slot_map->ne[1], g.lru.empty); // not cached + g.lru.slot_map[il] = slots; + } + l.cpu_experts.clear(); + l.cpu_acc = 0; + } + } + } + void log_stats() const { auto log = [](const char * name, const stats & st) { const size_t n = st.hits + st.misses; @@ -970,6 +1055,18 @@ int64_t llama_moe_cache::copy_experts(ggml_backend_t backend, const ggml_tensor return pimpl->copy_experts(backend, w, dst, e, last); } +void llama_moe_cache::release_device() { + pimpl->release_device(); +} + +bool llama_moe_cache::restore_device() { + return pimpl->restore_device(); +} + +bool llama_moe_cache::resident() const { + return pimpl->resident(); +} + std::map llama_moe_cache::memory_breakdown() const { std::map res; for (const auto & d : pimpl->devices) { diff --git a/src/llama-moe-cache.h b/src/llama-moe-cache.h index 833eac360..ed11fb81e 100644 --- a/src/llama-moe-cache.h +++ b/src/llama-moe-cache.h @@ -60,6 +60,12 @@ public: // returns the number of experts copied, 0 if expert e is not in the cache int64_t copy_experts(ggml_backend_t backend, const ggml_tensor * w, ggml_tensor * dst, int64_t e, int64_t last); + // on-demand VRAM: free the device banks and empty the cache, the caller must synchronize first + void release_device(); + // reallocate the banks empty, returns false if out of memory + bool restore_device(); + bool resident() const; + std::map memory_breakdown() const; private: