diff --git a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md index 1106ed15864e..1324f59a50e7 100644 --- a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md +++ b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md @@ -611,10 +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 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. -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). @@ -622,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_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_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_DIR` 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). @@ -667,9 +675,8 @@ This needs a 64 GB system. ```bash export GGML_OPENVINO_DEVICE=GPU -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 10f1f46e12a4..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,9 +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_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_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 bd486b8a1090..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_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 4a9be2968686..f258bb42ea4e 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -128,7 +128,8 @@ constexpr env_var env_vars[] = { // Text {"GGML_OPENVINO_DEVICE", env_type::STR}, {"GGML_OPENVINO_CACHE_DIR", env_type::STR}, - {"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}, @@ -271,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_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); + } break; } case env_type::BOOL: diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index ad0b447de401..fc372927b022 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(); +// 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(); + 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 a89f476af720..fe1b050fb6af 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -13,7 +13,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -33,7 +35,10 @@ #include #include #include +#include +#include #include +#include #include #ifdef _WIN32 @@ -47,6 +52,15 @@ # include # include # include +# ifdef __linux__ +# include +# include +# endif +#endif + +// 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 // ===================================================== @@ -67,6 +81,215 @@ // ===================================================== namespace { +// Live ggml_openvino_spill_trim_scope objects, and when the last one ended +std::atomic spill_scopes{0}; +std::atomic spill_scope_end_us{0}; + +#ifdef GGML_OPENVINO_SPILL_LIMITER +// 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 +// 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) : + 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: + 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 + // are not on disk. + static void log_stop(const char * call) { + GGML_LOG_WARN("ggml-openvino: GGML_OPENVINO_COMPILE_MEM_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. SIZE_MAX + // when mincore fails. + 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) { + log_stop("mincore"); + return SIZE_MAX; + } + for (size_t i = 0; i < n; i++) { + resident += pages[i] & 1; + } + sampled += n; + } + return sampled ? static_cast(double(resident) / sampled * size_) : 0; + } + + // false when a call failed + bool page_out() { + // dirty file pages cannot be dropped until written back + if (msync(data_, size_, MS_SYNC) != 0) { + log_stop("msync"); + return false; + } + if (madvise(data_, size_, MADV_PAGEOUT) != 0) { + log_stop("madvise(MADV_PAGEOUT)"); + return false; + } + return true; + } + + void run() { + std::unique_lock lock(wake_mutex_); + while (!stop_) { + // 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 && !in_scope()) { + continue; + } + lock.unlock(); + const size_t resident = requested ? size_ : resident_bytes(); + if (resident == SIZE_MAX || (resident > budget_ && !page_out())) { + return; + } + lock.lock(); + } + } + + void * data_; + size_t size_; + size_t budget_; + size_t page_; + size_t written_ = 0; // only the loading thread writes weights + std::mutex wake_mutex_; + std::condition_variable wake_; + bool stop_ = false; + bool page_out_requested_ = false; + std::thread thread_; +}; + +// 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; + } + 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 + // warn only when set explicitly, not through GGML_OPENVINO_MEMORY_OPTIMIZE + static std::atomic warned{false}; + if (fraction < 1 && ggml_openvino_getenv_str("GGML_OPENVINO_COMPILE_MEM_SPILL") != nullptr && + !warned.exchange(true)) { + GGML_LOG_WARN( + "ggml-openvino: a GGML_OPENVINO_COMPILE_MEM_SPILL fraction needs Linux 5.4 or later, spilling without a " + "limit\n"); + } + return 0; +} +#endif + +#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_COMPILE_MEM_SPILL")) { + return std::strtod(v, nullptr); + } + 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; @@ -99,6 +322,12 @@ struct ggml_backend_openvino_buffer_context { // data is in the weight buffer registry bool weight_registered = false; + // 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 + std::vector evicted_sources; // 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. @@ -168,55 +397,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 char * spill_dir = - ggml_openvino_model_cache_only() ? nullptr : ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR")) { - // 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. - 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; + 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); + } } - 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; - } - 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); - 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__); +#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. @@ -265,6 +470,7 @@ struct ggml_backend_openvino_buffer_context { if (kv_on_demand) { ggml_openvino_kv_storage_unregister(data, size); } + spill_limiter.reset(); // its thread reads the mapping if (spill_mapping != nullptr) { #ifdef _WIN32 VirtualFree(spill_mapping, 0, MEM_RELEASE); @@ -463,6 +669,15 @@ void ggml_openvino_unregister_weight_buffer(const void * data) { reg.buffers.end()); } +ggml_openvino_spill_trim_scope::ggml_openvino_spill_trim_scope() { + spill_scopes++; +} + +ggml_openvino_spill_trim_scope::~ggml_openvino_spill_trim_scope() { + spill_scope_end_us = ggml_time_us(); + spill_scopes--; +} + void ggml_openvino_release_weight_buffers() { auto & reg = ov_weight_registry(); std::lock_guard lock(reg.mutex); @@ -503,6 +718,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); } @@ -513,6 +729,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"); } @@ -719,6 +936,49 @@ 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_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) { + if (ctx->spill_budget == 0) { + return; + } + 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_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_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) { + 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 // 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 +1006,12 @@ static void ggml_openvino_release_source_pages(ggml_backend_openvino_buffer_cont VirtualUnlock(reinterpret_cast(first), last - first); } #elif defined(__linux__) +# 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); // a hint, as above + } +# endif // MADV_DONTNEED fails on locked (mlock) memory and leaves it resident madvise(reinterpret_cast(first), last - first, MADV_DONTNEED); #endif @@ -786,6 +1052,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer memcpy(tensor->data, data, size); return; } + 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); @@ -811,6 +1078,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); } + if (ctx->spill_limiter) { + ctx->spill_limiter->note_write(ggml_nbytes(tensor)); + } } 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); @@ -820,6 +1090,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(); @@ -840,6 +1113,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; @@ -2280,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"; } diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index f5921fce8a21..ca6d0633844b 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -169,7 +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_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"; } } 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();