OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[Core][GPU] Prefetch constants during model compilation in GPU (#38993)
Oleg Pipikin06c75721f31f
diff --git a/src/common/util/include/openvino/util/memory.hpp b/src/common/util/include/openvino/util/memory.hppindex 6086b2099af..fdeda45271a 100644--- a/src/common/util/include/openvino/util/memory.hpp+++ b/src/common/util/include/openvino/util/memory.hpp@@ -7,6 +7,7 @@#include <cstddef>#include <cstdint>#include <cstdlib>+#include <future>#include <limits>#include <memory>#include <optional>@@ -141,6 +142,9 @@ struct MemoryProperties {size_t offset = 0; //!< Offset of this buffer within the allocation identified by IBuffer::get_id().};+/** @brief Handle to wait for a background prefetch; an invalid handle means there is nothing to wait for. */+using PrefetchToken = std::shared_future<void>;+/** @brief Read-only, non-owning view (pointer + size) of a buffer's contents. */class MemoryView {public:diff --git a/src/common/util/include/openvino/util/mmap_object.hpp b/src/common/util/include/openvino/util/mmap_object.hppindex 815776732e7..27b9f4034ae 100644--- a/src/common/util/include/openvino/util/mmap_object.hpp+++ b/src/common/util/include/openvino/util/mmap_object.hpp@@ -79,8 +79,10 @@ public:* @param offset Offset within the mapping where prefetching starts.* @param size Number of bytes to prefetch. Defaults to the rest of the* mapping when set to auto_size.+ * @return A handle that can be waited on to know when the region is actually resident; an+ * invalid handle means there is nothing to wait for.*/- virtual void hint_prefetch_async(size_t offset = 0, size_t size = auto_size) = 0;+ virtual util::PrefetchToken hint_prefetch_async(size_t offset = 0, size_t size = auto_size) noexcept = 0;};/**diff --git a/src/common/util/src/memory_prefetch.cpp b/src/common/util/src/memory_prefetch.cppindex c93b45a23a4..9051bd8cbac 100644--- a/src/common/util/src/memory_prefetch.cpp+++ b/src/common/util/src/memory_prefetch.cpp@@ -4,14 +4,16 @@#include "memory_prefetch.hpp"+#include <atomic>#include <condition_variable>#include <cstdint>+#include <exception>#include <functional>#include <future>#include <list>+#include <memory>#include <mutex>#include <new>-#include <stdexcept>#include <thread>#include <vector>@@ -77,19 +79,8 @@ public:ThreadPool(ThreadPool&&) = delete;ThreadPool& operator=(ThreadPool&&) = delete;- std::vector<std::future<void>> submit(std::vector<std::function<void()>>&& jobs) {- std::vector<std::future<void>> futures;- futures.reserve(jobs.size());- std::list<std::function<void()>> pending;- for (auto& job : jobs) {- auto task = std::make_shared<std::packaged_task<void()>>(std::move(job));- futures.push_back(task->get_future());- pending.emplace_back([task]() {- (*task)();- });- }- m_queue.push(std::move(pending));- return futures;+ void submit(std::list<std::function<void()>>&& jobs) noexcept {+ m_queue.push(std::move(jobs));}private:@@ -124,28 +115,54 @@ private:std::vector<std::thread> m_workers;};+// Counts the page-population chunks of one request down to zero; the last chunk to finish fulfills+// the promise, so the whole region is reported through a single handle without parking a pool+// worker on a join.+class CompletionLatch {+public:+ explicit CompletionLatch(size_t chunk_count) : m_remaining(chunk_count) {}++ void count_down() noexcept {+ if (m_remaining.fetch_sub(1, std::memory_order_acq_rel) == 1) {+ m_promise.set_value();+ }+ }++ PrefetchToken get_future() {+ return m_promise.get_future().share();+ }++private:+ std::atomic<size_t> m_remaining;+ std::promise<void> m_promise;+};+} // namespace-std::vector<std::future<void>> submit_page_toucher_tasks(void* ptr, size_t size, size_t num_threads) noexcept {+PrefetchToken submit_page_toucher_tasks(void* ptr, size_t size, size_t num_threads) noexcept {try {const auto page_size = static_cast<size_t>(get_system_page_size());const auto chunk_size =std::max<size_t>(align_size_up(size / num_threads, page_size), default_parallel_io_min_chunk);+ const auto chunk_count = ceil_div(size, chunk_size);+ if (chunk_count == 0) {+ return {};+ }- std::vector<std::function<void()>> jobs;- jobs.reserve(ceil_div(size, chunk_size));-+ auto latch = std::make_shared<CompletionLatch>(chunk_count);+ std::list<std::function<void()>> jobs;for (auto first = reinterpret_cast<const uint8_t*>(ptr), last = first + size; first < last;first += chunk_size) {- jobs.emplace_back(PageToucher{first, std::min(first + chunk_size, last), page_size});+ jobs.emplace_back([latch, toucher = PageToucher{first, std::min(first + chunk_size, last), page_size}]() {+ toucher();+ latch->count_down();+ });}- return ThreadPool::instance().submit(std::move(jobs));- } catch (const std::bad_alloc&) {- // Job/future/packaged_task allocation failed under memory pressure.- return {};- } catch (const std::length_error&) {- // vector::reserve()'s requested capacity exceeded max_size() (e.g. a pathological- // ptr/size/num_threads combination producing an absurd chunk count).+ // Taken before the jobs can run: std::promise forbids concurrent get_future()/set_value().+ auto future = latch->get_future();+ ThreadPool::instance().submit(std::move(jobs));+ return future;+ } catch (const std::exception&) {return {};}}diff --git a/src/common/util/src/memory_prefetch.hpp b/src/common/util/src/memory_prefetch.hppindex 3da82c4e72e..9fe17c54f72 100644--- a/src/common/util/src/memory_prefetch.hpp+++ b/src/common/util/src/memory_prefetch.hpp@@ -9,7 +9,6 @@#include <cstdint>#include <future>#include <thread>-#include <vector>#include "openvino/util/memory.hpp"#include "openvino/util/mmap_object.hpp"@@ -32,8 +31,6 @@ struct PageToucher {}};-class PrefetchToken;-/*** @brief Pre-fetches a page-aligned, committed VM range into physical memory, blocking until every* page is resident.@@ -47,73 +44,19 @@ void vm_prefetch(void* ptr, size_t size, size_t num_threads) noexcept;/*** @brief Asynchronous variant of @ref vm_prefetch: submits page-population to the shared pool and- * returns immediately with a @ref PrefetchToken to wait on.+ * returns immediately with a handle reporting progress of the whole range.** @param ptr Page-aligned base address of the range.* @param size Multiple of the system page size.* @param num_threads Number of population jobs to split the range into; @c 0 requests only a- * lightweight advisory OS hint instead of touching pages and returns an empty- * token.+ * lightweight advisory OS hint instead of touching pages and returns an invalid+ * handle.*- * Returns an empty token if the work could not be scheduled.+ * The handle does not keep the populated memory alive: the caller must keep that memory valid until+ * the handle becomes ready. Returns an invalid handle if the work could not be scheduled.*/PrefetchToken vm_prefetch_async(void* ptr, size_t size, size_t num_threads) noexcept;-/**- * @brief Move-only RAII handle for background page-population started by @ref vm_prefetch_async.- *- * Destruction (or an explicit @ref wait) joins the outstanding work, so nothing is ever left- * running uncontrolled. The token does not keep the populated memory alive: the caller must keep- * that memory valid until the token completes, is destroyed, or its futures are @ref detach "detached".- */-class PrefetchToken {-public:- PrefetchToken() noexcept = default;- explicit PrefetchToken(std::vector<std::future<void>>&& tasks) noexcept : m_tasks(std::move(tasks)) {}-- PrefetchToken(const PrefetchToken&) = delete;- PrefetchToken& operator=(const PrefetchToken&) = delete;- PrefetchToken(PrefetchToken&&) noexcept = default;-- PrefetchToken& operator=(PrefetchToken&& other) noexcept {- if (this != &other) {- wait();- m_tasks = std::move(other.m_tasks);- }- return *this;- }-- ~PrefetchToken() {- wait();- }-- void wait() noexcept {- for (auto& task : m_tasks) {- if (task.valid()) {- task.wait();- }- }- m_tasks.clear();- }-- std::vector<std::future<void>> detach() noexcept {- auto tasks = std::move(m_tasks);- m_tasks.clear();- return tasks;- }-- bool valid() const noexcept {- return !m_tasks.empty();- }-- explicit operator bool() const noexcept {- return valid();- }--private:- std::vector<std::future<void>> m_tasks;-};-/*** @brief Submits page-population jobs for [ptr, ptr + size) to the shared background thread pool,* splitting the range into up to @p num_threads chunks.@@ -122,9 +65,10 @@ private:* @param size Multiple of the system page size.* @param num_threads Number of population jobs to split the range into.*- * Returns an empty vector if the work could not be scheduled (e.g. an allocation failure).+ * Returns a handle that becomes ready once every chunk has been touched, or an invalid handle if+ * the work could not be scheduled (e.g. an allocation failure).*/-std::vector<std::future<void>> submit_page_toucher_tasks(void* ptr, size_t size, size_t num_threads) noexcept;+PrefetchToken submit_page_toucher_tasks(void* ptr, size_t size, size_t num_threads) noexcept;/*** @brief Clamps [offset, offset + size) to [0, mapping_size) and page-aligns the result, roundingdiff --git a/src/common/util/src/os/lin/lin_memory.cpp b/src/common/util/src/os/lin/lin_memory.cppindex 1483b02f5f9..33ae5493c73 100644--- a/src/common/util/src/os/lin/lin_memory.cpp+++ b/src/common/util/src/os/lin/lin_memory.cpp@@ -81,8 +81,8 @@ void vm_prefetch(void* ptr, size_t size, size_t num_threads) noexcept {assert(ptr != nullptr && size > 0);if (num_threads == 0) {madvise_hint(ptr, size);- } else {- PrefetchToken(submit_page_toucher_tasks(ptr, size, num_threads)).wait();+ } else if (const auto done = submit_page_toucher_tasks(ptr, size, num_threads); done.valid()) {+ done.wait();}}@@ -92,7 +92,7 @@ PrefetchToken vm_prefetch_async(void* ptr, size_t size, size_t num_threads) noexmadvise_hint(ptr, size);return {};}- return PrefetchToken(submit_page_toucher_tasks(ptr, size, num_threads));+ return submit_page_toucher_tasks(ptr, size, num_threads);}} // namespace ov::utildiff --git a/src/common/util/src/os/lin/lin_mmap_object.cpp b/src/common/util/src/os/lin/lin_mmap_object.cppindex dbdcb4c27cd..26773563c96 100644--- a/src/common/util/src/os/lin/lin_mmap_object.cpp+++ b/src/common/util/src/os/lin/lin_mmap_object.cpp@@ -113,24 +113,29 @@ class MapHolder final : public MappedMemory {size_t m_size = 0;std::optional<uint64_t> m_id;HandleHolder m_handle;- // Tasks adopted from hint_prefetch_async()'s token; joined before unmapping (see ~MapHolder).+ // Handles shared with hint_prefetch_async()'s caller; joined before unmapping (see ~MapHolder).std::mutex m_pending_prefetch_mutex;- std::vector<std::future<void>> m_pending_prefetch;-- void adopt_pending_prefetch(std::vector<std::future<void>>&& tasks) {- std::lock_guard<std::mutex> lock(m_pending_prefetch_mutex);- // Reap already-finished futures so the vector doesn't grow without bound across repeated- // hint_prefetch_async() calls over this mapping's lifetime.- m_pending_prefetch.erase(std::remove_if(m_pending_prefetch.begin(),- m_pending_prefetch.end(),- [](std::future<void>& task) {- return !task.valid() || task.wait_for(std::chrono::seconds(0)) ==- std::future_status::ready;- }),- m_pending_prefetch.end());- m_pending_prefetch.insert(m_pending_prefetch.end(),- std::make_move_iterator(tasks.begin()),- std::make_move_iterator(tasks.end()));+ std::vector<util::PrefetchToken> m_pending_prefetch;++ void adopt_pending_prefetch(util::PrefetchToken task) noexcept {+ if (task.valid()) {+ try {+ std::lock_guard<std::mutex> lock(m_pending_prefetch_mutex);+ // Reap already-finished handles so the vector doesn't grow without bound across repeated+ // hint_prefetch_async() calls over this mapping's lifetime.+ m_pending_prefetch.erase(std::remove_if(m_pending_prefetch.begin(),+ m_pending_prefetch.end(),+ [](util::PrefetchToken& pending) {+ return !pending.valid() ||+ pending.wait_for(std::chrono::seconds(0)) ==+ std::future_status::ready;+ }),+ m_pending_prefetch.end());+ m_pending_prefetch.push_back(std::move(task));+ } catch (const std::exception&) {+ task.wait();+ }+ }}void wait_for_pending_prefetch() noexcept {@@ -231,13 +236,16 @@ public:}}- void hint_prefetch_async(size_t offset, size_t size) override {+ util::PrefetchToken hint_prefetch_async(size_t offset, size_t size) noexcept override {if (const auto region = util::clamp_align_region(m_data, m_size, offset, size);region.m_length > util::default_parallel_io_threshold) {- auto token = util::vm_prefetch_async(reinterpret_cast<void*>(region.m_address),- region.m_length,- util::prefetch_thread_count(region.m_length));- adopt_pending_prefetch(token.detach());+ auto future = util::vm_prefetch_async(reinterpret_cast<void*>(region.m_address),+ region.m_length,+ util::prefetch_thread_count(region.m_length));+ adopt_pending_prefetch(future);+ return future;+ } else {+ return {};}}};diff --git a/src/common/util/src/os/win/win_memory.cpp b/src/common/util/src/os/win/win_memory.cppindex b0640b41874..97c95375383 100644--- a/src/common/util/src/os/win/win_memory.cpp+++ b/src/common/util/src/os/win/win_memory.cpp@@ -64,8 +64,8 @@ void vm_prefetch(void* ptr, size_t size, size_t num_threads) noexcept {if (num_threads == 0) {WIN32_MEMORY_RANGE_ENTRY entry{ptr, size};::PrefetchVirtualMemory(::GetCurrentProcess(), 1, &entry, 0);- } else {- PrefetchToken(submit_page_toucher_tasks(ptr, size, num_threads)).wait();+ } else if (const auto done = submit_page_toucher_tasks(ptr, size, num_threads); done.valid()) {+ done.wait();}}@@ -76,7 +76,7 @@ PrefetchToken vm_prefetch_async(void* ptr, size_t size, size_t num_threads) noex::PrefetchVirtualMemory(::GetCurrentProcess(), 1, &entry, 0);return {};}- return PrefetchToken(submit_page_toucher_tasks(ptr, size, num_threads));+ return submit_page_toucher_tasks(ptr, size, num_threads);}} // namespace ov::utildiff --git a/src/common/util/src/os/win/win_mmap_object.cpp b/src/common/util/src/os/win/win_mmap_object.cppindex abe58db9be8..e3f3a641331 100644--- a/src/common/util/src/os/win/win_mmap_object.cpp+++ b/src/common/util/src/os/win/win_mmap_object.cpp@@ -316,14 +316,14 @@ public:void hint_prefetch(size_t offset, size_t size) noexcept override;- void hint_prefetch_async(size_t offset, size_t size) override;+ util::PrefetchToken hint_prefetch_async(size_t offset, size_t size) noexcept override;private:/**- * @brief Adopts futures detached from a util::PrefetchToken, reaping already-finished ones so- * the pending list doesn't grow unbounded across repeated hint_prefetch_async() calls.+ * @brief Adopts the handle returned by util::vm_prefetch_async(), reaping already-finished ones+ * so the pending list doesn't grow unbounded across repeated hint_prefetch_async() calls.*/- void adopt_pending_prefetch(std::vector<std::future<void>>&& tasks);+ void adopt_pending_prefetch(util::PrefetchToken task) noexcept;/** @brief Joins all outstanding background prefetch tasks. Must run before any teardown that* unmaps or frees the view, since a detached task may still be touching those pages. */@@ -399,9 +399,9 @@ private:*/std::mutex m_slot_mutex;- // Tasks adopted from hint_prefetch_async()'s token; joined before unmapping (see ~MapHolder).+ // Handles shared with hint_prefetch_async()'s caller; joined before unmapping (see ~MapHolder).std::mutex m_pending_prefetch_mutex;- std::vector<std::future<void>> m_pending_prefetch;+ std::vector<util::PrefetchToken> m_pending_prefetch;};LONG NTAPI MmapVehRegistry::veh(PEXCEPTION_POINTERS ep) {@@ -801,20 +801,28 @@ util::AlignedRegion clamp_align_region(const void* data, size_t mapping_size, si} // namespace-void MapHolder::adopt_pending_prefetch(std::vector<std::future<void>>&& tasks) {- std::lock_guard<std::mutex> lock(m_pending_prefetch_mutex);- // Reap already-finished futures so the vector doesn't grow without bound across repeated- // hint_prefetch_async() calls over this mapping's lifetime.- m_pending_prefetch.erase(std::remove_if(m_pending_prefetch.begin(),- m_pending_prefetch.end(),- [](std::future<void>& task) {- return !task.valid() || task.wait_for(std::chrono::seconds(0)) ==- std::future_status::ready;- }),- m_pending_prefetch.end());- m_pending_prefetch.insert(m_pending_prefetch.end(),- std::make_move_iterator(tasks.begin()),- std::make_move_iterator(tasks.end()));+void MapHolder::adopt_pending_prefetch(util::PrefetchToken task) noexcept {+ if (task.valid()) {+ try {+ std::lock_guard<std::mutex> lock(m_pending_prefetch_mutex);+ // Reap already-finished handles so the vector doesn't grow without bound across repeated+ // hint_prefetch_async() calls over this mapping's lifetime.+ m_pending_prefetch.erase(std::remove_if(m_pending_prefetch.begin(),+ m_pending_prefetch.end(),+ [](util::PrefetchToken& pending) {+ return !pending.valid() ||+ pending.wait_for(std::chrono::seconds(0)) ==+ std::future_status::ready;+ }),+ m_pending_prefetch.end());+ m_pending_prefetch.push_back(std::move(task));+ } catch (const std::exception&) {+ // Bookkeeping failed (e.g. allocation failure): the prefetch already started in the+ // background, so block here instead of returning with it untracked, or ~MapHolder could+ // unmap while it is still touching these pages.+ task.wait();+ }+ }}void MapHolder::wait_for_pending_prefetch() noexcept {@@ -837,14 +845,16 @@ void MapHolder::hint_prefetch(size_t offset, size_t size) noexcept {}}-void MapHolder::hint_prefetch_async(size_t offset, size_t size) {+util::PrefetchToken MapHolder::hint_prefetch_async(size_t offset, size_t size) noexcept {if (const auto region = util::clamp_align_region(m_data, m_size, offset, size);region.m_length > util::default_parallel_io_threshold) {- auto token = util::vm_prefetch_async(reinterpret_cast<void*>(region.m_address),- region.m_length,- util::prefetch_thread_count(region.m_length));- adopt_pending_prefetch(token.detach());+ auto future = util::vm_prefetch_async(reinterpret_cast<void*>(region.m_address),+ region.m_length,+ util::prefetch_thread_count(region.m_length));+ adopt_pending_prefetch(future);+ return future;}+ return {};}std::pair<char*, char*> MapHolder::compute_evict_range(size_t offset, size_t size) const noexcept {diff --git a/src/core/dev_api/dev_headers.cmake b/src/core/dev_api/dev_headers.cmakeindex 76008975186..d1bf3b0fec7 100644--- a/src/core/dev_api/dev_headers.cmake+++ b/src/core/dev_api/dev_headers.cmake@@ -15,6 +15,7 @@ set(DEV_HEADERS${CMAKE_CURRENT_LIST_DIR}/openvino/core/tensor_util.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/core/validation_util.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/core/weight_sharing_util.hpp+ ${CMAKE_CURRENT_LIST_DIR}/openvino/core/weights_prefetch.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/core/rt_info/weightless_caching_attributes.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/core/type/element_iterator.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/core/type/element_type_info.hppdiff --git a/src/core/dev_api/openvino/core/weight_sharing_util.hpp b/src/core/dev_api/openvino/core/weight_sharing_util.hppindex caf5a51a7c0..f0de43ecf71 100644--- a/src/core/dev_api/openvino/core/weight_sharing_util.hpp+++ b/src/core/dev_api/openvino/core/weight_sharing_util.hpp@@ -10,6 +10,7 @@#include "openvino/core/core_visibility.hpp"#include "openvino/core/type/element_type.hpp"+#include "openvino/util/memory.hpp"namespace ov {class MappedMemory;@@ -131,6 +132,16 @@ struct OPENVINO_API Extension {* @param constant Constant node to evict buffer for.*/static void hint_evict(ov::op::v0::Constant& constant) noexcept;++ /** @brief Hint to start loading the constant's buffer into physical memory in the background.+ *+ * @note Returns immediately, the data is not guaranteed to be resident when the call returns.+ *+ * @param constant Constant node to prefetch buffer for.+ * @return A handle that can be waited on to know when the data is actually resident; an+ * invalid handle means there is nothing to wait for.+ */+ static ov::util::PrefetchToken hint_prefetch(const ov::op::v0::Constant& constant) noexcept;};/** @brief Get the source buffer for a given source id.diff --git a/src/core/dev_api/openvino/core/weights_prefetch.hpp b/src/core/dev_api/openvino/core/weights_prefetch.hppnew file mode 100644index 00000000000..1f096b8f9cc--- /dev/null+++ b/src/core/dev_api/openvino/core/weights_prefetch.hpp@@ -0,0 +1,91 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <memory>+#include <optional>+#include <unordered_map>+#include <vector>++#include "openvino/core/core_visibility.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/util/memory.hpp"++namespace ov::util {++/** @brief Loads the weights before they are read and evicts them after use. */+class OPENVINO_API IPrefetchScheduler {+public:+ virtual ~IPrefetchScheduler() = default;++ /** @brief Requests asynchronous prefetch of the node's weights if not already requested. Call it right before the+ * node is read. */+ virtual void acquire(const ov::Node& node) noexcept = 0;++ /** @brief Evicts the node weights and prefetches the next ones. Call it once the node is not read. */+ virtual void release(const ov::Node& node) noexcept = 0;+};++/**+ * @brief Loads the constants ahead of their consumer and evicts them after use.+ *+ * Fits a plugin that reads each constant once, in the order of ops. With lookahead = 2 and constants A B C D:+ * prefetch A, B; acquire A, release A (evict A, prefetch C); acquire B, release B (evict B, prefetch D); ...+ *+ * Non-constant nodes and constants not backed by a file mapping are ignored. Not thread safe.+ *+ * Entry states:+ * @verbatim+ pending ---(1)---> prefetch_requested ---(2)---> released+ | ^+ +----------------------(3)-----------------------++ @endverbatim+ * (1) prefetch_ahead() or acquire(), only if hint_prefetch() started loading (constant is file-backed).+ * (2) release(): waits for the load to finish, then evicts.+ * (3) release() of a constant that was never prefetched, or prefetch_ahead() finds the constant destroyed.+ *+ * released is final: the entry is never prefetched again.+ */+class OPENVINO_API OrderedPrefetchScheduler : public IPrefetchScheduler {+public:+ /**+ * @param ops Nodes in the order they are consumed; only the constants among them are tracked,+ * duplicates are ignored.+ * @param lookahead Minimum number of constants prefetched and not released yet.+ * @param min_bytes More constants are prefetched while fewer bytes than this are prefetched and not released yet.+ *+ * Default lookahead and min_bytes showed the best compile time in manual testing.+ */+ explicit OrderedPrefetchScheduler(const std::vector<std::shared_ptr<ov::Node>>& ops,+ size_t lookahead = 2,+ size_t min_bytes = 32 * one_mib);++ void acquire(const ov::Node& node) noexcept override;+ void release(const ov::Node& node) noexcept override;++private:+ enum class State { pending, prefetch_requested, released };++ struct Entry {+ std::weak_ptr<ov::op::v0::Constant> constant; // Does not keep the constant alive.+ size_t size; // Byte size, cached since weak_ptr may expire.+ State state = State::pending;+ PrefetchToken future; // Valid while state is prefetch_requested.+ };++ void prefetch(Entry& entry, const ov::op::v0::Constant& constant) noexcept;+ void prefetch_ahead() noexcept;+ std::optional<size_t> index_of(const ov::Node& node) const noexcept;++ std::vector<Entry> m_entries; // In the order of consumption.+ std::unordered_map<const ov::Node*, size_t> m_indices; // Constant address -> index into m_entries.+ size_t m_lookahead; // Minimum number of constants kept prefetched and not released.+ size_t m_min_bytes; // Minimum number of prefetched-and-not-released bytes.+ size_t m_next; // Index of the next constant to prefetch.+ size_t m_in_flight; // Number of constants currently prefetched and not released.+ size_t m_in_flight_bytes; // Bytes of the m_in_flight constants.+};+} // namespace ov::utildiff --git a/src/core/dev_api/openvino/runtime/aligned_buffer.hpp b/src/core/dev_api/openvino/runtime/aligned_buffer.hppindex 3aeff2af625..1e171718032 100644--- a/src/core/dev_api/openvino/runtime/aligned_buffer.hpp+++ b/src/core/dev_api/openvino/runtime/aligned_buffer.hpp@@ -9,6 +9,7 @@#include "openvino/core/attribute_adapter.hpp"#include "openvino/core/core_visibility.hpp"+#include "openvino/util/memory.hpp"namespace ov {@@ -77,12 +78,22 @@ public:/// \brief Ensures the buffer is available and populated with actual data.virtual void hint_prefetch() const;+ /// \brief Starts populating the buffer in the background and returns immediately.+ /// \return A handle that can be waited on to know when the data is actually resident; an+ /// invalid handle means there is nothing to wait for.+ virtual util::PrefetchToken hint_prefetch_async() const noexcept;+protected:virtual void hint_evict(size_t offset, size_t size) noexcept;static void invoke_evict(AlignedBuffer& buffer, size_t offset, size_t size) noexcept;static void invoke_hint_prefetch(const AlignedBuffer& buffer);+ virtual util::PrefetchToken hint_prefetch_async(size_t offset, size_t size) const noexcept;+ static util::PrefetchToken invoke_hint_prefetch_async(const AlignedBuffer& buffer,+ size_t offset,+ size_t size) noexcept;+char* m_aligned_buffer;size_t m_byte_size;};diff --git a/src/core/dev_api/openvino/runtime/shared_buffer.hpp b/src/core/dev_api/openvino/runtime/shared_buffer.hppindex e40e58c1621..501938a0daa 100644--- a/src/core/dev_api/openvino/runtime/shared_buffer.hpp+++ b/src/core/dev_api/openvino/runtime/shared_buffer.hpp@@ -44,6 +44,10 @@ public:}}+ util::PrefetchToken hint_prefetch_async() const noexcept override {+ return hint_prefetch_async(get_offset(), m_byte_size);+ }+protected:template <typename U>struct is_aligned_buffer_ptr : std::false_type {};@@ -57,8 +61,25 @@ protected:if (m_shared_object) {m_shared_object->hint_evict(offset, size);}- } else {+ } else if constexpr (is_aligned_buffer_ptr_v<T>) {+ if (m_shared_object) {+ invoke_evict(*m_shared_object, offset, size);+ }+ }+ }++ // The offset is relative to the root source buffer, so it is forwarded to the parents unchanged.+ util::PrefetchToken hint_prefetch_async(size_t offset, size_t size) const noexcept override {+ if constexpr (std::is_same_v<std::shared_ptr<ov::MappedMemory>, T>) {+ if (m_shared_object) {+ return m_shared_object->hint_prefetch_async(offset, size);+ }+ } else if constexpr (is_aligned_buffer_ptr_v<T>) {+ if (m_shared_object) {+ return invoke_hint_prefetch_async(*m_shared_object, offset, size);+ }}+ return {};}void hint_prefetch() const override {diff --git a/src/core/src/runtime/aligned_buffer.cpp b/src/core/src/runtime/aligned_buffer.cppindex 4a6c21b7339..63ebd683346 100644--- a/src/core/src/runtime/aligned_buffer.cpp+++ b/src/core/src/runtime/aligned_buffer.cpp@@ -60,4 +60,18 @@ void AlignedBuffer::hint_prefetch() const {}void AlignedBuffer::invoke_hint_prefetch(const AlignedBuffer& buffer) {buffer.hint_prefetch();}++util::PrefetchToken AlignedBuffer::hint_prefetch_async() const noexcept {+ return {};+}++util::PrefetchToken AlignedBuffer::hint_prefetch_async(size_t, size_t) const noexcept {+ return {};+}++util::PrefetchToken AlignedBuffer::invoke_hint_prefetch_async(const AlignedBuffer& buffer,+ size_t offset,+ size_t size) noexcept {+ return buffer.hint_prefetch_async(offset, size);+}} // namespace ovdiff --git a/src/core/src/sources.cmake b/src/core/src/sources.cmakeindex c71168e7d3b..ab6876c5b7a 100644--- a/src/core/src/sources.cmake+++ b/src/core/src/sources.cmake@@ -47,6 +47,7 @@ set(LIBRARY_SRC${CMAKE_CURRENT_LIST_DIR}/validation_util.cpp${CMAKE_CURRENT_LIST_DIR}/version.cpp${CMAKE_CURRENT_LIST_DIR}/weight_sharing_util.cpp+ ${CMAKE_CURRENT_LIST_DIR}/weights_prefetch.cpp${CMAKE_CURRENT_LIST_DIR}/descriptor/input.cpp${CMAKE_CURRENT_LIST_DIR}/descriptor/output.cpp${CMAKE_CURRENT_LIST_DIR}/descriptor/shared_tensor.cppdiff --git a/src/core/src/weight_sharing_util.cpp b/src/core/src/weight_sharing_util.cppindex 23f252617f2..dcec56a002d 100644--- a/src/core/src/weight_sharing_util.cpp+++ b/src/core/src/weight_sharing_util.cpp@@ -107,6 +107,11 @@ void Extension::hint_evict(ov::op::v0::Constant& constant) noexcept {}}+ov::util::PrefetchToken Extension::hint_prefetch(const ov::op::v0::Constant& constant) noexcept {+ return (constant.m_data && constant.m_data->get_descriptor()) ? constant.m_data->hint_prefetch_async()+ : ov::util::PrefetchToken{};+}+std::shared_ptr<ov::AlignedBuffer> get_source_buffer(const Context& shared_context, const DataID source_id) {const auto& weights = shared_context.m_cache_sources;if (auto weight_it = weights.find(source_id); weight_it != weights.end()) {diff --git a/src/core/src/weights_prefetch.cpp b/src/core/src/weights_prefetch.cppnew file mode 100644index 00000000000..c6d4c9cc6a5--- /dev/null+++ b/src/core/src/weights_prefetch.cpp@@ -0,0 +1,87 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/core/weights_prefetch.hpp"++#include <utility>++#include "openvino/core/node.hpp"+#include "openvino/core/type.hpp"+#include "openvino/core/weight_sharing_util.hpp"+#include "openvino/op/constant.hpp"++namespace ov::util {++OrderedPrefetchScheduler::OrderedPrefetchScheduler(const std::vector<std::shared_ptr<ov::Node>>& ops,+ size_t lookahead,+ size_t min_bytes)+ : m_lookahead(lookahead),+ m_min_bytes(min_bytes),+ m_next(0),+ m_in_flight(0),+ m_in_flight_bytes(0) {+ m_entries.reserve(ops.size());+ for (const auto& op : ops) {+ if (auto constant = ov::as_type_ptr<ov::op::v0::Constant>(op);+ constant && m_indices.emplace(constant.get(), m_entries.size()).second) {+ m_entries.push_back({constant, constant->get_byte_size()});+ }+ }+ prefetch_ahead();+}++std::optional<size_t> OrderedPrefetchScheduler::index_of(const ov::Node& node) const noexcept {+ // The lock check guards against a dead constant whose address was reused by another node.+ if (const auto found = m_indices.find(&node);+ found != m_indices.end() && m_entries[found->second].constant.lock().get() == &node) {+ return found->second;+ }+ return std::nullopt;+}++void OrderedPrefetchScheduler::prefetch(Entry& entry, const ov::op::v0::Constant& constant) noexcept {+ entry.future = ov::weight_sharing::Extension::hint_prefetch(constant);+ if (entry.future.valid()) {+ entry.state = State::prefetch_requested;+ ++m_in_flight;+ m_in_flight_bytes += entry.size;+ }+}++void OrderedPrefetchScheduler::acquire(const ov::Node& node) noexcept {+ if (const auto index = index_of(node); index && m_entries[*index].state == State::pending) {+ // Consumed ahead of the planned order: still load it in the background, on several threads.+ prefetch(m_entries[*index], static_cast<const ov::op::v0::Constant&>(node));+ }+}++void OrderedPrefetchScheduler::release(const ov::Node& node) noexcept {+ if (const auto index = index_of(node)) {+ auto& entry = m_entries[*index];+ if (entry.state == State::prefetch_requested) {+ entry.future.wait();+ --m_in_flight;+ m_in_flight_bytes -= entry.size;+ }+ entry.state = State::released;+ entry.future = {};+ // Alive: the caller holds node and index_of() verified it.+ ov::weight_sharing::Extension::hint_evict(*entry.constant.lock());+ prefetch_ahead();+ }+}++void OrderedPrefetchScheduler::prefetch_ahead() noexcept {+ for (; (m_in_flight < m_lookahead || m_in_flight_bytes < m_min_bytes) && m_next < m_entries.size(); ++m_next) {+ if (auto& entry = m_entries[m_next]; entry.state == State::pending) {+ if (const auto constant = entry.constant.lock()) {+ prefetch(entry, *constant);+ } else {+ entry.state = State::released;+ }+ }+ }+}++} // namespace ov::utildiff --git a/src/core/tests/mmap_object.cpp b/src/core/tests/mmap_object.cppindex a8a191bc0e4..fa90389f96e 100644--- a/src/core/tests/mmap_object.cpp+++ b/src/core/tests/mmap_object.cpp@@ -20,6 +20,7 @@#include "common_test_utils/common_utils.hpp"#include "common_test_utils/file_utils.hpp"#include "openvino/util/file_util.hpp"+#include "openvino/util/math_util.hpp"namespace ov::test {diff --git a/src/core/tests/ov_tensor_test.cpp b/src/core/tests/ov_tensor_test.cppindex 40671059c0f..6ac07c1954c 100644--- a/src/core/tests/ov_tensor_test.cpp+++ b/src/core/tests/ov_tensor_test.cpp@@ -1367,7 +1367,7 @@ public:MOCK_METHOD(void, hint_evict, (size_t offset, size_t size), (noexcept, override));MOCK_METHOD(void, hint_prefetch, (size_t offset, size_t size), (noexcept, override));- MOCK_METHOD(void, hint_prefetch_async, (size_t offset, size_t size), (override));+ MOCK_METHOD(ov::util::PrefetchToken, hint_prefetch_async, (size_t offset, size_t size), (noexcept, override));private:std::vector<std::byte> m_data;diff --git a/src/core/tests/shared_buffer.cpp b/src/core/tests/shared_buffer.cppindex 0a760f53a84..201946323e2 100644--- a/src/core/tests/shared_buffer.cpp+++ b/src/core/tests/shared_buffer.cpp@@ -8,11 +8,13 @@#include <filesystem>#include <fstream>+#include <future>#include <optional>#include <sstream>#include <vector>#include "common_test_utils/common_utils.hpp"+#include "openvino/core/weights_prefetch.hpp"#include "openvino/op/constant.hpp"#include "openvino/util/mmap_object.hpp"@@ -545,7 +547,7 @@ public:MOCK_METHOD(void, hint_prefetch, (size_t offset, size_t size), (noexcept, override));- MOCK_METHOD(void, hint_prefetch_async, (size_t offset, size_t size), (override));+ MOCK_METHOD(ov::util::PrefetchToken, hint_prefetch_async, (size_t offset, size_t size), (noexcept, override));private:std::vector<char> m_data;@@ -608,4 +610,117 @@ TEST_F(SharedBufferTest, no_call_when_mmap_object_is_null) {std::shared_ptr<ov::MappedMemory>{} /*null*/);EXPECT_NO_THROW(buffer->hint_evict());}++TEST_F(SharedBufferTest, aligned_shared_buffer_propagates_prefetch_async_to_mmap) {+ constexpr size_t mmap_size = 2048;+ constexpr size_t parent_offset = 64;+ constexpr size_t child_offset = 32;+ constexpr size_t child_size = 128;++ auto mock = std::make_shared<MockMappedMemory>(mmap_size);+ auto parent = std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::MappedMemory>>>(mock->data() + parent_offset,+ mmap_size - parent_offset,+ mock);+ auto child = std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>(+ parent->get_ptr<char>() + child_offset,+ child_size,+ std::static_pointer_cast<ov::AlignedBuffer>(parent));++ EXPECT_CALL(*mock, hint_prefetch_async(parent_offset + child_offset, child_size)).Times(1);+ child->hint_prefetch_async();+}++static std::vector<std::shared_ptr<ov::Node>> make_mapped_constants(const std::shared_ptr<MockMappedMemory>& mock,+ size_t count,+ size_t size) {+ // hint_prefetch_async must return a handle PrefetchScheduler::acquire() can wait on without blocking.+ ON_CALL(*mock, hint_prefetch_async(::testing::_, ::testing::_)).WillByDefault(::testing::Invoke([](auto, auto) {+ std::promise<void> ready;+ ready.set_value();+ return ready.get_future().share();+ }));+ auto mapped =+ std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::MappedMemory>>>(mock->data(), count * size, mock);+ std::vector<std::shared_ptr<ov::Node>> ops;+ for (size_t i = 0; i < count; ++i) {+ auto buffer = std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>(+ mapped->get_ptr<char>() + i * size,+ size,+ std::static_pointer_cast<ov::AlignedBuffer>(mapped));+ ops.push_back(std::make_shared<ov::op::v0::Constant>(ov::element::u8, ov::Shape{size}, buffer));+ }+ return ops;+}++TEST_F(SharedBufferTest, prefetch_scheduler_keeps_lookahead_window) {+ constexpr size_t count = 4;+ constexpr size_t size = 256;++ auto mock = std::make_shared<MockMappedMemory>(count * size);+ const auto ops = make_mapped_constants(mock, count, size);++ {+ // lookahead = 2: prefetch A, B; consume A, evict A, prefetch C; consume B, evict B, prefetch D; ...+ ::testing::InSequence in_sequence;+ EXPECT_CALL(*mock, hint_prefetch_async(0 * size, size));+ EXPECT_CALL(*mock, hint_prefetch_async(1 * size, size));+ EXPECT_CALL(*mock, hint_evict_mock(0 * size, size));+ EXPECT_CALL(*mock, hint_prefetch_async(2 * size, size));+ EXPECT_CALL(*mock, hint_evict_mock(1 * size, size));+ EXPECT_CALL(*mock, hint_prefetch_async(3 * size, size));+ EXPECT_CALL(*mock, hint_evict_mock(2 * size, size));+ EXPECT_CALL(*mock, hint_evict_mock(3 * size, size));+ }++ ov::util::OrderedPrefetchScheduler scheduler(ops, 2, 0);+ for (const auto& op : ops) {+ scheduler.acquire(*op);+ scheduler.release(*op);+ }+}++TEST_F(SharedBufferTest, prefetch_scheduler_extends_lookahead_below_min_bytes) {+ constexpr size_t count = 4;+ constexpr size_t size = 256;++ auto mock = std::make_shared<MockMappedMemory>(count * size);+ const auto ops = make_mapped_constants(mock, count, size);++ {+ // lookahead = 2, min_bytes = 600: prefetch A, B, C (768 bytes); consume A, evict A, prefetch D; ...+ ::testing::InSequence in_sequence;+ EXPECT_CALL(*mock, hint_prefetch_async(0 * size, size));+ EXPECT_CALL(*mock, hint_prefetch_async(1 * size, size));+ EXPECT_CALL(*mock, hint_prefetch_async(2 * size, size));+ EXPECT_CALL(*mock, hint_evict_mock(0 * size, size));+ EXPECT_CALL(*mock, hint_prefetch_async(3 * size, size));+ EXPECT_CALL(*mock, hint_evict_mock(1 * size, size));+ EXPECT_CALL(*mock, hint_evict_mock(2 * size, size));+ EXPECT_CALL(*mock, hint_evict_mock(3 * size, size));+ }++ ov::util::OrderedPrefetchScheduler scheduler(ops, 2, 600);+ for (const auto& op : ops) {+ scheduler.acquire(*op);+ scheduler.release(*op);+ }+}++TEST_F(SharedBufferTest, prefetch_scheduler_ignores_non_file_backed_constants_in_window) {+ constexpr size_t count = 2;+ constexpr size_t size = 256;++ auto mock = std::make_shared<MockMappedMemory>(count * size);+ const auto mapped_ops = make_mapped_constants(mock, count, size);+ std::vector<std::shared_ptr<ov::Node>> ops{+ std::make_shared<ov::op::v0::Constant>(ov::element::u8, ov::Shape{size}, std::vector<uint8_t>(size)),+ std::make_shared<ov::op::v0::Constant>(ov::element::u8, ov::Shape{size}, std::vector<uint8_t>(size))};+ ops.insert(ops.end(), mapped_ops.begin(), mapped_ops.end());++ EXPECT_CALL(*mock, hint_prefetch_async(0 * size, size)).Times(1);+ EXPECT_CALL(*mock, hint_prefetch_async(1 * size, size)).Times(1);++ ov::util::OrderedPrefetchScheduler scheduler(ops, 2, 0);+ ::testing::Mock::VerifyAndClearExpectations(mock.get());+}} // namespace ov::testdiff --git a/src/plugins/intel_gpu/src/plugin/program_builder.cpp b/src/plugins/intel_gpu/src/plugin/program_builder.cppindex b6e57b64f10..812148f1f07 100644--- a/src/plugins/intel_gpu/src/plugin/program_builder.cpp+++ b/src/plugins/intel_gpu/src/plugin/program_builder.cpp@@ -4,6 +4,7 @@#include "intel_gpu/runtime/internal_properties.hpp"#include "openvino/core/rt_info/weightless_caching_attributes.hpp"+#include "openvino/core/weights_prefetch.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/split.hpp"#include "openvino/op/variadic_split.hpp"@@ -162,8 +163,18 @@ std::shared_ptr<cldnn::program> ProgramBuilder::build(const std::vector<std::shaprepare_build();{GPU_DEBUG_DEFINE_MEM_LOGGER("CreateSingleLayerPrimitives");+ const std::vector<std::shared_ptr<ov::Node>> no_ops;+#ifdef _WIN32+ // TODO: CVS-198510 enable on Windows once prefetch shows a compile-time gain there.+ const bool use_prefetch = false;+#else+ const bool use_prefetch = m_config.get_offload_ratio() == 0;+#endif+ ov::util::OrderedPrefetchScheduler weights_prefetch(use_prefetch ? ops : no_ops);for (const auto& op : ops) {+ weights_prefetch.acquire(*op);CreateSingleLayerPrimitive(op);+ weights_prefetch.release(*op);}}