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
[GPU] prefetch the cache stream around the small-read bursts in program::load() (#35508)
Sungeun Kimb083a05f64a6
diff --git a/src/common/util/include/openvino/util/parallel_io.hpp b/src/common/util/include/openvino/util/parallel_io.hppindex 234a23af23c..8c6cd6fcc22 100644--- a/src/common/util/include/openvino/util/parallel_io.hpp+++ b/src/common/util/include/openvino/util/parallel_io.hpp@@ -22,6 +22,11 @@ inline constexpr FileHandle INVALID_HANDLE_VALUE = -1;inline constexpr size_t default_parallel_io_threshold = 4UL * 1024 * 1024; ///< 4 MB default threshold for parallel I/Oinline constexpr size_t default_parallel_io_min_chunk = 2UL * 1024 * 1024; ///< 2 MB minimum chunk size per thread+/** @brief Default upper bound for ParallelReadStreamBuf::prefetch() requests.+ * Sized to cover a typical large-model deserialization burst in a single window while keeping+ * prefetch allocation and dispatch cost bounded. Reads outside the window fall back to file I/O.+ */+inline constexpr size_t default_parallel_io_prefetch_cap = 32UL * 1024 * 1024;/*** @brief Open a file for reading and retrieve its size.diff --git a/src/common/util/include/openvino/util/parallel_read_streambuf.hpp b/src/common/util/include/openvino/util/parallel_read_streambuf.hppindex 2d3c94e8218..2661e3b9ad7 100644--- a/src/common/util/include/openvino/util/parallel_read_streambuf.hpp+++ b/src/common/util/include/openvino/util/parallel_read_streambuf.hpp@@ -50,6 +50,27 @@ public:ParallelReadStreamBuf(const ParallelReadStreamBuf&) = delete;ParallelReadStreamBuf& operator=(const ParallelReadStreamBuf&) = delete;+ /**+ * @brief Preload @p size bytes starting at the current logical position into+ * an internal buffer using one parallel positional read.+ *+ * After a successful prefetch, subsequent xsgetn()/underflow() calls that+ * fall inside [current_pos, current_pos + size) are served from memory via+ * memcpy instead of issuing per-call pread(). Reads that fall outside the+ * prefetched window transparently fall back to the normal file-IO path and+ * invalidate the prefetched window.+ *+ * Intended call site: the producer of a long serialized region (e.g.+ * program::weights_load in the GPU plugin) calls prefetch() once at the+ * start of the region to collapse thousands of small ib >> ... small-reads+ * into a single bulk parallel pread.+ *+ * @param size Number of bytes to preload. Clamped to remaining file size.+ * @return true if the prefetch read succeeded (buffer is now valid), false+ * otherwise (buffer is left empty; reads fall back to file I/O).+ */+ bool prefetch(std::streamsize size);+protected:std::streamsize xsgetn(char_type* dst, std::streamsize n) override;int_type underflow() override;@@ -71,6 +92,14 @@ private:std::streamoff m_file_size = 0;size_t m_threshold = default_parallel_io_threshold;std::unique_ptr<char_type[]> m_underflow_buf; ///< lazily allocated buffer for underflow()++ std::unique_ptr<char_type[]> m_prefetch_buf; ///< host-side prefetch buffer; null when capacity is zero+ std::streamoff m_prefetch_begin = 0; ///< absolute file offset of m_prefetch_buf[0]+ size_t m_prefetch_size = 0; ///< valid bytes in m_prefetch_buf (0 = window invalid)+ size_t m_prefetch_capacity = 0; ///< allocated capacity of m_prefetch_buf in bytes++ bool serve_from_prefetch(char* dst, size_t size, std::streamoff abs_offset);+ void invalidate_prefetch();};} // namespace ov::util\ No newline at end of filediff --git a/src/common/util/src/parallel_read_streambuf.cpp b/src/common/util/src/parallel_read_streambuf.cppindex 0ab43588763..3d3bfbafdad 100644--- a/src/common/util/src/parallel_read_streambuf.cpp+++ b/src/common/util/src/parallel_read_streambuf.cpp@@ -69,6 +69,14 @@ std::streamsize ParallelReadStreamBuf::xsgetn(char_type* dst, std::streamsize n)const size_t bytes = static_cast<size_t>(to_read);const size_t offset = static_cast<size_t>(m_file_offset);+ // Prefetch fast path: if the whole request sits inside the prefetched window,+ // serve it from memory with one memcpy instead of issuing a pread.+ if (serve_from_prefetch(dst, bytes, m_file_offset)) {+ m_file_offset += to_read;+ total += to_read;+ return total;+ }+bool ok = (bytes >= m_threshold) ? parallel_read(dst, bytes, offset) : single_read(dst, bytes, offset);if (ok) {@@ -91,8 +99,13 @@ ParallelReadStreamBuf::int_type ParallelReadStreamBuf::underflow() {// consumers (std::getline, operator>>) don't issue one pread per char.const size_t to_read =static_cast<size_t>((std::min)(static_cast<std::streamoff>(UNDERFLOW_BUF), m_file_size - m_file_offset));- if (!single_read(m_underflow_buf.get(), to_read, static_cast<size_t>(m_file_offset))) {- return traits_type::eof();+ // Prefetch fast path: fill the underflow buffer from the prefetched window+ // if possible, avoiding a pread per 8 KiB chunk of character-by-character+ // consumption (operator>>, std::getline).+ if (!serve_from_prefetch(m_underflow_buf.get(), to_read, m_file_offset)) {+ if (!single_read(m_underflow_buf.get(), to_read, static_cast<size_t>(m_file_offset))) {+ return traits_type::eof();+ }}// Advance m_file_offset past the bytes we just read into the get area.// m_file_offset now points to the byte after egptr(), consistent with@@ -135,6 +148,14 @@ ParallelReadStreamBuf::pos_type ParallelReadStreamBuf::seekoff(off_type off,}setg(nullptr, nullptr, nullptr); // invalidate get-area+ // If the new absolute position is outside the prefetched window, drop the+ // prefetch buffer so we don't serve stale or partial data from it.+ if (m_prefetch_size > 0) {+ const std::streamoff end = m_prefetch_begin + static_cast<std::streamoff>(m_prefetch_size);+ if (new_pos < m_prefetch_begin || new_pos >= end) {+ invalidate_prefetch();+ }+ }m_file_offset = new_pos;// Return the logical position (0 == start of exposed stream).return pos_type(m_file_offset - m_header_offset);@@ -165,6 +186,80 @@ std::streamsize ParallelReadStreamBuf::showmanyc() {return total > 0 ? total : static_cast<std::streamsize>(-1);}+// Prefetch a region of @p size bytes starting at the current logical position+// into an internal buffer. Returns true if the prefetch succeeded and the+// buffer is now ready to serve subsequent small reads.+bool ParallelReadStreamBuf::prefetch(std::streamsize size) {+ if (size <= 0) {+ return false;+ }++ // Account for bytes still sitting in the underflow get-area. The logical+ // cursor that the caller cares about is the position of the next byte the+ // caller will consume, which is m_file_offset - (egptr - gptr).+ const std::streamoff ahead = (gptr() != nullptr) ? static_cast<std::streamoff>(egptr() - gptr()) : 0;+ const std::streamoff abs_begin = m_file_offset - ahead;++ if (abs_begin < 0 || abs_begin >= m_file_size) {+ return false;+ }++ const std::streamoff remaining = m_file_size - abs_begin;+ const size_t to_load = static_cast<size_t>((std::min)(static_cast<std::streamoff>(size), remaining));+ if (to_load == 0) {+ return false;+ }++ // Drop any pre-existing prefetch window; we fill a fresh one below.+ invalidate_prefetch();++ // Reuse an existing allocation when possible to avoid repeated malloc/free+ // across consecutive prefetch() calls in the same stream lifetime.+ if (!m_prefetch_buf || m_prefetch_capacity < to_load) {+ m_prefetch_buf = std::make_unique<char_type[]>(to_load);+ m_prefetch_capacity = to_load;+ }+ const size_t abs_begin_sz = static_cast<size_t>(abs_begin);++ // Use the same parallel_read path as the normal large-read code so that+ // hw_threads, chunking, and per-thread fds all match the tuned behavior.+ const bool ok = (to_load >= m_threshold) ? parallel_read(m_prefetch_buf.get(), to_load, abs_begin_sz)+ : single_read(m_prefetch_buf.get(), to_load, abs_begin_sz);+ if (!ok) {+ return false;+ }++ m_prefetch_begin = abs_begin;+ m_prefetch_size = to_load;+ return true;+}++// Serve a request from the prefetch buffer if the full range is covered.+// Returns true when the buffer was used; on false the caller must fall back to+// the regular file-IO path (which will also invalidate the stale window via+// seekoff semantics when a subsequent xsgetn crosses the boundary).+bool ParallelReadStreamBuf::serve_from_prefetch(char* dst, size_t size, std::streamoff abs_offset) {+ if (m_prefetch_size == 0 || !m_prefetch_buf) {+ return false;+ }+ const std::streamoff begin = m_prefetch_begin;+ const std::streamoff end = begin + static_cast<std::streamoff>(m_prefetch_size);+ if (abs_offset < begin || static_cast<std::streamoff>(abs_offset + static_cast<std::streamoff>(size)) > end) {+ // Partial overlap falls through to file I/O; serving a partial slice here+ // would force xsgetn to issue a second pread for the tail, negating the+ // amortization benefit we are chasing.+ return false;+ }+ const size_t local = static_cast<size_t>(abs_offset - begin);+ std::memcpy(dst, m_prefetch_buf.get() + local, size);+ return true;+}++void ParallelReadStreamBuf::invalidate_prefetch() {+ m_prefetch_begin = 0;+ m_prefetch_size = 0;+}+// Single-threaded positional readbool ParallelReadStreamBuf::single_read(char* dst, size_t size, size_t file_offset) {return positional_read(m_handle, dst, size, file_offset);diff --git a/src/inference/tests/unit/parallel_read_streambuf_test.cpp b/src/inference/tests/unit/parallel_read_streambuf_test.cppindex 40c21e801ae..9483e5a287a 100644--- a/src/inference/tests/unit/parallel_read_streambuf_test.cpp+++ b/src/inference/tests/unit/parallel_read_streambuf_test.cpp@@ -522,4 +522,97 @@ TEST_F(ParallelReadStreamBufTest, BackwardSeekFromCurrent) {EXPECT_EQ(got, slice);}+// Prefetch: after prefetch(size) the next xsgetn must return the same bytes as+// the underlying file, served from the internal prefetch buffer (no pread per+// call). The observable contract is just "same data"; we cannot directly count+// syscalls, so this test guards correctness rather than performance.+TEST_F(ParallelReadStreamBufTest, PrefetchThenReadReturnsCorrectData) {+ constexpr size_t k_size = 64 * 1024;+ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ util::ParallelReadStreamBuf buf(m_tmp_path, /*header_offset=*/0, /*threshold=*/1);+ std::istream stream(&buf);++ ASSERT_TRUE(buf.prefetch(static_cast<std::streamsize>(k_size)));++ std::vector<char> got(k_size);+ ASSERT_TRUE(stream.read(got.data(), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(got, expected);+ EXPECT_EQ(stream.tellg(), std::streampos(k_size));+}++// Prefetch clamps to remaining file size when the requested size exceeds EOF.+// Reading past the prefetch boundary must still work via the regular file-IO+// path without corruption.+TEST_F(ParallelReadStreamBufTest, PrefetchClampsToFileSizeAndFallsThrough) {+ constexpr size_t k_size = 8 * 1024; // 8 KB file+ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ util::ParallelReadStreamBuf buf(m_tmp_path, /*header_offset=*/0, /*threshold=*/1);+ std::istream stream(&buf);++ // Request far more than the file holds; prefetch clamps internally.+ ASSERT_TRUE(buf.prefetch(static_cast<std::streamsize>(64 * 1024 * 1024)));++ std::vector<char> got(k_size);+ ASSERT_TRUE(stream.read(got.data(), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(got, expected);++ // A further read must return EOF without corrupting state.+ char tail = 0;+ stream.read(&tail, 1);+ EXPECT_TRUE(stream.eof() || !stream.good());+}++// Seeking outside the prefetched window must transparently invalidate the+// buffer; the subsequent read fetches from the file and still matches.+TEST_F(ParallelReadStreamBufTest, PrefetchInvalidatedOnSeekOutsideWindow) {+ constexpr size_t k_size = 16 * 1024;+ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ util::ParallelReadStreamBuf buf(m_tmp_path, /*header_offset=*/0, /*threshold=*/1);+ std::istream stream(&buf);++ // Prefetch the first 4 KiB only.+ constexpr size_t k_prefetch = 4 * 1024;+ ASSERT_TRUE(buf.prefetch(static_cast<std::streamsize>(k_prefetch)));++ // Seek past the prefetched window – this must drop the buffer.+ constexpr std::streamoff k_seek_to = 10 * 1024;+ stream.seekg(k_seek_to, std::ios::beg);+ ASSERT_TRUE(stream.good());++ // Read 512 bytes from the new position; the data must still match expected.+ constexpr size_t k_read = 512;+ std::vector<char> got(k_read);+ ASSERT_TRUE(stream.read(got.data(), static_cast<std::streamsize>(k_read)));+ std::vector<char> slice(expected.begin() + k_seek_to, expected.begin() + k_seek_to + k_read);+ EXPECT_EQ(got, slice);+}++// Prefetch at EOF or with zero size returns false without changing state.+TEST_F(ParallelReadStreamBufTest, PrefetchEdgeCases) {+ constexpr size_t k_size = 1024;+ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ util::ParallelReadStreamBuf buf(m_tmp_path, /*header_offset=*/0, /*threshold=*/1);+ std::istream stream(&buf);++ // Zero-size prefetch is a no-op.+ EXPECT_FALSE(buf.prefetch(0));++ // Drain the whole file first, then prefetch past EOF must return false.+ std::vector<char> got(k_size);+ ASSERT_TRUE(stream.read(got.data(), static_cast<std::streamsize>(k_size)));+ EXPECT_FALSE(buf.prefetch(static_cast<std::streamsize>(k_size)));+}+} // namespace ov::testdiff --git a/src/plugins/intel_gpu/include/intel_gpu/graph/serialization/binary_buffer.hpp b/src/plugins/intel_gpu/include/intel_gpu/graph/serialization/binary_buffer.hppindex 9b374a6d227..5d8513fe3d3 100644--- a/src/plugins/intel_gpu/include/intel_gpu/graph/serialization/binary_buffer.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/graph/serialization/binary_buffer.hpp@@ -55,6 +55,14 @@ public:"[GPU] Failed to read " + std::to_string(size) + " bytes from stream! Read " + std::to_string(read_size));}+ /// Access the underlying streambuf. Callers that know their backing buffer+ /// implements an optimization hook (e.g. ov::util::ParallelReadStreamBuf's+ /// prefetch()) can dynamic_cast the result to trigger it without changing+ /// this generic reader API. Safe to call at any point during deserialize.+ std::streambuf* get_streambuf() const {+ return _stream.rdbuf();+ }+void setKernelImplParams(void* impl_params) { _impl_params = impl_params; }void* getKernelImplParams() const { return _impl_params; }diff --git a/src/plugins/intel_gpu/src/graph/common_utils/parallel_mem_streambuf.hpp b/src/plugins/intel_gpu/src/graph/common_utils/parallel_mem_streambuf.hppindex 4fcec9d34ed..70768287ace 100644--- a/src/plugins/intel_gpu/src/graph/common_utils/parallel_mem_streambuf.hpp+++ b/src/plugins/intel_gpu/src/graph/common_utils/parallel_mem_streambuf.hpp@@ -28,6 +28,13 @@ public:ParallelMemStreamBuf(const ParallelMemStreamBuf&) = delete;ParallelMemStreamBuf& operator=(const ParallelMemStreamBuf&) = delete;+ /// Forward prefetch to the delegated ParallelReadStreamBuf if this instance+ /// wraps a file-backed mmap. Returns false for the in-memory memcpy path,+ /// where the data is already resident and no preloading is meaningful.+ bool prefetch(std::streamsize size) {+ return m_file_buf ? m_file_buf->prefetch(size) : false;+ }+protected:std::streamsize xsgetn(char_type* dst, std::streamsize n) override;int_type underflow() override;diff --git a/src/plugins/intel_gpu/src/graph/program.cpp b/src/plugins/intel_gpu/src/graph/program.cppindex f49b5dba800..5bbfc48c1ff 100644--- a/src/plugins/intel_gpu/src/graph/program.cpp+++ b/src/plugins/intel_gpu/src/graph/program.cpp@@ -9,6 +9,8 @@#include "openvino/runtime/system_conf.hpp"#include "openvino/runtime/threading/cpu_streams_info.hpp"#include "openvino/util/file_util.hpp"+#include "openvino/util/parallel_read_streambuf.hpp"+#include "common_utils/parallel_mem_streambuf.hpp"#include "intel_gpu/runtime/memory.hpp"#include "intel_gpu/runtime/engine.hpp"@@ -1978,6 +1980,22 @@ void program::load(cldnn::BinaryInputBuffer& ib,size_t num_nodes;ib >> num_nodes;bool is_valid_data_node;++ // Prefetch hook: if the backing streambuf is ParallelReadStreamBuf (or+ // ParallelMemStreamBuf wrapping one for a file-backed mmap), ask it to+ // collapse the upcoming thousands of small ib >> ... reads for data+ // primitives into one bulk parallel pread. The cap keeps the up-front+ // dispatch/allocation cost bounded; reads that fall outside the prefetched+ // window transparently fall back to file I/O.+ {+ auto* rdbuf = ib.get_streambuf();+ if (auto* prs = dynamic_cast<ov::util::ParallelReadStreamBuf*>(rdbuf)) {+ prs->prefetch(ov::util::default_parallel_io_prefetch_cap);+ } else if (auto* pms = dynamic_cast<ov::intel_gpu::ParallelMemStreamBuf*>(rdbuf)) {+ pms->prefetch(ov::util::default_parallel_io_prefetch_cap);+ }+ }+for (size_t i = 0; i < num_nodes; ++i) {ib >> is_valid_data_node;if (!is_valid_data_node)@@ -2005,6 +2023,18 @@ void program::load(cldnn::BinaryInputBuffer& ib,md_node2.replace_memory(md_node2.typed_desc()->mem);}+ // Same prefetch hook for the post-load loop: node_post_load is dominated by+ // ~15 small ib >> ... calls per node across thousands of nodes, which maps+ // to thousands of single_read dispatches if left unbatched.+ {+ auto* rdbuf = ib.get_streambuf();+ if (auto* prs = dynamic_cast<ov::util::ParallelReadStreamBuf*>(rdbuf)) {+ prs->prefetch(ov::util::default_parallel_io_prefetch_cap);+ } else if (auto* pms = dynamic_cast<ov::intel_gpu::ParallelMemStreamBuf*>(rdbuf)) {+ pms->prefetch(ov::util::default_parallel_io_prefetch_cap);+ }+ }+for (size_t i = 0; i < num_nodes; ++i) {primitive_id prim_id;ib >> prim_id;