From 7786e2cbfb5dc6a9f89bf6a526d65d2c7cf4dd91 Mon Sep 17 00:00:00 2001 From: Mustafa Cavus Date: Thu, 3 Dec 2026 03:15:58 +0100 Subject: [PATCH 1/6] openvino: add GGML_OPENVINO_SPILL_RESIDENT to cap the spilled weights kept in RAM Assisted-by: Claude Opus 5.5 --- .../src/ggml-openvino/ggml-openvino-extra.cpp | 1 + ggml/src/ggml-openvino/ggml-openvino.cpp | 193 ++++++++++++++++++ 2 files changed, 194 insertions(+) diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 4a9be2968686..a1381437f08e 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -129,6 +129,7 @@ constexpr env_var env_vars[] = { {"GGML_OPENVINO_DEVICE", env_type::STR}, {"GGML_OPENVINO_CACHE_DIR", env_type::STR}, {"GGML_OPENVINO_SPILL_DIR", env_type::STR}, + {"GGML_OPENVINO_SPILL_RESIDENT", env_type::STR}, {"GGML_OPENVINO_DEBUG_NODE", env_type::STR}, {"GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR", env_type::STR}, {"GGML_OPENVINO_NPU_COMPILE_CONFIG", env_type::STR}, diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index a89f476af720..8fe236ec96bb 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -12,6 +12,8 @@ #include #include +#include +#include #include #include #include @@ -33,7 +35,9 @@ #include #include #include +#include #include +#include #include #ifdef _WIN32 @@ -67,6 +71,131 @@ // ===================================================== namespace { +#ifdef __linux__ +// GGML_OPENVINO_SPILL_RESIDENT: keep at most a budget of a spilled weight buffer (GGML_OPENVINO_SPILL_DIR) in RAM. +// Spilled pages are file-backed, but the kernel only evicts them under memory pressure, so on a machine with free +// RAM the whole buffer stays resident. A thread writes the dirty pages to the file and drops them: after every half +// budget of weight writes while the model loads, and whenever the resident part exceeds the budget while +// compile_model reads the weights back. It checks less often once nothing needs trimming. +class spill_resident_limiter { + public: + spill_resident_limiter(void * data, size_t size, size_t budget) : + data_(data), size_(size), budget_(budget), page_(static_cast(sysconf(_SC_PAGESIZE))) { + thread_ = std::thread([this] { run(); }); + } + + ~spill_resident_limiter() { + { + std::lock_guard lock(wake_mutex_); + stop_ = true; + } + wake_.notify_all(); + thread_.join(); + } + + // Called after a write into the buffer. Written pages are resident, so after every budget / 2 bytes the thread + // pages out without measuring. Writing the pages to disk takes as long as converting them, so it runs alongside. + void note_write(size_t bytes) { + if ((written_ += bytes) >= budget_ / 2) { + written_ = 0; + { + std::lock_guard lock(wake_mutex_); + page_out_requested_ = true; + } + wake_.notify_all(); + } + } + + private: + // Estimated from a sample: mincore looks up every page in the page cache, which takes ~65 ms for 7 GB. + size_t resident_bytes() { + constexpr size_t run = 16, stride = 1024; // pages + unsigned char pages[run]; + size_t sampled = 0, resident = 0; + for (size_t off = 0; off < size_; off += stride * page_) { + const size_t len = std::min(run * page_, size_ - off); + const size_t n = (len + page_ - 1) / page_; + if (mincore(static_cast(data_) + off, len, pages) != 0) { + return 0; + } + for (size_t i = 0; i < n; i++) { + resident += pages[i] & 1; + } + sampled += n; + } + return sampled ? static_cast(double(resident) / sampled * size_) : 0; + } + + void trim() { + std::lock_guard lock(trim_mutex_); + if (resident_bytes() > budget_) { + page_out(); + } + } + + void page_out() { + // dirty file pages cannot be dropped until written back + msync(data_, size_, MS_SYNC); +# ifdef MADV_PAGEOUT + madvise(data_, size_, MADV_PAGEOUT); +# else + madvise(data_, size_, MADV_DONTNEED); // unmaps; the clean pages stay reclaimable page cache +# endif + last_trim_ = std::chrono::steady_clock::now(); + } + + void run() { + std::unique_lock lock(wake_mutex_); + while (!stop_) { + const bool recent = std::chrono::steady_clock::now() - last_trim_.load() < std::chrono::seconds(10); + wake_.wait_for(lock, recent ? std::chrono::milliseconds(50) : std::chrono::milliseconds(200), + [this] { return stop_ || page_out_requested_; }); + if (stop_) { + break; + } + const bool requested = std::exchange(page_out_requested_, false); + lock.unlock(); + if (requested) { + std::lock_guard trim_lock(trim_mutex_); + page_out(); + } else { + trim(); + } + lock.lock(); + } + } + + void * data_; + size_t size_; + size_t budget_; + size_t page_; + std::atomic written_{0}; + std::atomic last_trim_{std::chrono::steady_clock::now()}; + std::mutex trim_mutex_; + std::mutex wake_mutex_; + std::condition_variable wake_; + bool stop_ = false; + bool page_out_requested_ = false; + std::thread thread_; +}; + +// GGML_OPENVINO_SPILL_RESIDENT as bytes: "%" of the buffer size, or "" MiB. 0 = no limit. +static size_t ggml_openvino_spill_resident_budget(size_t buffer_size) { + const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_RESIDENT"); + if (v == nullptr || *v == '\0') { + return 0; + } + char * end = nullptr; + const double x = std::strtod(v, &end); + if (end == v || !(x > 0)) { // also rejects NaN + GGML_LOG_WARN("ggml-openvino: GGML_OPENVINO_SPILL_RESIDENT=%s is not a size (\"35%%\" or MiB), ignoring\n", v); + return 0; + } + const double bytes = *end == '%' ? buffer_size * x / 100.0 : x * 1024 * 1024; + return bytes >= double(buffer_size) ? buffer_size : static_cast(bytes); +} +#endif + // Buffer context that manages per-tensor allocations (no contiguous buffer for weights) struct ggml_backend_openvino_buffer_context { int device; @@ -99,6 +228,15 @@ struct ggml_backend_openvino_buffer_context { // data is in the weight buffer registry bool weight_registered = false; +#ifdef __linux__ + // GGML_OPENVINO_SPILL_RESIDENT on a spilled buffer. The limiter starts at the first weight write: the buffer's + // usage is not known when it is allocated, and KV cache and compute buffers must not be paged out. + std::unique_ptr spill_limiter; + size_t spill_budget = 0; + std::once_flag spill_limiter_once; + // source mappings already evicted once under the budget + std::vector evicted_sources; +#endif // One counter for both constructors: the id is part of the weight identity in the graph key, so a host-pointer // buffer and an allocated buffer must never share one. @@ -208,6 +346,9 @@ struct ggml_backend_openvino_buffer_context { spill_size = size; GGML_LOG_INFO("%s: weight buffer spilled to %s (%zu MB, file-backed)\n", __func__, spill_dir, size / 1024 / 1024); +# ifdef __linux__ + spill_budget = ggml_openvino_spill_resident_budget(size); +# endif ov_buffer = std::make_shared(ov::element::u8, ov::Shape{size}, data); } else #endif @@ -265,6 +406,9 @@ struct ggml_backend_openvino_buffer_context { if (kv_on_demand) { ggml_openvino_kv_storage_unregister(data, size); } +#ifdef __linux__ + spill_limiter.reset(); // its thread reads the mapping +#endif if (spill_mapping != nullptr) { #ifdef _WIN32 VirtualFree(spill_mapping, 0, MEM_RELEASE); @@ -719,6 +863,39 @@ static bool ggml_openvino_range_has_locked_pages(uintptr_t first, uintptr_t last } #endif +#ifdef __linux__ +// Before a weight is converted into a spilled buffer with GGML_OPENVINO_SPILL_RESIDENT: start the limiter on the first +// weight, and evict the GGUF once. llama.cpp maps it with MAP_POPULATE, so the whole file is resident before the first +// tensor arrives; after the eviction, each tensor is read from disk when it is converted. +static void ggml_openvino_spill_budget_before_write(ggml_backend_openvino_buffer_context * ctx, const void * data, + size_t size) { + if (ctx->spill_budget == 0) { + return; + } + std::call_once(ctx->spill_limiter_once, [ctx] { + ctx->spill_limiter = + std::make_unique(ctx->spill_mapping, ctx->spill_size, ctx->spill_budget); + GGML_LOG_INFO("%s: at most %zu of %zu MB of the spilled weights stay in RAM (GGML_OPENVINO_SPILL_RESIDENT)\n", + __func__, ctx->spill_budget / 1024 / 1024, ctx->spill_size / 1024 / 1024); + }); +# ifdef MADV_PAGEOUT + const ggml_openvino_source_mapping * mapping = ggml_openvino_find_source_mapping(data, size, ctx->source_mappings); + if (mapping != nullptr && mapping->read_only && + std::find(ctx->evicted_sources.begin(), ctx->evicted_sources.end(), mapping->begin) == + ctx->evicted_sources.end()) { + ctx->evicted_sources.push_back(mapping->begin); + madvise(reinterpret_cast(mapping->begin), mapping->end - mapping->begin, MADV_PAGEOUT); + } + if (mapping != nullptr) { + // read this tensor back in large requests rather than one page fault at a time + const uintptr_t page = (uintptr_t) sysconf(_SC_PAGESIZE); + const uintptr_t first = (uintptr_t) data & ~(page - 1); + madvise(reinterpret_cast(first), (uintptr_t) data + size - first, MADV_WILLNEED); + } +# endif +} +#endif + // A weight's GGUF bytes have been converted into its OpenVINO buffer. Pages of a read-only file mapping are clean and // come back from the file if they are read again, so release them instead of letting them compete with the buffer for // RAM while the model loads. Only whole pages are released, and locked pages (--load-mode mlock) are kept. @@ -746,6 +923,12 @@ static void ggml_openvino_release_source_pages(ggml_backend_openvino_buffer_cont VirtualUnlock(reinterpret_cast(first), last - first); } #elif defined(__linux__) +# ifdef MADV_PAGEOUT + if (ctx->spill_limiter) { + // under a resident budget the GGUF's page cache must go too, not only this process's mapping of it + madvise(reinterpret_cast(first), last - first, MADV_PAGEOUT); + } +# endif // MADV_DONTNEED fails on locked (mlock) memory and leaves it resident madvise(reinterpret_cast(first), last - first, MADV_DONTNEED); #endif @@ -786,6 +969,11 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer memcpy(tensor->data, data, size); return; } +#ifdef __linux__ + if (!ctx->external_memory) { + ggml_openvino_spill_budget_before_write(ctx, data, size); + } +#endif try { auto result = process_weight_tensor(tensor, data, tensor->data); result.weight_node->set_friendly_name(tensor->name); @@ -811,6 +999,11 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer if (!ctx->external_memory) { ggml_openvino_release_source_pages(ctx, data, size); } +#ifdef __linux__ + if (ctx->spill_limiter) { + ctx->spill_limiter->note_write(ggml_nbytes(tensor)); + } +#endif } catch (const std::exception & e) { GGML_LOG_ERROR("%s: failed to process weight tensor for %s: %s\n", __func__, tensor->name, e.what()); memcpy((char *) tensor->data + offset, data, size); From f16e29969357b7ebb65ac48ea0ce70f72990f3f5 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Fri, 4 Dec 2026 00:39:57 +0530 Subject: [PATCH 2/6] openvino: review fixes for GGML_OPENVINO_SPILL_RESIDENT --- ggml/src/ggml-openvino/dev_doc/COOKBOOK.md | 3 + .../dev_doc/OpenVINO-ENV-VARS.md | 1 + .../src/ggml-openvino/ggml-openvino-extra.cpp | 8 + ggml/src/ggml-openvino/ggml-openvino-extra.h | 10 ++ ggml/src/ggml-openvino/ggml-openvino.cpp | 160 +++++++++++++----- ggml/src/ggml-openvino/utils.cpp | 13 +- 6 files changed, 145 insertions(+), 50 deletions(-) diff --git a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md index 1106ed15864e..9b80689ce79d 100644 --- a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md +++ b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md @@ -615,6 +615,9 @@ With the default settings, the GPU and CPU plugins keep their own copy of the we # Use a directory on a local disk (not tmpfs) with free space of about the model size. Can lower prompt speed. export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill mkdir -p $GGML_OPENVINO_SPILL_DIR +# Linux: while the model loads and compiles, keep at most 10% of the spilled weights in RAM, also when RAM is free (or MiB: 2048). +# The first token can come later, while the weights are written to disk. +export GGML_OPENVINO_SPILL_RESIDENT=10% # GPU: nothing to set. The backend already releases its host copy of the weights after compilation # (GGML_OPENVINO_RELEASE_WEIGHTS=1, the default). diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index 10f1f46e12a4..f4d211c9ca89 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -82,6 +82,7 @@ These variables lower the host memory peak. They do not change the output. Comma | `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | unset | When set, the default of `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, of `GGML_OPENVINO_RELEASE_WEIGHTS`. `0` also keeps the host weights on GPU. | | `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. | | `GGML_OPENVINO_SPILL_DIR` | CPU, GPU | String | `not set` | Back the host buffers of the backend (weights, KV cache, compute) with files in this directory, so the kernel can drop their pages. Use real storage, not tmpfs (`/tmp` on many systems). NPU: only with `GGML_OPENVINO_NPU_L0_HOST_TENSORS=0`. Not part of the cache key. Ignored on Windows and in cache-only mode. | +| `GGML_OPENVINO_SPILL_RESIDENT` | CPU, GPU | String | `not set` | With `GGML_OPENVINO_SPILL_DIR`: while the model loads and compiles, keep at most this part of the spilled weights in RAM, also when RAM is free. A percent of the weights (`10%`), or MiB for each weight buffer (`2048`; a large model can have more than one). `0` or a value at least the buffer size sets no limit. Only the weights, not the KV cache or compute buffers. The first token can come later, while the weights are written to disk. Linux 5.4 or later. | | `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least this size get demand-zero host memory instead of Level Zero host memory. | ## NPU plugin properties diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index a1381437f08e..22bd12b494c6 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -243,6 +243,14 @@ std::string checked_env_value(const env_var & var, const char * value) { int number = 0; switch (var.type) { case env_type::STR: + if (std::strcmp(var.name, "GGML_OPENVINO_SPILL_RESIDENT") == 0) { + char * end = nullptr; + const double size = std::strtod(value, &end); + if (end == value || !(size >= 0) || !trim_spaces(*end == '%' ? end + 1 : end).empty()) { + GGML_ABORT("ggml-openvino: %s=%s is not valid, use a percent of the weights (10%%) or MiB (2048)", + var.name, value); + } + } break; case env_type::ENUM: { const std::string wanted = trim_spaces(value); diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index ad0b447de401..7bd63447909c 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -290,6 +290,16 @@ void ggml_openvino_unregister_weight_buffer(const void * data); void ggml_openvino_release_weight_buffers(); bool ggml_openvino_restore_weight_buffers(); +// GGML_OPENVINO_SPILL_RESIDENT: the limiters trim the spilled weights while the model loads and while one of these is +// alive, and sleep otherwise. Hold one around compile_model (it reads the weights back) and around rewriting released +// weights. +struct ggml_openvino_spill_trim_scope { + ggml_openvino_spill_trim_scope(); + ~ggml_openvino_spill_trim_scope(); + ggml_openvino_spill_trim_scope(const ggml_openvino_spill_trim_scope &) = delete; + ggml_openvino_spill_trim_scope & operator=(const ggml_openvino_spill_trim_scope &) = delete; +}; + // Group size of a 2-bit type that is loaded as u2 weights, 0 for other types size_t ggml_openvino_u2_group_size(ggml_type type); diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 8fe236ec96bb..b20bd7c6c5db 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -12,10 +12,10 @@ #include #include -#include -#include #include +#include #include +#include #include #include #include @@ -53,6 +53,11 @@ # include #endif +// GGML_OPENVINO_SPILL_RESIDENT needs MADV_PAGEOUT (Linux 5.4) +#if defined(__linux__) && defined(MADV_PAGEOUT) +# define GGML_OPENVINO_SPILL_LIMITER +#endif + // ===================================================== // OpenVINO Buffer Implementation using ov::Tensor // ===================================================== @@ -71,12 +76,32 @@ // ===================================================== namespace { -#ifdef __linux__ +#ifdef GGML_OPENVINO_SPILL_LIMITER +// Live ggml_openvino_spill_trim_scope objects, how many have started, and when the last one ended. +std::atomic spill_scopes{0}; +std::atomic spill_scope_starts{0}; +std::atomic spill_scope_end_us{0}; + +enum spill_call { SPILL_MINCORE, SPILL_MSYNC, SPILL_PAGEOUT, SPILL_FILE_PAGEOUT, SPILL_FILE_WILLNEED, SPILL_CALLS }; + +// Logs the first failure of each call only: the later ones fail the same way. +void spill_warn_once(spill_call call) { + static const char * names[SPILL_CALLS] = {"mincore", "msync", "madvise(MADV_PAGEOUT)", + "madvise(MADV_PAGEOUT) of the model file", + "madvise(MADV_WILLNEED) of the model file"}; + static std::atomic warned[SPILL_CALLS]; + if (!warned[call].exchange(true)) { + GGML_LOG_WARN("ggml-openvino: GGML_OPENVINO_SPILL_RESIDENT: %s failed: %s\n", names[call], strerror(errno)); + } +} + // GGML_OPENVINO_SPILL_RESIDENT: keep at most a budget of a spilled weight buffer (GGML_OPENVINO_SPILL_DIR) in RAM. // Spilled pages are file-backed, but the kernel only evicts them under memory pressure, so on a machine with free // RAM the whole buffer stays resident. A thread writes the dirty pages to the file and drops them: after every half // budget of weight writes while the model loads, and whenever the resident part exceeds the budget while -// compile_model reads the weights back. It checks less often once nothing needs trimming. +// compile_model reads the weights back (ggml_openvino_spill_trim_scope). Outside of these it sleeps without measuring. +// When a page-out frees almost nothing (pages no longer mapped, e.g. after the GPU weight release), it waits longer +// before the next one, until the next scope starts. class spill_resident_limiter { public: spill_resident_limiter(void * data, size_t size, size_t budget) : @@ -96,6 +121,7 @@ class spill_resident_limiter { // Called after a write into the buffer. Written pages are resident, so after every budget / 2 bytes the thread // pages out without measuring. Writing the pages to disk takes as long as converting them, so it runs alongside. void note_write(size_t bytes) { + last_write_us_ = ggml_time_us(); if ((written_ += bytes) >= budget_ / 2) { written_ = 0; { @@ -107,6 +133,14 @@ class spill_resident_limiter { } private: + static constexpr int64_t active_us = 10 * 1000 * 1000; + + // While the model loads or a ggml_openvino_spill_trim_scope is alive, and for 10 s after. + bool active() const { + const int64_t now = ggml_time_us(); + return spill_scopes > 0 || now - last_write_us_ < active_us || now - spill_scope_end_us < active_us; + } + // Estimated from a sample: mincore looks up every page in the page cache, which takes ~65 ms for 7 GB. size_t resident_bytes() { constexpr size_t run = 16, stride = 1024; // pages @@ -116,7 +150,8 @@ class spill_resident_limiter { const size_t len = std::min(run * page_, size_ - off); const size_t n = (len + page_ - 1) / page_; if (mincore(static_cast(data_) + off, len, pages) != 0) { - return 0; + spill_warn_once(SPILL_MINCORE); + return size_; // unknown: page out } for (size_t i = 0; i < n; i++) { resident += pages[i] & 1; @@ -126,40 +161,49 @@ class spill_resident_limiter { return sampled ? static_cast(double(resident) / sampled * size_) : 0; } - void trim() { - std::lock_guard lock(trim_mutex_); - if (resident_bytes() > budget_) { - page_out(); - } - } - void page_out() { // dirty file pages cannot be dropped until written back - msync(data_, size_, MS_SYNC); -# ifdef MADV_PAGEOUT - madvise(data_, size_, MADV_PAGEOUT); -# else - madvise(data_, size_, MADV_DONTNEED); // unmaps; the clean pages stay reclaimable page cache -# endif - last_trim_ = std::chrono::steady_clock::now(); + if (msync(data_, size_, MS_SYNC) != 0) { + spill_warn_once(SPILL_MSYNC); + } + if (madvise(data_, size_, MADV_PAGEOUT) != 0) { + spill_warn_once(SPILL_PAGEOUT); + } } void run() { + int64_t last_trim_us = 0; + int misses = 0; // measured page-outs in a row that freed almost nothing + int scope_starts = spill_scope_starts; std::unique_lock lock(wake_mutex_); while (!stop_) { - const bool recent = std::chrono::steady_clock::now() - last_trim_.load() < std::chrono::seconds(10); - wake_.wait_for(lock, recent ? std::chrono::milliseconds(50) : std::chrono::milliseconds(200), - [this] { return stop_ || page_out_requested_; }); + if (scope_starts != spill_scope_starts) { // a new compile or weight rewrite: measure again soon + scope_starts = spill_scope_starts; + misses = 0; + } + std::chrono::milliseconds wait(500); // idle: only checks whether a load or compile started + if (active()) { + wait = std::chrono::milliseconds(ggml_time_us() - last_trim_us < active_us ? 50 : 200) * (1 << misses); + } + wake_.wait_for(lock, wait, [this] { return stop_ || page_out_requested_; }); if (stop_) { break; } const bool requested = std::exchange(page_out_requested_, false); + if (!requested && !active()) { + misses = 0; + continue; + } lock.unlock(); if (requested) { - std::lock_guard trim_lock(trim_mutex_); page_out(); + last_trim_us = ggml_time_us(); + } else if (const size_t before = resident_bytes(); before > budget_) { + page_out(); + last_trim_us = ggml_time_us(); + misses = resident_bytes() + budget_ / 8 > before ? std::min(misses + 1, 6) : 0; } else { - trim(); + misses = 0; } lock.lock(); } @@ -170,8 +214,7 @@ class spill_resident_limiter { size_t budget_; size_t page_; std::atomic written_{0}; - std::atomic last_trim_{std::chrono::steady_clock::now()}; - std::mutex trim_mutex_; + std::atomic last_write_us_{0}; std::mutex wake_mutex_; std::condition_variable wake_; bool stop_ = false; @@ -179,20 +222,20 @@ class spill_resident_limiter { std::thread thread_; }; -// GGML_OPENVINO_SPILL_RESIDENT as bytes: "%" of the buffer size, or "" MiB. 0 = no limit. +// GGML_OPENVINO_SPILL_RESIDENT as bytes for one buffer: "%" of the buffer size, or "" MiB per buffer (checked at +// startup). 0 (no limit) when the variable is unset, 0, or at least the buffer size; otherwise at least 1 MiB. static size_t ggml_openvino_spill_resident_budget(size_t buffer_size) { const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_RESIDENT"); - if (v == nullptr || *v == '\0') { + if (v == nullptr) { return 0; } char * end = nullptr; const double x = std::strtod(v, &end); - if (end == v || !(x > 0)) { // also rejects NaN - GGML_LOG_WARN("ggml-openvino: GGML_OPENVINO_SPILL_RESIDENT=%s is not a size (\"35%%\" or MiB), ignoring\n", v); + const double bytes = *end == '%' ? buffer_size * x / 100.0 : x * 1024 * 1024; + if (bytes <= 0 || bytes >= double(buffer_size)) { return 0; } - const double bytes = *end == '%' ? buffer_size * x / 100.0 : x * 1024 * 1024; - return bytes >= double(buffer_size) ? buffer_size : static_cast(bytes); + return std::max(static_cast(bytes), 1024 * 1024); // a tiny value still sets a limit } #endif @@ -228,7 +271,7 @@ struct ggml_backend_openvino_buffer_context { // data is in the weight buffer registry bool weight_registered = false; -#ifdef __linux__ +#ifdef GGML_OPENVINO_SPILL_LIMITER // GGML_OPENVINO_SPILL_RESIDENT on a spilled buffer. The limiter starts at the first weight write: the buffer's // usage is not known when it is allocated, and KV cache and compute buffers must not be paged out. std::unique_ptr spill_limiter; @@ -346,8 +389,13 @@ struct ggml_backend_openvino_buffer_context { spill_size = size; GGML_LOG_INFO("%s: weight buffer spilled to %s (%zu MB, file-backed)\n", __func__, spill_dir, size / 1024 / 1024); -# ifdef __linux__ +# ifdef GGML_OPENVINO_SPILL_LIMITER spill_budget = ggml_openvino_spill_resident_budget(size); +# else + if (ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_RESIDENT")) { + GGML_LOG_WARN("%s: GGML_OPENVINO_SPILL_RESIDENT needs MADV_PAGEOUT (Linux 5.4), ignoring\n", + __func__); + } # endif ov_buffer = std::make_shared(ov::element::u8, ov::Shape{size}, data); } else @@ -406,7 +454,7 @@ struct ggml_backend_openvino_buffer_context { if (kv_on_demand) { ggml_openvino_kv_storage_unregister(data, size); } -#ifdef __linux__ +#ifdef GGML_OPENVINO_SPILL_LIMITER spill_limiter.reset(); // its thread reads the mapping #endif if (spill_mapping != nullptr) { @@ -607,6 +655,20 @@ void ggml_openvino_unregister_weight_buffer(const void * data) { reg.buffers.end()); } +ggml_openvino_spill_trim_scope::ggml_openvino_spill_trim_scope() { +#ifdef GGML_OPENVINO_SPILL_LIMITER + spill_scopes++; + spill_scope_starts++; +#endif +} + +ggml_openvino_spill_trim_scope::~ggml_openvino_spill_trim_scope() { +#ifdef GGML_OPENVINO_SPILL_LIMITER + spill_scope_end_us = ggml_time_us(); + spill_scopes--; +#endif +} + void ggml_openvino_release_weight_buffers() { auto & reg = ov_weight_registry(); std::lock_guard lock(reg.mutex); @@ -647,6 +709,7 @@ void ggml_openvino_release_weight_buffers() { bool ggml_openvino_restore_weight_buffers() { auto & reg = ov_weight_registry(); std::lock_guard lock(reg.mutex); + ggml_openvino_spill_trim_scope trim_scope; return ov_restore_weight_buffers(reg); } @@ -657,6 +720,7 @@ static void ggml_openvino_keep_weight_buffers() { if (reg.keep) { return; } + ggml_openvino_spill_trim_scope trim_scope; if (!ov_restore_weight_buffers(reg)) { GGML_ABORT("ggml-openvino: cannot write the released host weights again"); } @@ -863,7 +927,7 @@ static bool ggml_openvino_range_has_locked_pages(uintptr_t first, uintptr_t last } #endif -#ifdef __linux__ +#ifdef GGML_OPENVINO_SPILL_LIMITER // Before a weight is converted into a spilled buffer with GGML_OPENVINO_SPILL_RESIDENT: start the limiter on the first // weight, and evict the GGUF once. llama.cpp maps it with MAP_POPULATE, so the whole file is resident before the first // tensor arrives; after the eviction, each tensor is read from disk when it is converted. @@ -872,27 +936,29 @@ static void ggml_openvino_spill_budget_before_write(ggml_backend_openvino_buffer if (ctx->spill_budget == 0) { return; } - std::call_once(ctx->spill_limiter_once, [ctx] { + std::call_once(ctx->spill_limiter_once, [ctx, fn = __func__] { ctx->spill_limiter = std::make_unique(ctx->spill_mapping, ctx->spill_size, ctx->spill_budget); GGML_LOG_INFO("%s: at most %zu of %zu MB of the spilled weights stay in RAM (GGML_OPENVINO_SPILL_RESIDENT)\n", - __func__, ctx->spill_budget / 1024 / 1024, ctx->spill_size / 1024 / 1024); + fn, ctx->spill_budget / 1024 / 1024, ctx->spill_size / 1024 / 1024); }); -# ifdef MADV_PAGEOUT const ggml_openvino_source_mapping * mapping = ggml_openvino_find_source_mapping(data, size, ctx->source_mappings); if (mapping != nullptr && mapping->read_only && std::find(ctx->evicted_sources.begin(), ctx->evicted_sources.end(), mapping->begin) == ctx->evicted_sources.end()) { ctx->evicted_sources.push_back(mapping->begin); - madvise(reinterpret_cast(mapping->begin), mapping->end - mapping->begin, MADV_PAGEOUT); + if (madvise(reinterpret_cast(mapping->begin), mapping->end - mapping->begin, MADV_PAGEOUT) != 0) { + spill_warn_once(SPILL_FILE_PAGEOUT); + } } if (mapping != nullptr) { // read this tensor back in large requests rather than one page fault at a time const uintptr_t page = (uintptr_t) sysconf(_SC_PAGESIZE); const uintptr_t first = (uintptr_t) data & ~(page - 1); - madvise(reinterpret_cast(first), (uintptr_t) data + size - first, MADV_WILLNEED); + if (madvise(reinterpret_cast(first), (uintptr_t) data + size - first, MADV_WILLNEED) != 0) { + spill_warn_once(SPILL_FILE_WILLNEED); + } } -# endif } #endif @@ -923,10 +989,12 @@ static void ggml_openvino_release_source_pages(ggml_backend_openvino_buffer_cont VirtualUnlock(reinterpret_cast(first), last - first); } #elif defined(__linux__) -# ifdef MADV_PAGEOUT +# ifdef GGML_OPENVINO_SPILL_LIMITER if (ctx->spill_limiter) { // under a resident budget the GGUF's page cache must go too, not only this process's mapping of it - madvise(reinterpret_cast(first), last - first, MADV_PAGEOUT); + if (madvise(reinterpret_cast(first), last - first, MADV_PAGEOUT) != 0) { + spill_warn_once(SPILL_FILE_PAGEOUT); + } } # endif // MADV_DONTNEED fails on locked (mlock) memory and leaves it resident @@ -969,7 +1037,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer memcpy(tensor->data, data, size); return; } -#ifdef __linux__ +#ifdef GGML_OPENVINO_SPILL_LIMITER if (!ctx->external_memory) { ggml_openvino_spill_budget_before_write(ctx, data, size); } @@ -999,7 +1067,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer if (!ctx->external_memory) { ggml_openvino_release_source_pages(ctx, data, size); } -#ifdef __linux__ +#ifdef GGML_OPENVINO_SPILL_LIMITER if (ctx->spill_limiter) { ctx->spill_limiter->note_write(ggml_nbytes(tensor)); } diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index baf91cf09515..9fa7f80256d4 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -1702,10 +1702,13 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share const ov::AnyMap & compile_config = model_cache_dir.empty() ? config : mc_config; ov::CompiledModel compiled_model; auto remote_context = ggml_openvino_get_remote_context(device); - if (remote_context.has_value()) { - compiled_model = core.compile_model(model, remote_context.value(), compile_config); - } else { - compiled_model = core.compile_model(model, device, compile_config); + { + ggml_openvino_spill_trim_scope trim_scope; + if (remote_context.has_value()) { + compiled_model = core.compile_model(model, remote_context.value(), compile_config); + } else { + compiled_model = core.compile_model(model, device, compile_config); + } } compile_end_time = ggml_time_us(); @@ -2141,6 +2144,7 @@ static void build_static_model(const static_build_args & a, ov::AnyMap import_config = model_config; import_config[ov::hint::model.name()] = std::shared_ptr(model); const int64_t import_start_time = ggml_time_us(); + ggml_openvino_spill_trim_scope trim_scope; // ov::hint::model: the import can read the weights compiled_model = core.import_model(blob_in, device, import_config); const int64_t import_end_time = ggml_time_us(); if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING")) { @@ -2161,6 +2165,7 @@ static void build_static_model(const static_build_args & a, if (a.weightless_bank) { compile_config[ov::enable_weightless.name()] = true; } + ggml_openvino_spill_trim_scope trim_scope; compiled_model = core.compile_model(model, device, compile_config); } local_compile_end_time = ggml_time_us(); From 7795c3a1e856d26a7116ed8929bc68962fdc6722 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Fri, 4 Dec 2026 01:41:12 +0530 Subject: [PATCH 3/6] openvino: take GGML_OPENVINO_SPILL_RESIDENT as a fraction --- ggml/src/ggml-openvino/dev_doc/COOKBOOK.md | 4 ++-- .../ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md | 2 +- ggml/src/ggml-openvino/ggml-openvino-extra.cpp | 16 ++++++---------- ggml/src/ggml-openvino/ggml-openvino.cpp | 16 ++++++---------- 4 files changed, 15 insertions(+), 23 deletions(-) diff --git a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md index 9b80689ce79d..8a33a0f2925d 100644 --- a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md +++ b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md @@ -615,9 +615,9 @@ With the default settings, the GPU and CPU plugins keep their own copy of the we # Use a directory on a local disk (not tmpfs) with free space of about the model size. Can lower prompt speed. export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill mkdir -p $GGML_OPENVINO_SPILL_DIR -# Linux: while the model loads and compiles, keep at most 10% of the spilled weights in RAM, also when RAM is free (or MiB: 2048). +# Linux: while the model loads and compiles, keep at most 10% of the spilled weights in RAM, also when RAM is free. # The first token can come later, while the weights are written to disk. -export GGML_OPENVINO_SPILL_RESIDENT=10% +export GGML_OPENVINO_SPILL_RESIDENT=0.1 # GPU: nothing to set. The backend already releases its host copy of the weights after compilation # (GGML_OPENVINO_RELEASE_WEIGHTS=1, the default). diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index f4d211c9ca89..c0b52b43df8f 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -82,7 +82,7 @@ These variables lower the host memory peak. They do not change the output. Comma | `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | unset | When set, the default of `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, of `GGML_OPENVINO_RELEASE_WEIGHTS`. `0` also keeps the host weights on GPU. | | `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. | | `GGML_OPENVINO_SPILL_DIR` | CPU, GPU | String | `not set` | Back the host buffers of the backend (weights, KV cache, compute) with files in this directory, so the kernel can drop their pages. Use real storage, not tmpfs (`/tmp` on many systems). NPU: only with `GGML_OPENVINO_NPU_L0_HOST_TENSORS=0`. Not part of the cache key. Ignored on Windows and in cache-only mode. | -| `GGML_OPENVINO_SPILL_RESIDENT` | CPU, GPU | String | `not set` | With `GGML_OPENVINO_SPILL_DIR`: while the model loads and compiles, keep at most this part of the spilled weights in RAM, also when RAM is free. A percent of the weights (`10%`), or MiB for each weight buffer (`2048`; a large model can have more than one). `0` or a value at least the buffer size sets no limit. Only the weights, not the KV cache or compute buffers. The first token can come later, while the weights are written to disk. Linux 5.4 or later. | +| `GGML_OPENVINO_SPILL_RESIDENT` | CPU, GPU | Float | `not set` | With `GGML_OPENVINO_SPILL_DIR`: while the model loads and compiles, keep at most this fraction of the spilled weights in RAM, also when RAM is free. From `0` to `1`: `0.1` keeps 10%. `0` or `1` sets no limit. Only the weights, not the KV cache or compute buffers. The first token can come later, while the weights are written to disk. Linux 5.4 or later. | | `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least this size get demand-zero host memory instead of Level Zero host memory. | ## NPU plugin properties diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 22bd12b494c6..f7d2a04dca1c 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -129,7 +129,7 @@ constexpr env_var env_vars[] = { {"GGML_OPENVINO_DEVICE", env_type::STR}, {"GGML_OPENVINO_CACHE_DIR", env_type::STR}, {"GGML_OPENVINO_SPILL_DIR", env_type::STR}, - {"GGML_OPENVINO_SPILL_RESIDENT", env_type::STR}, + {"GGML_OPENVINO_SPILL_RESIDENT", env_type::FLOAT}, {"GGML_OPENVINO_DEBUG_NODE", env_type::STR}, {"GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR", env_type::STR}, {"GGML_OPENVINO_NPU_COMPILE_CONFIG", env_type::STR}, @@ -243,14 +243,6 @@ std::string checked_env_value(const env_var & var, const char * value) { int number = 0; switch (var.type) { case env_type::STR: - if (std::strcmp(var.name, "GGML_OPENVINO_SPILL_RESIDENT") == 0) { - char * end = nullptr; - const double size = std::strtod(value, &end); - if (end == value || !(size >= 0) || !trim_spaces(*end == '%' ? end + 1 : end).empty()) { - GGML_ABORT("ggml-openvino: %s=%s is not valid, use a percent of the weights (10%%) or MiB (2048)", - var.name, value); - } - } break; case env_type::ENUM: { const std::string wanted = trim_spaces(value); @@ -280,10 +272,14 @@ std::string checked_env_value(const env_var & var, const char * value) { return std::to_string(number); case env_type::FLOAT: { char * end = nullptr; - (void) std::strtof(value, &end); + const float number = std::strtof(value, &end); if (end == value || !trim_spaces(end).empty()) { GGML_ABORT("ggml-openvino: %s=%s is not valid, use a number", var.name, value); } + if (std::strcmp(var.name, "GGML_OPENVINO_SPILL_RESIDENT") == 0 && !(number >= 0 && number <= 1)) { + GGML_ABORT("ggml-openvino: %s=%s is not valid, use a fraction of the weights from 0 to 1 (0.1)", var.name, + value); + } break; } case env_type::BOOL: diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index b20bd7c6c5db..7b2acc59d1a9 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -222,20 +222,16 @@ class spill_resident_limiter { std::thread thread_; }; -// GGML_OPENVINO_SPILL_RESIDENT as bytes for one buffer: "%" of the buffer size, or "" MiB per buffer (checked at -// startup). 0 (no limit) when the variable is unset, 0, or at least the buffer size; otherwise at least 1 MiB. +// GGML_OPENVINO_SPILL_RESIDENT as bytes for one buffer: a fraction of its size, from 0 to 1 (checked at startup), and +// at least 1 MiB. 0 (no limit) when the variable is unset, 0 or 1, or when the budget is not smaller than the buffer. static size_t ggml_openvino_spill_resident_budget(size_t buffer_size) { const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_RESIDENT"); - if (v == nullptr) { + const double fraction = v != nullptr ? std::strtod(v, nullptr) : 0; + if (!(fraction > 0)) { return 0; } - char * end = nullptr; - const double x = std::strtod(v, &end); - const double bytes = *end == '%' ? buffer_size * x / 100.0 : x * 1024 * 1024; - if (bytes <= 0 || bytes >= double(buffer_size)) { - return 0; - } - return std::max(static_cast(bytes), 1024 * 1024); // a tiny value still sets a limit + const size_t bytes = std::max(static_cast(buffer_size * fraction), 1024 * 1024); + return bytes < buffer_size ? bytes : 0; } #endif From 46b86b8fc8da3fb0268eacec12134cc85c44fe9a Mon Sep 17 00:00:00 2001 From: ravi9 Date: Fri, 4 Dec 2026 02:49:12 +0530 Subject: [PATCH 4/6] openvino: add GGML_OPENVINO_SPILL and simplify the spill limiter --- ggml/src/ggml-openvino/dev_doc/COOKBOOK.md | 17 +- .../dev_doc/OpenVINO-ENV-VARS.md | 4 +- ggml/src/ggml-openvino/dev_doc/README.md | 2 +- .../src/ggml-openvino/ggml-openvino-extra.cpp | 8 +- ggml/src/ggml-openvino/ggml-openvino-extra.h | 4 +- ggml/src/ggml-openvino/ggml-openvino.cpp | 224 ++++++++---------- ggml/src/ggml-openvino/model-cache.cpp | 1 + 7 files changed, 124 insertions(+), 136 deletions(-) diff --git a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md index 8a33a0f2925d..f8a7fb94863b 100644 --- a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md +++ b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md @@ -611,13 +611,15 @@ On the NPU, the cache holds the compiled models without weights, plus one shared With the default settings, the GPU and CPU plugins keep their own copy of the weights next to the copy of the backend while a model compiles. On integrated GPUs, both copies are in system RAM. The settings below lower that peak. They do not change the output. ```bash -# GPU or CPU, large model: back the host buffers with a file, so the kernel can drop their pages. -# Use a directory on a local disk (not tmpfs) with free space of about the model size. Can lower prompt speed. +# GPU or CPU, large model: back the host buffers with files, so the kernel can drop their pages. +# Needs free disk space of about the model size. Can lower prompt speed. +export GGML_OPENVINO_SPILL=1 +# Linux, instead of 1: also keep at most 10% of the spilled weights in RAM while the model loads and compiles, when +# RAM is free too. The first token can come later, while the weights are written to disk. +export GGML_OPENVINO_SPILL=0.1 +# The files go to /var/tmp. Another directory, on a local disk (not tmpfs): export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill mkdir -p $GGML_OPENVINO_SPILL_DIR -# Linux: while the model loads and compiles, keep at most 10% of the spilled weights in RAM, also when RAM is free. -# The first token can come later, while the weights are written to disk. -export GGML_OPENVINO_SPILL_RESIDENT=0.1 # GPU: nothing to set. The backend already releases its host copy of the weights after compilation # (GGML_OPENVINO_RELEASE_WEIGHTS=1, the default). @@ -630,9 +632,9 @@ export GGML_OPENVINO_REDUCE_COMPILE_MEM=1 export GGML_OPENVINO_MEMORY_OPTIMIZE=1 ``` -- The same model, started again and again: [cache-only mode](#cpu-and-gpu) skips the weight upload. `GGML_OPENVINO_SPILL_DIR` is optional in the first run. +- The same model, started again and again: [cache-only mode](#cpu-and-gpu) skips the weight upload. `GGML_OPENVINO_SPILL` is optional in the first run. - NPU: `GGML_OPENVINO_SELF_CONTAINED_MMAP=1` uses the memory-mapped GGUF file as the model buffer. See [NPU: gemma-4 E2B example](#npu-gemma-4-e2b-example). -- `GGML_OPENVINO_SPILL_DIR` is ignored on Windows and in cache-only mode. +- `GGML_OPENVINO_SPILL` is ignored on Windows and in cache-only mode. - `-lm none` (no mmap) does not lower the memory in use. Cache-only mode needs mmap loading and stops with an error with `-lm none`. - The variables: [Memory optimization](OpenVINO-ENV-VARS.md#memory-optimization). @@ -670,6 +672,7 @@ This needs a 64 GB system. ```bash export GGML_OPENVINO_DEVICE=GPU +export GGML_OPENVINO_SPILL=1 export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill # local disk, not tmpfs export GGML_OPENVINO_ROPE_SINCOS=device_f32 # long prompts mkdir -p $GGML_OPENVINO_SPILL_DIR diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index c0b52b43df8f..d193b0bf684b 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -81,8 +81,8 @@ These variables lower the host memory peak. They do not change the output. Comma |---|---|---|---|---| | `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | unset | When set, the default of `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, of `GGML_OPENVINO_RELEASE_WEIGHTS`. `0` also keeps the host weights on GPU. | | `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. | -| `GGML_OPENVINO_SPILL_DIR` | CPU, GPU | String | `not set` | Back the host buffers of the backend (weights, KV cache, compute) with files in this directory, so the kernel can drop their pages. Use real storage, not tmpfs (`/tmp` on many systems). NPU: only with `GGML_OPENVINO_NPU_L0_HOST_TENSORS=0`. Not part of the cache key. Ignored on Windows and in cache-only mode. | -| `GGML_OPENVINO_SPILL_RESIDENT` | CPU, GPU | Float | `not set` | With `GGML_OPENVINO_SPILL_DIR`: while the model loads and compiles, keep at most this fraction of the spilled weights in RAM, also when RAM is free. From `0` to `1`: `0.1` keeps 10%. `0` or `1` sets no limit. Only the weights, not the KV cache or compute buffers. The first token can come later, while the weights are written to disk. Linux 5.4 or later. | +| `GGML_OPENVINO_SPILL` | CPU, GPU | Float | `0` | Back the host buffers of the backend (weights, KV cache, compute) with files in `GGML_OPENVINO_SPILL_DIR`, so the kernel can drop their pages. `0`: off. `1`: on. A fraction in between: on, and while the model loads and compiles, keep at most this fraction of the spilled weights in RAM, also when RAM is free (`0.1` keeps 10%, Linux 5.4 or later); the model file's pages are dropped too, and the first token can come later, while the weights are written to disk. Needs free disk space of about the model size. NPU: only with `GGML_OPENVINO_NPU_L0_HOST_TENSORS=0`. Not part of the cache key. Ignored on Windows and in cache-only mode. | +| `GGML_OPENVINO_SPILL_DIR` | CPU, GPU | String | `/var/tmp` | Directory for the `GGML_OPENVINO_SPILL` files. Use real storage, not tmpfs (`/tmp` on many systems). Set without `GGML_OPENVINO_SPILL`, it turns spilling on, as `GGML_OPENVINO_SPILL=1`. | | `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least this size get demand-zero host memory instead of Level Zero host memory. | ## NPU plugin properties diff --git a/ggml/src/ggml-openvino/dev_doc/README.md b/ggml/src/ggml-openvino/dev_doc/README.md index bd486b8a1090..cfc38aa54d29 100644 --- a/ggml/src/ggml-openvino/dev_doc/README.md +++ b/ggml/src/ggml-openvino/dev_doc/README.md @@ -86,7 +86,7 @@ Settings that must stay exactly the same between the runs, including set versus Settings that can differ: -- `GGML_OPENVINO_SPILL_DIR`: optional on the first run and ignored in cache-only mode. Host-weight release is disabled in cache-only mode. +- `GGML_OPENVINO_SPILL` and `GGML_OPENVINO_SPILL_DIR`: optional on the first run and ignored in cache-only mode. Host-weight release is disabled in cache-only mode. - `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`: changes only the output bindings. - `GGML_OPENVINO_KV_SLICE`: a runtime binding option for dynamic graphs. The same dynamic compiled graph accepts full-capacity and live-prefix attention K/V tensors. Eligibility: [KV cache binding](#kv-cache-binding). diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index f7d2a04dca1c..14f5da0c34ca 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -128,8 +128,8 @@ constexpr env_var env_vars[] = { // Text {"GGML_OPENVINO_DEVICE", env_type::STR}, {"GGML_OPENVINO_CACHE_DIR", env_type::STR}, + {"GGML_OPENVINO_SPILL", env_type::FLOAT}, {"GGML_OPENVINO_SPILL_DIR", env_type::STR}, - {"GGML_OPENVINO_SPILL_RESIDENT", env_type::FLOAT}, {"GGML_OPENVINO_DEBUG_NODE", env_type::STR}, {"GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR", env_type::STR}, {"GGML_OPENVINO_NPU_COMPILE_CONFIG", env_type::STR}, @@ -276,9 +276,9 @@ std::string checked_env_value(const env_var & var, const char * value) { if (end == value || !trim_spaces(end).empty()) { GGML_ABORT("ggml-openvino: %s=%s is not valid, use a number", var.name, value); } - if (std::strcmp(var.name, "GGML_OPENVINO_SPILL_RESIDENT") == 0 && !(number >= 0 && number <= 1)) { - GGML_ABORT("ggml-openvino: %s=%s is not valid, use a fraction of the weights from 0 to 1 (0.1)", var.name, - value); + if (std::strcmp(var.name, "GGML_OPENVINO_SPILL") == 0 && !(number >= 0 && number <= 1)) { + GGML_ABORT("ggml-openvino: %s=%s is not valid, use 0 (off), 1 (on) or a fraction in between (0.1)", + var.name, value); } break; } diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 7bd63447909c..8c5fa5811c7f 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -290,8 +290,8 @@ void ggml_openvino_unregister_weight_buffer(const void * data); void ggml_openvino_release_weight_buffers(); bool ggml_openvino_restore_weight_buffers(); -// GGML_OPENVINO_SPILL_RESIDENT: the limiters trim the spilled weights while the model loads and while one of these is -// alive, and sleep otherwise. Hold one around compile_model (it reads the weights back) and around rewriting released +// A GGML_OPENVINO_SPILL fraction: the limiters trim the spilled weights while the model loads, and while one of these is +// alive and for 10 s after, and sleep otherwise. Hold one around compile_model (it reads the weights back) and around rewriting released // weights. struct ggml_openvino_spill_trim_scope { ggml_openvino_spill_trim_scope(); diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 7b2acc59d1a9..6cf94a1fea1b 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -53,7 +54,7 @@ # include #endif -// GGML_OPENVINO_SPILL_RESIDENT needs MADV_PAGEOUT (Linux 5.4) +// A GGML_OPENVINO_SPILL fraction needs MADV_PAGEOUT (Linux 5.4) #if defined(__linux__) && defined(MADV_PAGEOUT) # define GGML_OPENVINO_SPILL_LIMITER #endif @@ -76,32 +77,17 @@ // ===================================================== namespace { -#ifdef GGML_OPENVINO_SPILL_LIMITER -// Live ggml_openvino_spill_trim_scope objects, how many have started, and when the last one ended. +// Live ggml_openvino_spill_trim_scope objects, and when the last one ended std::atomic spill_scopes{0}; -std::atomic spill_scope_starts{0}; std::atomic spill_scope_end_us{0}; -enum spill_call { SPILL_MINCORE, SPILL_MSYNC, SPILL_PAGEOUT, SPILL_FILE_PAGEOUT, SPILL_FILE_WILLNEED, SPILL_CALLS }; - -// Logs the first failure of each call only: the later ones fail the same way. -void spill_warn_once(spill_call call) { - static const char * names[SPILL_CALLS] = {"mincore", "msync", "madvise(MADV_PAGEOUT)", - "madvise(MADV_PAGEOUT) of the model file", - "madvise(MADV_WILLNEED) of the model file"}; - static std::atomic warned[SPILL_CALLS]; - if (!warned[call].exchange(true)) { - GGML_LOG_WARN("ggml-openvino: GGML_OPENVINO_SPILL_RESIDENT: %s failed: %s\n", names[call], strerror(errno)); - } -} - -// GGML_OPENVINO_SPILL_RESIDENT: keep at most a budget of a spilled weight buffer (GGML_OPENVINO_SPILL_DIR) in RAM. +#ifdef GGML_OPENVINO_SPILL_LIMITER +// GGML_OPENVINO_SPILL with a fraction: keep at most a budget of a spilled weight buffer in RAM. // Spilled pages are file-backed, but the kernel only evicts them under memory pressure, so on a machine with free // RAM the whole buffer stays resident. A thread writes the dirty pages to the file and drops them: after every half -// budget of weight writes while the model loads, and whenever the resident part exceeds the budget while -// compile_model reads the weights back (ggml_openvino_spill_trim_scope). Outside of these it sleeps without measuring. -// When a page-out frees almost nothing (pages no longer mapped, e.g. after the GPU weight release), it waits longer -// before the next one, until the next scope starts. +// budget of weight writes while the model loads, and, while a ggml_openvino_spill_trim_scope is alive (compile_model +// reads the weights back) and for 10 s after (the CPU plugin's first inference reads them too), whenever the resident +// part exceeds the budget. Otherwise it sleeps. class spill_resident_limiter { public: spill_resident_limiter(void * data, size_t size, size_t budget) : @@ -121,7 +107,6 @@ class spill_resident_limiter { // Called after a write into the buffer. Written pages are resident, so after every budget / 2 bytes the thread // pages out without measuring. Writing the pages to disk takes as long as converting them, so it runs alongside. void note_write(size_t bytes) { - last_write_us_ = ggml_time_us(); if ((written_ += bytes) >= budget_ / 2) { written_ = 0; { @@ -133,15 +118,17 @@ class spill_resident_limiter { } private: - static constexpr int64_t active_us = 10 * 1000 * 1000; + static bool in_scope() { return spill_scopes > 0 || ggml_time_us() - spill_scope_end_us < 10 * 1000 * 1000; } - // While the model loads or a ggml_openvino_spill_trim_scope is alive, and for 10 s after. - bool active() const { - const int64_t now = ggml_time_us(); - return spill_scopes > 0 || now - last_write_us_ < active_us || now - spill_scope_end_us < active_us; + // The limiter stops at the first failed call: after a failed msync, dropping the pages could lose weights that + // are not on disk. + static void log_stop(const char * call) { + GGML_LOG_WARN("ggml-openvino: GGML_OPENVINO_SPILL: %s failed (%s), no limit from now on\n", call, + strerror(errno)); } - // Estimated from a sample: mincore looks up every page in the page cache, which takes ~65 ms for 7 GB. + // Estimated from a sample: mincore looks up every page in the page cache, which takes ~65 ms for 7 GB. SIZE_MAX + // when mincore fails. size_t resident_bytes() { constexpr size_t run = 16, stride = 1024; // pages unsigned char pages[run]; @@ -150,8 +137,8 @@ class spill_resident_limiter { const size_t len = std::min(run * page_, size_ - off); const size_t n = (len + page_ - 1) / page_; if (mincore(static_cast(data_) + off, len, pages) != 0) { - spill_warn_once(SPILL_MINCORE); - return size_; // unknown: page out + log_stop("mincore"); + return SIZE_MAX; } for (size_t i = 0; i < n; i++) { resident += pages[i] & 1; @@ -161,49 +148,37 @@ class spill_resident_limiter { return sampled ? static_cast(double(resident) / sampled * size_) : 0; } - void page_out() { + // false when a call failed + bool page_out() { // dirty file pages cannot be dropped until written back if (msync(data_, size_, MS_SYNC) != 0) { - spill_warn_once(SPILL_MSYNC); + log_stop("msync"); + return false; } if (madvise(data_, size_, MADV_PAGEOUT) != 0) { - spill_warn_once(SPILL_PAGEOUT); + log_stop("madvise(MADV_PAGEOUT)"); + return false; } + return true; } void run() { - int64_t last_trim_us = 0; - int misses = 0; // measured page-outs in a row that freed almost nothing - int scope_starts = spill_scope_starts; std::unique_lock lock(wake_mutex_); while (!stop_) { - if (scope_starts != spill_scope_starts) { // a new compile or weight rewrite: measure again soon - scope_starts = spill_scope_starts; - misses = 0; - } - std::chrono::milliseconds wait(500); // idle: only checks whether a load or compile started - if (active()) { - wait = std::chrono::milliseconds(ggml_time_us() - last_trim_us < active_us ? 50 : 200) * (1 << misses); - } + // outside of a scope only note_write brings work: the timeout only checks whether a scope started + const std::chrono::milliseconds wait(in_scope() ? 50 : 500); wake_.wait_for(lock, wait, [this] { return stop_ || page_out_requested_; }); if (stop_) { break; } const bool requested = std::exchange(page_out_requested_, false); - if (!requested && !active()) { - misses = 0; + if (!requested && !in_scope()) { continue; } lock.unlock(); - if (requested) { - page_out(); - last_trim_us = ggml_time_us(); - } else if (const size_t before = resident_bytes(); before > budget_) { - page_out(); - last_trim_us = ggml_time_us(); - misses = resident_bytes() + budget_ / 8 > before ? std::min(misses + 1, 6) : 0; - } else { - misses = 0; + const size_t resident = requested ? size_ : resident_bytes(); + if (resident == SIZE_MAX || (resident > budget_ && !page_out())) { + return; } lock.lock(); } @@ -213,8 +188,7 @@ class spill_resident_limiter { size_t size_; size_t budget_; size_t page_; - std::atomic written_{0}; - std::atomic last_write_us_{0}; + size_t written_ = 0; // only the loading thread writes weights std::mutex wake_mutex_; std::condition_variable wake_; bool stop_ = false; @@ -222,19 +196,42 @@ class spill_resident_limiter { std::thread thread_; }; -// GGML_OPENVINO_SPILL_RESIDENT as bytes for one buffer: a fraction of its size, from 0 to 1 (checked at startup), and -// at least 1 MiB. 0 (no limit) when the variable is unset, 0 or 1, or when the budget is not smaller than the buffer. -static size_t ggml_openvino_spill_resident_budget(size_t buffer_size) { - const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_RESIDENT"); - const double fraction = v != nullptr ? std::strtod(v, nullptr) : 0; - if (!(fraction > 0)) { +// The resident limit of a spilled buffer in bytes: the GGML_OPENVINO_SPILL fraction of its size, at least 1 MiB. 0 (no +// limit) for 1, or when the limit is not smaller than the buffer. +static size_t ggml_openvino_spill_resident_budget(size_t buffer_size, double fraction) { + if (!(fraction < 1)) { return 0; } const size_t bytes = std::max(static_cast(buffer_size * fraction), 1024 * 1024); return bytes < buffer_size ? bytes : 0; } +#else +struct spill_resident_limiter { + void note_write(size_t) {} +}; + +[[maybe_unused]] static size_t ggml_openvino_spill_resident_budget(size_t, double fraction) { // unused on Windows + static std::atomic warned{false}; + if (fraction < 1 && !warned.exchange(true)) { + GGML_LOG_WARN( + "ggml-openvino: a GGML_OPENVINO_SPILL fraction needs Linux 5.4 or later, spilling without a limit\n"); + } + return 0; +} #endif +// GGML_OPENVINO_SPILL, checked at startup: 0 off, 1 back the host buffers with files, a fraction in between also limits +// the spilled weights kept in RAM. GGML_OPENVINO_SPILL_DIR set alone means 1. Off in cache-only mode. +static double ggml_openvino_spill_fraction() { + if (ggml_openvino_model_cache_only()) { + return 0; + } + if (const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_SPILL")) { + return std::strtod(v, nullptr); + } + return ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR") != nullptr ? 1 : 0; +} + // Buffer context that manages per-tensor allocations (no contiguous buffer for weights) struct ggml_backend_openvino_buffer_context { int device; @@ -267,15 +264,12 @@ struct ggml_backend_openvino_buffer_context { // data is in the weight buffer registry bool weight_registered = false; -#ifdef GGML_OPENVINO_SPILL_LIMITER - // GGML_OPENVINO_SPILL_RESIDENT on a spilled buffer. The limiter starts at the first weight write: the buffer's + // A GGML_OPENVINO_SPILL fraction on a spilled buffer. The limiter starts at the first weight write: the buffer's // usage is not known when it is allocated, and KV cache and compute buffers must not be paged out. std::unique_ptr spill_limiter; size_t spill_budget = 0; - std::once_flag spill_limiter_once; // source mappings already evicted once under the budget std::vector evicted_sources; -#endif // One counter for both constructors: the id is part of the weight identity in the graph key, so a host-pointer // buffer and an allocated buffer must never share one. @@ -349,8 +343,7 @@ struct ggml_backend_openvino_buffer_context { // backed by the Level Zero host tensor above } else #ifndef _WIN32 - if (const char * spill_dir = - ggml_openvino_model_cache_only() ? nullptr : ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR")) { + if (const double spill = ggml_openvino_spill_fraction(); spill > 0) { // Disk-backed weight buffer: back the repacked weights with a temp file via MAP_SHARED // instead of anonymous memory. Anonymous pages can only be evicted to swap, so the // repacked buffer stays pinned alongside the mmap'd source and both are resident at once @@ -361,6 +354,7 @@ struct ggml_backend_openvino_buffer_context { // // The directory must be real storage. Pointing this at a tmpfs mount (/tmp on many // systems) backs the "spill" with RAM and makes matters worse. + const char * spill_dir = ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR", "/var/tmp"); char path[PATH_MAX]; snprintf(path, sizeof(path), "%s/ggml-ov-weights-%d-XXXXXX", spill_dir, (int) getpid()); int fd = mkstemp(path); @@ -385,21 +379,14 @@ struct ggml_backend_openvino_buffer_context { spill_size = size; GGML_LOG_INFO("%s: weight buffer spilled to %s (%zu MB, file-backed)\n", __func__, spill_dir, size / 1024 / 1024); -# ifdef GGML_OPENVINO_SPILL_LIMITER - spill_budget = ggml_openvino_spill_resident_budget(size); -# else - if (ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_RESIDENT")) { - GGML_LOG_WARN("%s: GGML_OPENVINO_SPILL_RESIDENT needs MADV_PAGEOUT (Linux 5.4), ignoring\n", - __func__); - } -# endif + spill_budget = ggml_openvino_spill_resident_budget(size, spill); ov_buffer = std::make_shared(ov::element::u8, ov::Shape{size}, data); } else #endif { #ifdef _WIN32 - if (!ggml_openvino_model_cache_only() && ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR")) { - GGML_LOG_WARN("%s: GGML_OPENVINO_SPILL_DIR is not supported on Windows, ignoring\n", __func__); + if (ggml_openvino_spill_fraction() > 0) { + GGML_LOG_WARN("%s: GGML_OPENVINO_SPILL is not supported on Windows, ignoring\n", __func__); } #endif // Anonymous OS memory reads as zero without being touched, so a buffer becomes resident only as it @@ -450,9 +437,7 @@ struct ggml_backend_openvino_buffer_context { if (kv_on_demand) { ggml_openvino_kv_storage_unregister(data, size); } -#ifdef GGML_OPENVINO_SPILL_LIMITER spill_limiter.reset(); // its thread reads the mapping -#endif if (spill_mapping != nullptr) { #ifdef _WIN32 VirtualFree(spill_mapping, 0, MEM_RELEASE); @@ -652,17 +637,12 @@ void ggml_openvino_unregister_weight_buffer(const void * data) { } ggml_openvino_spill_trim_scope::ggml_openvino_spill_trim_scope() { -#ifdef GGML_OPENVINO_SPILL_LIMITER spill_scopes++; - spill_scope_starts++; -#endif } ggml_openvino_spill_trim_scope::~ggml_openvino_spill_trim_scope() { -#ifdef GGML_OPENVINO_SPILL_LIMITER spill_scope_end_us = ggml_time_us(); spill_scopes--; -#endif } void ggml_openvino_release_weight_buffers() { @@ -924,38 +904,44 @@ static bool ggml_openvino_range_has_locked_pages(uintptr_t first, uintptr_t last #endif #ifdef GGML_OPENVINO_SPILL_LIMITER -// Before a weight is converted into a spilled buffer with GGML_OPENVINO_SPILL_RESIDENT: start the limiter on the first +// Before a weight is written into a spilled buffer with a GGML_OPENVINO_SPILL fraction: start the limiter on the first // weight, and evict the GGUF once. llama.cpp maps it with MAP_POPULATE, so the whole file is resident before the first -// tensor arrives; after the eviction, each tensor is read from disk when it is converted. -static void ggml_openvino_spill_budget_before_write(ggml_backend_openvino_buffer_context * ctx, const void * data, +// tensor arrives; after the eviction, each tensor is read from disk when it is converted. The GGUF madvise calls are +// hints: they fail on locked pages (--mlock), which only keeps the pages. +static void ggml_openvino_spill_before_weight_write(ggml_backend_openvino_buffer_context * ctx, + const void * data, size_t size) { if (ctx->spill_budget == 0) { return; } - std::call_once(ctx->spill_limiter_once, [ctx, fn = __func__] { - ctx->spill_limiter = - std::make_unique(ctx->spill_mapping, ctx->spill_size, ctx->spill_budget); - GGML_LOG_INFO("%s: at most %zu of %zu MB of the spilled weights stay in RAM (GGML_OPENVINO_SPILL_RESIDENT)\n", - fn, ctx->spill_budget / 1024 / 1024, ctx->spill_size / 1024 / 1024); - }); - const ggml_openvino_source_mapping * mapping = ggml_openvino_find_source_mapping(data, size, ctx->source_mappings); - if (mapping != nullptr && mapping->read_only && - std::find(ctx->evicted_sources.begin(), ctx->evicted_sources.end(), mapping->begin) == - ctx->evicted_sources.end()) { - ctx->evicted_sources.push_back(mapping->begin); - if (madvise(reinterpret_cast(mapping->begin), mapping->end - mapping->begin, MADV_PAGEOUT) != 0) { - spill_warn_once(SPILL_FILE_PAGEOUT); + if (!ctx->spill_limiter) { // set_tensor does not run concurrently on one buffer + try { + ctx->spill_limiter = + std::make_unique(ctx->spill_mapping, ctx->spill_size, ctx->spill_budget); + } catch (const std::system_error & e) { + GGML_LOG_WARN("%s: cannot start the GGML_OPENVINO_SPILL thread (%s), no limit\n", __func__, e.what()); + ctx->spill_budget = 0; + return; } + GGML_LOG_INFO("%s: at most %zu of %zu MB of the spilled weights stay in RAM (GGML_OPENVINO_SPILL)\n", __func__, + ctx->spill_budget / 1024 / 1024, ctx->spill_size / 1024 / 1024); } - if (mapping != nullptr) { - // read this tensor back in large requests rather than one page fault at a time - const uintptr_t page = (uintptr_t) sysconf(_SC_PAGESIZE); - const uintptr_t first = (uintptr_t) data & ~(page - 1); - if (madvise(reinterpret_cast(first), (uintptr_t) data + size - first, MADV_WILLNEED) != 0) { - spill_warn_once(SPILL_FILE_WILLNEED); - } + const ggml_openvino_source_mapping * mapping = ggml_openvino_find_source_mapping(data, size, ctx->source_mappings); + if (mapping == nullptr) { + return; + } + if (mapping->read_only && std::find(ctx->evicted_sources.begin(), ctx->evicted_sources.end(), mapping->begin) == + ctx->evicted_sources.end()) { + ctx->evicted_sources.push_back(mapping->begin); + madvise(reinterpret_cast(mapping->begin), mapping->end - mapping->begin, MADV_PAGEOUT); } + // read this tensor back in large requests rather than one page fault at a time + const uintptr_t page = (uintptr_t) sysconf(_SC_PAGESIZE); + const uintptr_t first = (uintptr_t) data & ~(page - 1); + madvise(reinterpret_cast(first), (uintptr_t) data + size - first, MADV_WILLNEED); } +#else +static void ggml_openvino_spill_before_weight_write(ggml_backend_openvino_buffer_context *, const void *, size_t) {} #endif // A weight's GGUF bytes have been converted into its OpenVINO buffer. Pages of a read-only file mapping are clean and @@ -988,9 +974,7 @@ static void ggml_openvino_release_source_pages(ggml_backend_openvino_buffer_cont # ifdef GGML_OPENVINO_SPILL_LIMITER if (ctx->spill_limiter) { // under a resident budget the GGUF's page cache must go too, not only this process's mapping of it - if (madvise(reinterpret_cast(first), last - first, MADV_PAGEOUT) != 0) { - spill_warn_once(SPILL_FILE_PAGEOUT); - } + madvise(reinterpret_cast(first), last - first, MADV_PAGEOUT); // a hint, as above } # endif // MADV_DONTNEED fails on locked (mlock) memory and leaves it resident @@ -1033,11 +1017,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer memcpy(tensor->data, data, size); return; } -#ifdef GGML_OPENVINO_SPILL_LIMITER - if (!ctx->external_memory) { - ggml_openvino_spill_budget_before_write(ctx, data, size); - } -#endif + ggml_openvino_spill_before_weight_write(ctx, data, size); try { auto result = process_weight_tensor(tensor, data, tensor->data); result.weight_node->set_friendly_name(tensor->name); @@ -1063,11 +1043,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer if (!ctx->external_memory) { ggml_openvino_release_source_pages(ctx, data, size); } -#ifdef GGML_OPENVINO_SPILL_LIMITER if (ctx->spill_limiter) { ctx->spill_limiter->note_write(ggml_nbytes(tensor)); } -#endif } catch (const std::exception & e) { GGML_LOG_ERROR("%s: failed to process weight tensor for %s: %s\n", __func__, tensor->name, e.what()); memcpy((char *) tensor->data + offset, data, size); @@ -1077,6 +1055,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer } } else { // Non-weight tensor (KV cache, activations, etc.) - copy data. test-backend-ops also goes here + if (is_weight_buffer) { + ggml_openvino_spill_before_weight_write(ctx, data, size); + } if (ctx->is_remote) { cl_command_queue queue = ggml_openvino_get_cl_queue(ggml_openvino_get_available_devices()[ctx->device]); auto mem_cpy_fn = ggml_openvino_get_clEnqueueMemcpyINTEL(); @@ -1097,6 +1078,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer if (is_weight_buffer && !ctx->is_remote) { ggml_openvino_record_weight_write(buffer, tensor, offset, data, size, false); } + if (is_weight_buffer && ctx->spill_limiter) { + ctx->spill_limiter->note_write(size); + } if (ggml_openvino_extra_unchanged(ctx, tensor)) { return; diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index f5921fce8a21..121a4584116a 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -169,6 +169,7 @@ void ggml_openvino_model_cache_init() { #endif if (cache_only) { auto & config = ggml_openvino_get_device_config(); + config.environment_variables.erase("GGML_OPENVINO_SPILL"); config.environment_variables.erase("GGML_OPENVINO_SPILL_DIR"); config.environment_variables["GGML_OPENVINO_RELEASE_WEIGHTS"] = "0"; } From 41733ba2b8c42fbfa56267c69e2f37324090e79f Mon Sep 17 00:00:00 2001 From: ravi9 Date: Fri, 4 Dec 2026 05:32:47 +0530 Subject: [PATCH 5/6] openvino: add GGML_OPENVINO_COMPILE_MEM_SPILL --- ggml/src/ggml-openvino/dev_doc/COOKBOOK.md | 33 ++-- .../dev_doc/OpenVINO-ENV-VARS.md | 6 +- ggml/src/ggml-openvino/dev_doc/README.md | 2 +- .../src/ggml-openvino/ggml-openvino-extra.cpp | 6 +- ggml/src/ggml-openvino/ggml-openvino-extra.h | 6 +- ggml/src/ggml-openvino/ggml-openvino.cpp | 164 +++++++++++------- ggml/src/ggml-openvino/model-cache.cpp | 4 +- 7 files changed, 127 insertions(+), 94 deletions(-) diff --git a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md index f8a7fb94863b..1324f59a50e7 100644 --- a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md +++ b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md @@ -611,15 +611,18 @@ On the NPU, the cache holds the compiled models without weights, plus one shared With the default settings, the GPU and CPU plugins keep their own copy of the weights next to the copy of the backend while a model compiles. On integrated GPUs, both copies are in system RAM. The settings below lower that peak. They do not change the output. ```bash -# GPU or CPU, large model: back the host buffers with files, so the kernel can drop their pages. -# Needs free disk space of about the model size. Can lower prompt speed. -export GGML_OPENVINO_SPILL=1 -# Linux, instead of 1: also keep at most 10% of the spilled weights in RAM while the model loads and compiles, when -# RAM is free too. The first token can come later, while the weights are written to disk. -export GGML_OPENVINO_SPILL=0.1 -# The files go to /var/tmp. Another directory, on a local disk (not tmpfs): -export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill -mkdir -p $GGML_OPENVINO_SPILL_DIR +# GPU or CPU, large model, Linux: keep at most 10% of the weights in RAM while the model loads and compiles. +# This lowers the peak the most, also when RAM is free. The first token can come later. +export GGML_OPENVINO_COMPILE_MEM_SPILL=0.1 +# Or without a cap: the kernel drops the spilled pages only when RAM runs out, so the peak does not change while +# RAM is free. +# export GGML_OPENVINO_COMPILE_MEM_SPILL=1 +# Both back the host buffers with files in /var/tmp and write them at each start: the load takes longer, and decoding +# can be a little slower. Needs free disk space of more than the model size, on CPU also the KV cache; with less, the +# backend warns and uses RAM. +# Another directory, on a local disk (not tmpfs): +export GGML_OPENVINO_COMPILE_MEM_SPILL_DIR=$HOME/ov_spill +mkdir -p $GGML_OPENVINO_COMPILE_MEM_SPILL_DIR # GPU: nothing to set. The backend already releases its host copy of the weights after compilation # (GGML_OPENVINO_RELEASE_WEIGHTS=1, the default). @@ -627,14 +630,14 @@ mkdir -p $GGML_OPENVINO_SPILL_DIR # CPU, MoE model: build fewer weight nodes during compilation. export GGML_OPENVINO_REDUCE_COMPILE_MEM=1 -# Both switches at once: GGML_OPENVINO_MEMORY_OPTIMIZE sets the default of GGML_OPENVINO_REDUCE_COMPILE_MEM -# and, on GPU, of GGML_OPENVINO_RELEASE_WEIGHTS. +# All at once: GGML_OPENVINO_MEMORY_OPTIMIZE=1 sets GGML_OPENVINO_REDUCE_COMPILE_MEM=1, GGML_OPENVINO_COMPILE_MEM_SPILL=0.1 +# and, on GPU, GGML_OPENVINO_RELEASE_WEIGHTS=1 (already the default). Each one set on its own wins. export GGML_OPENVINO_MEMORY_OPTIMIZE=1 ``` -- The same model, started again and again: [cache-only mode](#cpu-and-gpu) skips the weight upload. `GGML_OPENVINO_SPILL` is optional in the first run. +- The same model, started again and again: [cache-only mode](#cpu-and-gpu) skips the weight upload. `GGML_OPENVINO_COMPILE_MEM_SPILL` is optional in the first run. - NPU: `GGML_OPENVINO_SELF_CONTAINED_MMAP=1` uses the memory-mapped GGUF file as the model buffer. See [NPU: gemma-4 E2B example](#npu-gemma-4-e2b-example). -- `GGML_OPENVINO_SPILL` is ignored on Windows and in cache-only mode. +- `GGML_OPENVINO_COMPILE_MEM_SPILL` is ignored on Windows and in cache-only mode. - `-lm none` (no mmap) does not lower the memory in use. Cache-only mode needs mmap loading and stops with an error with `-lm none`. - The variables: [Memory optimization](OpenVINO-ENV-VARS.md#memory-optimization). @@ -672,10 +675,8 @@ This needs a 64 GB system. ```bash export GGML_OPENVINO_DEVICE=GPU -export GGML_OPENVINO_SPILL=1 -export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill # local disk, not tmpfs +export GGML_OPENVINO_COMPILE_MEM_SPILL=1 export GGML_OPENVINO_ROPE_SINCOS=device_f32 # long prompts -mkdir -p $GGML_OPENVINO_SPILL_DIR ./build/ReleaseOV/bin/llama-server -m Muse-Glimmer-30B-Q4_K_M.gguf -md .gguf \ --spec-type draft-dflash --spec-draft-n-max 4 ``` diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index d193b0bf684b..243a40c5cf2a 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -79,10 +79,10 @@ These variables lower the host memory peak. They do not change the output. Comma | Variable | Device | Type | Default | Description | |---|---|---|---|---| -| `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | unset | When set, the default of `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, of `GGML_OPENVINO_RELEASE_WEIGHTS`. `0` also keeps the host weights on GPU. | +| `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | unset | When set, the default of `GGML_OPENVINO_REDUCE_COMPILE_MEM`, of `GGML_OPENVINO_COMPILE_MEM_SPILL` (`1` sets `0.1`) and, on GPU, of `GGML_OPENVINO_RELEASE_WEIGHTS`. `0` also keeps the host weights on GPU. | | `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. | -| `GGML_OPENVINO_SPILL` | CPU, GPU | Float | `0` | Back the host buffers of the backend (weights, KV cache, compute) with files in `GGML_OPENVINO_SPILL_DIR`, so the kernel can drop their pages. `0`: off. `1`: on. A fraction in between: on, and while the model loads and compiles, keep at most this fraction of the spilled weights in RAM, also when RAM is free (`0.1` keeps 10%, Linux 5.4 or later); the model file's pages are dropped too, and the first token can come later, while the weights are written to disk. Needs free disk space of about the model size. NPU: only with `GGML_OPENVINO_NPU_L0_HOST_TENSORS=0`. Not part of the cache key. Ignored on Windows and in cache-only mode. | -| `GGML_OPENVINO_SPILL_DIR` | CPU, GPU | String | `/var/tmp` | Directory for the `GGML_OPENVINO_SPILL` files. Use real storage, not tmpfs (`/tmp` on many systems). Set without `GGML_OPENVINO_SPILL`, it turns spilling on, as `GGML_OPENVINO_SPILL=1`. | +| `GGML_OPENVINO_COMPILE_MEM_SPILL` | CPU, GPU | Float | `0.1` with `GGML_OPENVINO_MEMORY_OPTIMIZE=1`, else `0` | Back the host buffers of the backend (weights, KV cache, compute) with files in `GGML_OPENVINO_COMPILE_MEM_SPILL_DIR`, so the kernel can drop their pages. `0`: off. `1`: on, but the kernel drops the pages only when RAM runs out, so the memory peak does not change while RAM is free. A fraction in between: on, and while the model loads and compiles, keep at most this fraction of the spilled weights in RAM, also when RAM is free (`0.1` keeps 10%, Linux 5.4 or later). A fraction lowers the peak the most; the model file's pages are dropped too, and the first token can come later, while the weights are written to disk. Each start writes the buffers to disk: the load takes longer, and decoding can be a little slower. The disk space is reserved when the files are created (not for rewrites on btrfs or ZFS): more than the model size, on CPU also the KV cache. With too little space, the backend warns and uses RAM. NPU: off unless set, and only with `GGML_OPENVINO_NPU_L0_HOST_TENSORS=0`. Not part of the cache key. Ignored on Windows and in cache-only mode. | +| `GGML_OPENVINO_COMPILE_MEM_SPILL_DIR` | CPU, GPU | String | `/var/tmp` | Directory for the `GGML_OPENVINO_COMPILE_MEM_SPILL` files. Use real storage, not tmpfs (`/tmp` on many systems): on tmpfs, the backend warns and uses RAM. | | `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least this size get demand-zero host memory instead of Level Zero host memory. | ## NPU plugin properties diff --git a/ggml/src/ggml-openvino/dev_doc/README.md b/ggml/src/ggml-openvino/dev_doc/README.md index cfc38aa54d29..ee169e909cf9 100644 --- a/ggml/src/ggml-openvino/dev_doc/README.md +++ b/ggml/src/ggml-openvino/dev_doc/README.md @@ -86,7 +86,7 @@ Settings that must stay exactly the same between the runs, including set versus Settings that can differ: -- `GGML_OPENVINO_SPILL` and `GGML_OPENVINO_SPILL_DIR`: optional on the first run and ignored in cache-only mode. Host-weight release is disabled in cache-only mode. +- `GGML_OPENVINO_COMPILE_MEM_SPILL` and `GGML_OPENVINO_COMPILE_MEM_SPILL_DIR`: optional on the first run and ignored in cache-only mode. Host-weight release is disabled in cache-only mode. - `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`: changes only the output bindings. - `GGML_OPENVINO_KV_SLICE`: a runtime binding option for dynamic graphs. The same dynamic compiled graph accepts full-capacity and live-prefix attention K/V tensors. Eligibility: [KV cache binding](#kv-cache-binding). diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 14f5da0c34ca..f258bb42ea4e 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -128,8 +128,8 @@ constexpr env_var env_vars[] = { // Text {"GGML_OPENVINO_DEVICE", env_type::STR}, {"GGML_OPENVINO_CACHE_DIR", env_type::STR}, - {"GGML_OPENVINO_SPILL", env_type::FLOAT}, - {"GGML_OPENVINO_SPILL_DIR", env_type::STR}, + {"GGML_OPENVINO_COMPILE_MEM_SPILL", env_type::FLOAT}, + {"GGML_OPENVINO_COMPILE_MEM_SPILL_DIR", env_type::STR}, {"GGML_OPENVINO_DEBUG_NODE", env_type::STR}, {"GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR", env_type::STR}, {"GGML_OPENVINO_NPU_COMPILE_CONFIG", env_type::STR}, @@ -276,7 +276,7 @@ std::string checked_env_value(const env_var & var, const char * value) { if (end == value || !trim_spaces(end).empty()) { GGML_ABORT("ggml-openvino: %s=%s is not valid, use a number", var.name, value); } - if (std::strcmp(var.name, "GGML_OPENVINO_SPILL") == 0 && !(number >= 0 && number <= 1)) { + if (std::strcmp(var.name, "GGML_OPENVINO_COMPILE_MEM_SPILL") == 0 && !(number >= 0 && number <= 1)) { GGML_ABORT("ggml-openvino: %s=%s is not valid, use 0 (off), 1 (on) or a fraction in between (0.1)", var.name, value); } diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 8c5fa5811c7f..fc372927b022 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -290,9 +290,9 @@ void ggml_openvino_unregister_weight_buffer(const void * data); void ggml_openvino_release_weight_buffers(); bool ggml_openvino_restore_weight_buffers(); -// A GGML_OPENVINO_SPILL fraction: the limiters trim the spilled weights while the model loads, and while one of these is -// alive and for 10 s after, and sleep otherwise. Hold one around compile_model (it reads the weights back) and around rewriting released -// weights. +// A GGML_OPENVINO_COMPILE_MEM_SPILL fraction: the limiters trim the spilled weights while the model loads, and while +// one of these is alive and for 10 s after, and sleep otherwise. Hold one around compile_model (it reads the weights +// back) and around rewriting released weights. struct ggml_openvino_spill_trim_scope { ggml_openvino_spill_trim_scope(); ~ggml_openvino_spill_trim_scope(); diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 6cf94a1fea1b..24b9b64a49cd 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -52,9 +52,13 @@ # include # include # include +# ifdef __linux__ +# include +# include +# endif #endif -// A GGML_OPENVINO_SPILL fraction needs MADV_PAGEOUT (Linux 5.4) +// A GGML_OPENVINO_COMPILE_MEM_SPILL fraction needs MADV_PAGEOUT (Linux 5.4) #if defined(__linux__) && defined(MADV_PAGEOUT) # define GGML_OPENVINO_SPILL_LIMITER #endif @@ -82,7 +86,7 @@ std::atomic spill_scopes{0}; std::atomic spill_scope_end_us{0}; #ifdef GGML_OPENVINO_SPILL_LIMITER -// GGML_OPENVINO_SPILL with a fraction: keep at most a budget of a spilled weight buffer in RAM. +// GGML_OPENVINO_COMPILE_MEM_SPILL with a fraction: keep at most a budget of a spilled weight buffer in RAM. // Spilled pages are file-backed, but the kernel only evicts them under memory pressure, so on a machine with free // RAM the whole buffer stays resident. A thread writes the dirty pages to the file and drops them: after every half // budget of weight writes while the model loads, and, while a ggml_openvino_spill_trim_scope is alive (compile_model @@ -123,7 +127,7 @@ class spill_resident_limiter { // The limiter stops at the first failed call: after a failed msync, dropping the pages could lose weights that // are not on disk. static void log_stop(const char * call) { - GGML_LOG_WARN("ggml-openvino: GGML_OPENVINO_SPILL: %s failed (%s), no limit from now on\n", call, + GGML_LOG_WARN("ggml-openvino: GGML_OPENVINO_COMPILE_MEM_SPILL: %s failed (%s), no limit from now on\n", call, strerror(errno)); } @@ -196,8 +200,8 @@ class spill_resident_limiter { std::thread thread_; }; -// The resident limit of a spilled buffer in bytes: the GGML_OPENVINO_SPILL fraction of its size, at least 1 MiB. 0 (no -// limit) for 1, or when the limit is not smaller than the buffer. +// The resident limit of a spilled buffer in bytes: the GGML_OPENVINO_COMPILE_MEM_SPILL fraction of its size, at least +// 1 MiB. 0 (no limit) for 1, or when the limit is not smaller than the buffer. static size_t ggml_openvino_spill_resident_budget(size_t buffer_size, double fraction) { if (!(fraction < 1)) { return 0; @@ -211,27 +215,78 @@ struct spill_resident_limiter { }; [[maybe_unused]] static size_t ggml_openvino_spill_resident_budget(size_t, double fraction) { // unused on Windows + // warn only when set explicitly, not through GGML_OPENVINO_MEMORY_OPTIMIZE static std::atomic warned{false}; - if (fraction < 1 && !warned.exchange(true)) { + if (fraction < 1 && ggml_openvino_getenv_str("GGML_OPENVINO_COMPILE_MEM_SPILL") != nullptr && + !warned.exchange(true)) { GGML_LOG_WARN( - "ggml-openvino: a GGML_OPENVINO_SPILL fraction needs Linux 5.4 or later, spilling without a limit\n"); + "ggml-openvino: a GGML_OPENVINO_COMPILE_MEM_SPILL fraction needs Linux 5.4 or later, spilling without a " + "limit\n"); } return 0; } #endif -// GGML_OPENVINO_SPILL, checked at startup: 0 off, 1 back the host buffers with files, a fraction in between also limits -// the spilled weights kept in RAM. GGML_OPENVINO_SPILL_DIR set alone means 1. Off in cache-only mode. +#ifndef _WIN32 +// GGML_OPENVINO_COMPILE_MEM_SPILL, checked at startup: 0 off, 1 back the host buffers with files, a fraction in between +// also limits the spilled weights kept in RAM. Unset: 0.1 with GGML_OPENVINO_MEMORY_OPTIMIZE=1, except on NPU, else 0. +// Off in cache-only mode. static double ggml_openvino_spill_fraction() { if (ggml_openvino_model_cache_only()) { return 0; } - if (const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_SPILL")) { + if (const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_COMPILE_MEM_SPILL")) { return std::strtod(v, nullptr); } - return ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR") != nullptr ? 1 : 0; + return !ggml_openvino_is_npu() && ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE") != 0 ? 0.1 : 0; } +// Back a buffer with a file in GGML_OPENVINO_COMPILE_MEM_SPILL_DIR (/var/tmp by default) via MAP_SHARED instead of +// anonymous memory. Anonymous pages can only be evicted to swap, so the repacked weights stay resident alongside the +// mmap'd source: that double residency is the load-time peak. File-backed pages are reclaimable: the kernel can write +// them back and drop them, then read them again on demand. The file is unlinked at once, so it disappears when the +// process exits. Returns nullptr with a warning when the file cannot be made; the caller then uses anonymous memory. +static void * ggml_openvino_spill_map(size_t size, const char * dir) { +# ifdef __linux__ + // On tmpfs or ramfs the file is RAM itself, and reserving its space below would make all of it resident at once. + struct statfs fs; + if (statfs(dir, &fs) == 0 && (fs.f_type == TMPFS_MAGIC || fs.f_type == RAMFS_MAGIC)) { + GGML_LOG_WARN("%s: the spill directory %s is in RAM (tmpfs), using anonymous memory\n", __func__, dir); + return nullptr; + } +# endif + char path[PATH_MAX]; + snprintf(path, sizeof(path), "%s/ggml-ov-weights-%d-XXXXXX", dir, (int) getpid()); + const int fd = mkstemp(path); + if (fd < 0) { + GGML_LOG_WARN("%s: cannot create a spill file in %s (%s), using anonymous memory\n", __func__, dir, + strerror(errno)); + return nullptr; + } + int err = unlink(path) == 0 && ftruncate(fd, (off_t) size) == 0 ? 0 : errno; +# ifdef __linux__ + // Reserve the disk space now: on a full disk, the first write to a page of a sparse file kills the process with + // SIGBUS. fallocate allocates without writing; a filesystem without it keeps the sparse file. Copy-on-write + // filesystems (btrfs, ZFS) can still need new space when a page is written again. + if (err == 0 && fallocate(fd, 0, 0, (off_t) size) != 0 && errno != EOPNOTSUPP) { + err = errno; + } +# endif + void * m = MAP_FAILED; + if (err == 0) { + m = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + err = m == MAP_FAILED ? errno : 0; + } + close(fd); // the mapping keeps the file alive + if (err != 0) { + GGML_LOG_WARN("%s: cannot spill %zu MB to %s (%s), using anonymous memory\n", __func__, size / 1024 / 1024, dir, + strerror(err)); + return nullptr; + } + return m; +} +#endif + // Buffer context that manages per-tensor allocations (no contiguous buffer for weights) struct ggml_backend_openvino_buffer_context { int device; @@ -264,8 +319,8 @@ struct ggml_backend_openvino_buffer_context { // data is in the weight buffer registry bool weight_registered = false; - // A GGML_OPENVINO_SPILL fraction on a spilled buffer. The limiter starts at the first weight write: the buffer's - // usage is not known when it is allocated, and KV cache and compute buffers must not be paged out. + // A GGML_OPENVINO_COMPILE_MEM_SPILL fraction on a spilled buffer. The limiter starts at the first weight write: the + // buffer's usage is not known when it is allocated, and KV cache and compute buffers must not be paged out. std::unique_ptr spill_limiter; size_t spill_budget = 0; // source mappings already evicted once under the budget @@ -339,56 +394,31 @@ struct ggml_backend_openvino_buffer_context { data = nullptr; } } - if (data != nullptr) { - // backed by the Level Zero host tensor above - } else + if (data == nullptr) { #ifndef _WIN32 - if (const double spill = ggml_openvino_spill_fraction(); spill > 0) { - // Disk-backed weight buffer: back the repacked weights with a temp file via MAP_SHARED - // instead of anonymous memory. Anonymous pages can only be evicted to swap, so the - // repacked buffer stays pinned alongside the mmap'd source and both are resident at once - // -- that double residency is the load-time peak. File-backed pages are reclaimable: the - // kernel can write them back and drop them under pressure, then re-read on demand, so RSS - // becomes a working set rather than the whole buffer. The file is unlinked immediately, - // so it disappears when the process exits. - // - // The directory must be real storage. Pointing this at a tmpfs mount (/tmp on many - // systems) backs the "spill" with RAM and makes matters worse. - const char * spill_dir = ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR", "/var/tmp"); - char path[PATH_MAX]; - snprintf(path, sizeof(path), "%s/ggml-ov-weights-%d-XXXXXX", spill_dir, (int) getpid()); - int fd = mkstemp(path); - if (fd < 0) { - GGML_LOG_ERROR("%s: mkstemp(%s) failed: %s\n", __func__, path, strerror(errno)); - return; - } - unlink(path); // anonymous-but-file-backed: freed on process exit - if (ftruncate(fd, (off_t) size) != 0) { - GGML_LOG_ERROR("%s: ftruncate(%zu) failed: %s\n", __func__, size, strerror(errno)); - close(fd); - return; + if (const double spill = ggml_openvino_spill_fraction(); spill > 0) { + const char * spill_dir = + ggml_openvino_getenv_str("GGML_OPENVINO_COMPILE_MEM_SPILL_DIR", "/var/tmp"); + data = ggml_openvino_spill_map(size, spill_dir); + if (data != nullptr) { + spill_mapping = data; + spill_size = size; + GGML_LOG_INFO("%s: buffer spilled to %s (%zu MB, file-backed)\n", __func__, spill_dir, + size / 1024 / 1024); + spill_budget = ggml_openvino_spill_resident_budget(size, spill); + ov_buffer = std::make_shared(ov::element::u8, ov::Shape{size}, data); + } } - void * m = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - close(fd); // the mapping keeps the file alive - if (m == MAP_FAILED) { - GGML_LOG_ERROR("%s: mmap(%zu) failed: %s\n", __func__, size, strerror(errno)); - return; - } - data = m; - spill_mapping = m; - spill_size = size; - GGML_LOG_INFO("%s: weight buffer spilled to %s (%zu MB, file-backed)\n", __func__, spill_dir, - size / 1024 / 1024); - spill_budget = ggml_openvino_spill_resident_budget(size, spill); - ov_buffer = std::make_shared(ov::element::u8, ov::Shape{size}, data); - } else -#endif - { -#ifdef _WIN32 - if (ggml_openvino_spill_fraction() > 0) { - GGML_LOG_WARN("%s: GGML_OPENVINO_SPILL is not supported on Windows, ignoring\n", __func__); +#else + // only when set explicitly, not through GGML_OPENVINO_MEMORY_OPTIMIZE + const char * spill = ggml_openvino_getenv_str("GGML_OPENVINO_COMPILE_MEM_SPILL"); + if (spill != nullptr && std::strtod(spill, nullptr) > 0) { + GGML_LOG_WARN("%s: GGML_OPENVINO_COMPILE_MEM_SPILL is not supported on Windows, ignoring\n", + __func__); } #endif + } + if (data == nullptr) { // Anonymous OS memory reads as zero without being touched, so a buffer becomes resident only as it // is written: a weight buffer tensor by tensor while the model loads, the host-untouched prefill // compute buffer never. @@ -904,10 +934,10 @@ static bool ggml_openvino_range_has_locked_pages(uintptr_t first, uintptr_t last #endif #ifdef GGML_OPENVINO_SPILL_LIMITER -// Before a weight is written into a spilled buffer with a GGML_OPENVINO_SPILL fraction: start the limiter on the first -// weight, and evict the GGUF once. llama.cpp maps it with MAP_POPULATE, so the whole file is resident before the first -// tensor arrives; after the eviction, each tensor is read from disk when it is converted. The GGUF madvise calls are -// hints: they fail on locked pages (--mlock), which only keeps the pages. +// Before a weight is written into a spilled buffer with a GGML_OPENVINO_COMPILE_MEM_SPILL fraction: start the limiter +// on the first weight, and evict the GGUF once. llama.cpp maps it with MAP_POPULATE, so the whole file is resident +// before the first tensor arrives; after the eviction, each tensor is read from disk when it is converted. The GGUF +// madvise calls are hints: they fail on locked pages (--mlock), which only keeps the pages. static void ggml_openvino_spill_before_weight_write(ggml_backend_openvino_buffer_context * ctx, const void * data, size_t size) { @@ -919,12 +949,14 @@ static void ggml_openvino_spill_before_weight_write(ggml_backend_openvino_buffer ctx->spill_limiter = std::make_unique(ctx->spill_mapping, ctx->spill_size, ctx->spill_budget); } catch (const std::system_error & e) { - GGML_LOG_WARN("%s: cannot start the GGML_OPENVINO_SPILL thread (%s), no limit\n", __func__, e.what()); + GGML_LOG_WARN("%s: cannot start the GGML_OPENVINO_COMPILE_MEM_SPILL thread (%s), no limit\n", __func__, + e.what()); ctx->spill_budget = 0; return; } - GGML_LOG_INFO("%s: at most %zu of %zu MB of the spilled weights stay in RAM (GGML_OPENVINO_SPILL)\n", __func__, - ctx->spill_budget / 1024 / 1024, ctx->spill_size / 1024 / 1024); + GGML_LOG_INFO( + "%s: at most %zu of %zu MB of the spilled weights stay in RAM (GGML_OPENVINO_COMPILE_MEM_SPILL)\n", + __func__, ctx->spill_budget / 1024 / 1024, ctx->spill_size / 1024 / 1024); } const ggml_openvino_source_mapping * mapping = ggml_openvino_find_source_mapping(data, size, ctx->source_mappings); if (mapping == nullptr) { diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index 121a4584116a..ca6d0633844b 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -169,8 +169,8 @@ void ggml_openvino_model_cache_init() { #endif if (cache_only) { auto & config = ggml_openvino_get_device_config(); - config.environment_variables.erase("GGML_OPENVINO_SPILL"); - config.environment_variables.erase("GGML_OPENVINO_SPILL_DIR"); + config.environment_variables.erase("GGML_OPENVINO_COMPILE_MEM_SPILL"); + config.environment_variables.erase("GGML_OPENVINO_COMPILE_MEM_SPILL_DIR"); config.environment_variables["GGML_OPENVINO_RELEASE_WEIGHTS"] = "0"; } } From 234dabb5d5d4e919b60b7be27ab15354c2549ba3 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Fri, 4 Dec 2026 05:32:48 +0530 Subject: [PATCH 6/6] openvino: clang-format fixes --- ggml/src/ggml-openvino/ggml-openvino.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 24b9b64a49cd..fe1b050fb6af 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -93,9 +93,12 @@ std::atomic spill_scope_end_us{0}; // reads the weights back) and for 10 s after (the CPU plugin's first inference reads them too), whenever the resident // part exceeds the budget. Otherwise it sleeps. class spill_resident_limiter { - public: +public: spill_resident_limiter(void * data, size_t size, size_t budget) : - data_(data), size_(size), budget_(budget), page_(static_cast(sysconf(_SC_PAGESIZE))) { + data_(data), + size_(size), + budget_(budget), + page_(static_cast(sysconf(_SC_PAGESIZE))) { thread_ = std::thread([this] { run(); }); } @@ -121,7 +124,7 @@ class spill_resident_limiter { } } - private: +private: static bool in_scope() { return spill_scopes > 0 || ggml_time_us() - spill_scope_end_us < 10 * 1000 * 1000; } // The limiter stops at the first failed call: after a failed msync, dropping the pages could lose weights that @@ -2553,8 +2556,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { !ov::frontend::ggml::op::gdn_per_key_gate_supported()) { reason = "GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 gate for state " "snapshots or the native state layout"; - } - else if (op->op_params[0] > 1) { + } else if (op->op_params[0] > 1) { if (ggml_openvino_is_static()) { reason = "GATED_DELTA_NET snapshots require dynamic execution"; }