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] Create lazy loading buffer (#35512)
Tomasz Jankowskibd98149602b9
diff --git a/src/common/util/include/openvino/util/memory.hpp b/src/common/util/include/openvino/util/memory.hppindex f1a6c8bd818..f192d5c4f7f 100644--- a/src/common/util/include/openvino/util/memory.hpp+++ b/src/common/util/include/openvino/util/memory.hpp@@ -6,6 +6,7 @@#include <cstddef>#include <cstdlib>+#include <string>namespace ov::util {@@ -39,4 +40,41 @@ void* aligned_alloc(size_t size, size_t alignment) noexcept;*/void aligned_free(void* ptr) noexcept;+/**+ * @brief Reserves a block of memory of the specified size without actually allocating physical memory.+ * The reserved memory block is not accessible until acquire_buffer() is called on it. The reserved memory block should+ * be released with release_buffer() when it is no longer needed.+ * @param size [in] Size of the memory block to reserve in bytes. Must be greater than 0.+ * @param error [out] Optional Error message in case of failure, empty otherwise.+ * @return Pointer to the reserved memory block, or nullptr if the reservation fail.+ */+void* reserve_buffer(size_t size, std::string* error = nullptr) noexcept;++/**+ * @brief Acquires the reserved memory block, making it accessible for read/write operations.+ * @param reserved_buffer [in] Pointer to the reserved memory block to acquire.+ * @param size [in] Size of the memory block to acquire in bytes. Must be greater than 0.+ * @param error [out] Optional Error message in case of failure, empty otherwise.+ * @note The reserved memory block should be successfully acquired before it can be used.+ */+void acquire_buffer(void* reserved_buffer, size_t size, std::string* error = nullptr) noexcept;++/**+ * @brief Evicts the acquired memory block, making it inaccessible and allowing the system to free physical memory.+ * @param reserved_buffer [in] Pointer to the reserved memory block to evict.+ * @param size [in] Size of the memory block to evict in bytes. Must be greater than 0.+ * @param error [out] Optional Error message in case of failure, empty otherwise.+ * @note After eviction, the reserved memory block can be acquired again with acquire_buffer().+ */+void evict_buffer(void* reserved_buffer, size_t size, std::string* error = nullptr) noexcept;++/**+ * @brief Releases the reserved memory block, freeing any associated resources. After this call, the reserved memory+ * block is no longer valid and should not be used.+ * @param reserved_buffer [in] Pointer to the reserved memory block to release.+ * @param size [in] Size of the memory block to release in bytes. Must be greater than 0.+ * @param error [out] Optional Error message in case of failure, empty otherwise.+ */+void release_buffer(void* reserved_buffer, size_t size, std::string* error = nullptr) noexcept;+} // namespace ov::utildiff --git a/src/common/util/src/os/lin/lin_memory.cpp b/src/common/util/src/os/lin/lin_memory.cppindex feec8bc1003..468494211a9 100644--- a/src/common/util/src/os/lin/lin_memory.cpp+++ b/src/common/util/src/os/lin/lin_memory.cpp@@ -2,8 +2,12 @@// SPDX-License-Identifier: Apache-2.0//+#include <sys/mman.h>++#include <cerrno>#include <cstddef>#include <cstdlib>+#include <cstring>#include "openvino/util/memory.hpp"@@ -20,4 +24,39 @@ void aligned_free(void* ptr) noexcept {std::free(ptr);}+void* reserve_buffer(size_t size, std::string* error) noexcept {+ const auto p = mmap(nullptr, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);+ if (p == MAP_FAILED) {+ if (error) {+ *error = std::string{"mmap failed, err: "} + std::strerror(errno);+ }+ return nullptr;+ }+ return p;+}++void acquire_buffer(void* reserved_buffer, size_t size, std::string* error) noexcept {+ if (mprotect(reserved_buffer, size, PROT_READ | PROT_WRITE) == -1) {+ if (error) {+ *error = std::string{"mprotect failed, err: "} + std::strerror(errno);+ }+ }+}++void evict_buffer(void* reserved_buffer, size_t size, std::string* error) noexcept {+ if (mmap(reserved_buffer, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) == MAP_FAILED) {+ if (error) {+ *error = std::string{"mprotect failed, err: "} + std::strerror(errno);+ }+ }+}++void release_buffer(void* reserved_buffer, size_t byte_size, std::string* error) noexcept {+ if (munmap(reserved_buffer, byte_size) == -1) {+ if (error) {+ *error = std::string{"munmap failed, err: "} + std::strerror(errno);+ }+ }+}+} // namespace ov::utildiff --git a/src/common/util/src/os/win/win_memory.cpp b/src/common/util/src/os/win/win_memory.cppindex 5fe38d3d343..31ebf86e97a 100644--- a/src/common/util/src/os/win/win_memory.cpp+++ b/src/common/util/src/os/win/win_memory.cpp@@ -2,8 +2,15 @@// SPDX-License-Identifier: Apache-2.0//-#include <cstddef>+#ifndef NOMINMAX+# define NOMINMAX+#endif+#include <malloc.h>+#include <windows.h>++#include <cstddef>+#include <cstring>#include "openvino/util/memory.hpp"@@ -20,4 +27,39 @@ void aligned_free(void* ptr) noexcept {_aligned_free(ptr);}+void* reserve_buffer(size_t size, std::string* error) noexcept {+ const auto p = VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_NOACCESS);+ if (p == NULL) {+ if (error) {+ *error = std::string{"VirtualAlloc reserve failed, err: "} + std::to_string(GetLastError());+ }+ return nullptr;+ }+ return p;+}++void acquire_buffer(void* reserved_buffer, size_t size, std::string* error) noexcept {+ if (VirtualAlloc(reserved_buffer, size, MEM_COMMIT, PAGE_READWRITE) == NULL) {+ if (error) {+ *error = std::string{"VirtualAlloc commit failed, err: "} + std::to_string(GetLastError());+ }+ }+}++void evict_buffer(void* reserved_buffer, size_t size, std::string* error) noexcept {+ if (VirtualFree(reserved_buffer, size, MEM_DECOMMIT) == 0) {+ if (error) {+ *error = std::string{"VirtualFree decommit failed, err: "} + std::to_string(GetLastError());+ }+ }+}++void release_buffer(void* reserved_buffer, size_t /* byte_size */, std::string* error) noexcept {+ if (VirtualFree(reserved_buffer, 0, MEM_RELEASE) == 0) {+ if (error) {+ *error = std::string{"VirtualFree release failed, err: "} + std::to_string(GetLastError());+ }+ }+}+} // namespace ov::utildiff --git a/src/core/dev_api/openvino/runtime/aligned_buffer.hpp b/src/core/dev_api/openvino/runtime/aligned_buffer.hppindex d43b37799ca..fe45f9dd3b8 100644--- a/src/core/dev_api/openvino/runtime/aligned_buffer.hpp+++ b/src/core/dev_api/openvino/runtime/aligned_buffer.hpp@@ -40,20 +40,25 @@ public:return m_byte_size;}void* get_ptr(size_t offset) const {+ hint_prefetch();return m_aligned_buffer + offset;}void* get_ptr() {+ hint_prefetch();return m_aligned_buffer;}const void* get_ptr() const {+ hint_prefetch();return m_aligned_buffer;}template <typename T>T* get_ptr() {+ hint_prefetch();return reinterpret_cast<T*>(m_aligned_buffer);}template <typename T>const T* get_ptr() const {+ hint_prefetch();return reinterpret_cast<const T*>(m_aligned_buffer);}@@ -69,10 +74,16 @@ public:virtual void hint_evict() noexcept;+ /// \brief Ensures the buffer is available and populated with actual data.+ virtual void hint_prefetch() const;+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);++ char* m_allocated_buffer;char* m_aligned_buffer;size_t m_byte_size;};diff --git a/src/core/dev_api/openvino/runtime/lazy_buffer.hpp b/src/core/dev_api/openvino/runtime/lazy_buffer.hppnew file mode 100644index 00000000000..12e0b233998--- /dev/null+++ b/src/core/dev_api/openvino/runtime/lazy_buffer.hpp@@ -0,0 +1,67 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <atomic>+#include <filesystem>+#include <memory>+#include <mutex>++#include "openvino/runtime/aligned_buffer.hpp"++namespace ov {++/** \brief LazyBuffer is lazy loaded AlignedBuffer which provides a view on a file w/o memory mapping. */+class OPENVINO_API LazyBuffer : public AlignedBuffer {+public:+ /**+ * @brief Constructs a LazyBuffer which provides a view on a file. The file content is loaded to memory when+ * get_ptr() is called for the first time after object creation or after hint_evict() is called. The file content is+ * loaded at aligned addresses, so the actual allocated memory may be larger than the requested byte size.+ * @param file_path Path to the file to load+ * @param offset Offset in the file to start the view+ * @param byte_size Size of the view in bytes+ * @throws AssertFailure if the file does not exist or the file size is smaller than the requested view.+ */+ LazyBuffer(std::filesystem::path file_path, size_t offset, size_t byte_size);++ LazyBuffer(LazyBuffer&&) noexcept;+ LazyBuffer& operator=(LazyBuffer&&) noexcept;+ ~LazyBuffer() override;++ LazyBuffer(const LazyBuffer&) = delete;+ LazyBuffer& operator=(const LazyBuffer&) = delete;++ /**+ * @brief Gets aligned pointer to reserved buffer without loading data into it.+ */+ void* get_reserved_ptr() const noexcept {+ return m_aligned_buffer;+ }++ /**+ * @brief Evicts the buffer from memory. After this call, next call to hint_prefetch() will load the file content+ * again.+ */+ void hint_evict() noexcept override;++ /**+ * @brief Loads the file content if it is not loaded yet. The content is loaded at aligned addresses,+ * so the actual allocated memory may be larger than the requested byte size.+ * @throws AssertFailure if the file cannot be opened or read. In this case, the buffer remains unloaded.+ */+ void hint_prefetch() const override;++protected:+ void hint_evict(size_t offset, size_t size) noexcept override;++private:+ std::filesystem::path m_file_path;+ size_t m_offset{0};++ mutable std::atomic<bool> m_loaded{false};+ mutable std::mutex m_loading;+};+} // namespace ovdiff --git a/src/core/dev_api/openvino/runtime/shared_buffer.hpp b/src/core/dev_api/openvino/runtime/shared_buffer.hppindex 005838fa1af..895689ee17f 100644--- a/src/core/dev_api/openvino/runtime/shared_buffer.hpp+++ b/src/core/dev_api/openvino/runtime/shared_buffer.hpp@@ -44,6 +44,13 @@ public:}protected:+ template <typename U>+ struct is_aligned_buffer_ptr : std::false_type {};+ template <typename U>+ struct is_aligned_buffer_ptr<std::shared_ptr<U>> : std::is_base_of<ov::AlignedBuffer, U> {};+ template <typename U>+ static constexpr bool is_aligned_buffer_ptr_v = is_aligned_buffer_ptr<U>::value;+virtual void hint_evict(size_t offset, size_t size) noexcept override {if constexpr (std::is_same_v<std::shared_ptr<ov::MappedMemory>, T>) {if (m_shared_object) {@@ -53,6 +60,14 @@ protected:}}+ void hint_prefetch() const override {+ if constexpr (is_aligned_buffer_ptr_v<T>) {+ if (this->m_shared_object) {+ AlignedBuffer::invoke_hint_prefetch(*this->m_shared_object);+ }+ }+ }+// protected to not create SharedBufferBase directlySharedBufferBase(char* data,size_t size,@@ -109,17 +124,10 @@ protected:template <typename T>class SharedBuffer : public SharedBufferBase<T> {- template <typename U>- struct is_aligned_buffer_ptr : std::false_type {};- template <typename U>- struct is_aligned_buffer_ptr<std::shared_ptr<U>> : std::is_base_of<ov::AlignedBuffer, U> {};- template <typename U>- static constexpr bool is_aligned_buffer_ptr_v = is_aligned_buffer_ptr<U>::value;-static std::shared_ptr<IBufferDescriptor> get_or_make_descriptor(const T& shared_object) {if constexpr (std::is_same_v<T, std::shared_ptr<ov::MappedMemory>>) {return detail::create_mmap_descriptor(shared_object);- } else if constexpr (is_aligned_buffer_ptr_v<T>) {+ } else if constexpr (SharedBufferBase<T>::template is_aligned_buffer_ptr_v<T>) {return shared_object ? shared_object->get_descriptor() : nullptr;} else {return nullptr;diff --git a/src/core/src/runtime/aligned_buffer.cpp b/src/core/src/runtime/aligned_buffer.cppindex 62ab4cad983..632fd5606cc 100644--- a/src/core/src/runtime/aligned_buffer.cpp+++ b/src/core/src/runtime/aligned_buffer.cpp@@ -52,4 +52,10 @@ void AlignedBuffer::hint_evict(size_t offset, size_t size) noexcept {}void AlignedBuffer::invoke_evict(AlignedBuffer& buffer, size_t offset, size_t size) noexcept {buffer.hint_evict(offset, size);}++void AlignedBuffer::hint_prefetch() const {}++void AlignedBuffer::invoke_hint_prefetch(const AlignedBuffer& buffer) {+ buffer.hint_prefetch();+}} // namespace ovdiff --git a/src/core/src/runtime/lazy_buffer.cpp b/src/core/src/runtime/lazy_buffer.cppnew file mode 100644index 00000000000..55d006cd166--- /dev/null+++ b/src/core/src/runtime/lazy_buffer.cpp@@ -0,0 +1,109 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/runtime/lazy_buffer.hpp"++#include <istream>+#include <mutex>+#include <utility>++#include "openvino/core/except.hpp"+#include "openvino/core/memory_util.hpp"+#include "openvino/util/file_util.hpp"+#include "openvino/util/memory.hpp"+#include "openvino/util/parallel_read_streambuf.hpp"++namespace ov {+LazyBuffer::LazyBuffer(std::filesystem::path file_path, size_t offset, size_t byte_size)+ : AlignedBuffer(),+ m_file_path{std::move(file_path)},+ m_offset{offset},+ m_loaded{false} {+ m_byte_size = byte_size;++ const auto file_size = util::file_size(m_file_path);+ OPENVINO_ASSERT(file_size >= 0, "Failed to get file size for ", m_file_path);++ const bool offset_fits = m_offset <= static_cast<size_t>(file_size);+ const bool size_fits = m_byte_size <= static_cast<size_t>(file_size) - m_offset;+ OPENVINO_ASSERT(offset_fits && size_fits,+ "Requested region ",+ m_offset,+ "+",+ m_byte_size,+ " exceeds file size ",+ file_size,+ " for file: ",+ m_file_path);++ m_aligned_buffer = static_cast<char*>(util::reserve_buffer(m_byte_size));+ OPENVINO_ASSERT(m_aligned_buffer != nullptr, "Failed to reserve memory for LazyBuffer");+}++LazyBuffer::~LazyBuffer() {+ util::release_buffer(m_aligned_buffer, m_byte_size);+ m_aligned_buffer = nullptr;+ m_byte_size = 0;+}++LazyBuffer::LazyBuffer(LazyBuffer&& other) noexcept+ : AlignedBuffer(std::move(other)),+ m_file_path{std::move(other.m_file_path)},+ m_offset{std::exchange(other.m_offset, 0)},+ m_loaded{other.m_loaded.exchange(false, std::memory_order_relaxed)} {}++LazyBuffer& LazyBuffer::operator=(LazyBuffer&& other) noexcept {+ if (this != &other) {+ AlignedBuffer::operator=(std::move(other));+ m_file_path = std::move(other.m_file_path);+ m_offset = std::exchange(other.m_offset, 0);+ m_loaded = other.m_loaded.exchange(false, std::memory_order_relaxed);+ }+ return *this;+}++void LazyBuffer::hint_prefetch() const {+ if (!m_loaded.load(std::memory_order_acquire)) {+ std::lock_guard lock{m_loading};+ if (m_loaded.load(std::memory_order_relaxed)) {+ return;+ }++ std::string error;+ util::acquire_buffer(m_aligned_buffer, m_byte_size, &error);+ if (!error.empty()) {+ OPENVINO_THROW("Failed to acquire memory for LazyBuffer. Error: ", error);+ }++ try {+ util::ParallelReadStreamBuf par_buf(m_file_path, static_cast<std::streamoff>(m_offset));+ std::istream file(&par_buf);+ OPENVINO_ASSERT(file, "Failed to open file: ", m_file_path);+ file.read(m_aligned_buffer, m_byte_size);+ OPENVINO_ASSERT(file, "Failed to read data from file: ", m_file_path);+ m_loaded.store(true, std::memory_order_release);+ } catch (...) {+ util::evict_buffer(m_aligned_buffer, m_byte_size);+ throw;+ }+ }+}++void LazyBuffer::hint_evict() noexcept {+ hint_evict(0, m_byte_size);+}++void LazyBuffer::hint_evict(size_t offset, size_t size) noexcept {+ if (m_loaded.load(std::memory_order_acquire)) {+ try {+ std::lock_guard lock{m_loading};+ if (m_loaded.load(std::memory_order_relaxed)) {+ util::evict_buffer(m_aligned_buffer, m_byte_size);+ m_loaded.store(false, std::memory_order_release);+ }+ } catch (...) {+ }+ }+}+} // namespace ovdiff --git a/src/core/tests/lazy_buffer.cpp b/src/core/tests/lazy_buffer.cppnew file mode 100644index 00000000000..93b9791ea6b--- /dev/null+++ b/src/core/tests/lazy_buffer.cpp@@ -0,0 +1,142 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/runtime/lazy_buffer.hpp"++#include <gtest/gtest.h>++#include <fstream>+#include <string_view>++#include "common_test_utils/common_utils.hpp"+#include "common_test_utils/test_assertions.hpp"++using namespace testing;++namespace ov::test {+class LazyBufferTest : public Test {+protected:+ std::filesystem::path m_file_path;+ std::vector<char> m_test_data;++ void SetUp() override {+ m_file_path = utils::generateTestFilePrefix();+ }++ void TearDown() override {+ std::filesystem::remove(m_file_path);+ }++ void write_test_data(size_t size) {+ m_test_data.resize(size);+ std::iota(m_test_data.begin(), m_test_data.end(), 0);+ std::ofstream os(m_file_path, std::ios::binary);+ os.write(m_test_data.data(), m_test_data.size());+ }++ void overwrite_test_data(size_t offset, const std::vector<char>& data) {+ ASSERT_LE(offset + data.size(), m_test_data.size());+ std::copy(data.begin(), data.end(), m_test_data.begin() + offset);++ std::fstream fs(m_file_path, std::ios::binary | std::ios::in | std::ios::out);+ ASSERT_TRUE(fs.is_open());+ fs.seekp(offset);+ fs.write(data.data(), data.size());+ ASSERT_TRUE(fs.good());+ }+};++TEST_F(LazyBufferTest, incorrect_file) {+ OV_EXPECT_THROW(std::ignore = std::make_unique<LazyBuffer>(std::filesystem::path{"no_file"}, 1, 2),+ AssertFailure,+ HasSubstr("Failed to get file size"));++ write_test_data(4);++ const auto test_params =+ std::vector<std::tuple<size_t, size_t>>{{0, 5}, {1, 4}, {4, 2}, {0, std::numeric_limits<size_t>::max()}};+ for (const auto& [offset, size] : test_params) {+ OV_EXPECT_THROW(std::ignore = std::make_unique<LazyBuffer>(m_file_path, offset, size),+ AssertFailure,+ HasSubstr("exceeds file size"));+ }+}++TEST_F(LazyBufferTest, read_file) {+ write_test_data(457);+ const auto test_params = std::vector<std::tuple<size_t, size_t>>{{0, 10},+ {5, 20},+ {50, 100},+ {0, m_test_data.size()},+ {14, 15},+ {128, 256}};+ for (const auto& [offset, size] : test_params) {+ auto lazy_b = LazyBuffer{m_file_path, offset, size};+ AlignedBuffer& buffer = lazy_b;+ char* data_ptr = nullptr;+ ASSERT_NO_THROW((data_ptr = buffer.get_ptr<char>()));+ ASSERT_NE(data_ptr, nullptr);+ ASSERT_EQ(buffer.size(), size);+ EXPECT_THAT(std::string_view(data_ptr, size), ElementsAreArray(m_test_data.data() + offset, size));+ }+}++TEST_F(LazyBufferTest, load_on_first_get_ptr) {+ write_test_data(128);++ constexpr size_t offset = 37;+ constexpr size_t size = 9;+ const std::vector<char> first_rewrite{'L', 'A', 'Z', 'Y', ' ', 'D', 'A', 'T', 'A'};+ const std::vector<char> second_rewrite{'O', 'V', 'E', 'R', 'W', 'R', 'I', 'T', 'E'};++ std::unique_ptr<AlignedBuffer> buffer = std::make_unique<LazyBuffer>(m_file_path, offset, size);++ // If constructor eagerly reads file data, get_ptr() would return original bytes instead of first_rewrite.+ overwrite_test_data(offset, first_rewrite);++ char* first_ptr = nullptr;+ ASSERT_NO_THROW((first_ptr = buffer->get_ptr<char>()));+ ASSERT_NE(first_ptr, nullptr);+ ASSERT_TRUE(std::equal(first_ptr, first_ptr + size, first_rewrite.begin()));++ // Once loaded, subsequent get_ptr() calls should return cached memory and ignore later file overwrites.+ overwrite_test_data(offset, second_rewrite);++ char* second_ptr = nullptr;+ ASSERT_NO_THROW((second_ptr = buffer->get_ptr<char>()));+ ASSERT_EQ(second_ptr, first_ptr);+ EXPECT_THAT(first_rewrite, ElementsAreArray(second_ptr, size));+}++TEST_F(LazyBufferTest, evict_and_reload) {+ write_test_data(128);++ constexpr size_t offset = 31;+ constexpr size_t size = 9;+ const std::vector<char> first_rewrite{'L', 'A', 'Z', 'Y', ' ', 'D', 'A', 'T', 'A'};+ const std::vector<char> second_rewrite{'O', 'V', 'E', 'R', 'W', 'R', 'I', 'T', 'E'};++ const auto buffer = std::make_unique<LazyBuffer>(m_file_path, offset, size);++ overwrite_test_data(offset, first_rewrite);+ char* first_ptr = nullptr;+ ASSERT_NO_THROW((first_ptr = buffer->get_ptr<char>()));+ ASSERT_NE(first_ptr, nullptr);+ ASSERT_THAT(first_rewrite, ElementsAreArray(first_ptr, size));++ // After evict(), get_ptr() should load the same file content again+ buffer->hint_evict();+ ASSERT_NO_THROW((first_ptr = buffer->get_ptr<char>()));+ ASSERT_NE(first_ptr, nullptr);+ ASSERT_THAT(first_rewrite, ElementsAreArray(first_ptr, size));++ // After evict(), get_ptr() should load the file content again and reflect the second overwrite.+ buffer->hint_evict();+ overwrite_test_data(offset, second_rewrite);+ char* second_ptr = nullptr;+ ASSERT_NO_THROW((second_ptr = buffer->get_ptr<char>()));+ ASSERT_EQ(second_ptr, first_ptr);+ EXPECT_THAT(second_rewrite, ElementsAreArray(second_ptr, size));+}+} // namespace ov::testdiff --git a/src/frontends/onnx/frontend/src/utils/tensor_external_data.cpp b/src/frontends/onnx/frontend/src/utils/tensor_external_data.cppindex 605c3aacd46..2146fe68ebb 100644--- a/src/frontends/onnx/frontend/src/utils/tensor_external_data.cpp+++ b/src/frontends/onnx/frontend/src/utils/tensor_external_data.cpp@@ -8,6 +8,7 @@#include <sstream>#include "exceptions.hpp"+#include "openvino/runtime/lazy_buffer.hpp"#include "openvino/util/file_util.hpp"#include "openvino/util/log.hpp"@@ -77,30 +78,39 @@ Buffer<ov::AlignedBuffer> TensorExternalData::load_external_data(const std::file} catch (const std::runtime_error& e) {throw error::invalid_external_data{e.what()};}- std::ifstream external_data_stream(full_path, std::ios::binary | std::ios::in | std::ios::ate);- if (external_data_stream.fail()) {- throw error::invalid_external_data{*this};- }- const uint64_t file_size = static_cast<uint64_t>(external_data_stream.tellg());- if (m_data_length > file_size || m_offset > file_size - m_data_length) {+ const auto file_size = util::file_size(full_path);+ if (file_size < 0 || m_data_length > static_cast<uint64_t>(file_size) ||+ m_offset > static_cast<uint64_t>(file_size) - m_data_length) {throw error::invalid_external_data{*this};}uint64_t read_data_length = m_data_length > 0 ? m_data_length : static_cast<uint64_t>(file_size) - m_offset;+ const auto get_now_buffer = [&]() {+ std::ifstream external_data_stream(full_path, std::ios::binary | std::ios::in | std::ios::ate);+ if (external_data_stream.fail()) {+ throw error::invalid_external_data{*this};+ }+ // default value of m_offset is 0+ external_data_stream.seekg(m_offset, std::ios::beg);- // default value of m_offset is 0- external_data_stream.seekg(m_offset, std::ios::beg);-- auto read_data = std::make_shared<ov::AlignedBuffer>(read_data_length);- external_data_stream.read(read_data->get_ptr<char>(), read_data_length);- external_data_stream.close();-- auto buffer = std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>(read_data->get_ptr<char>(),- read_data->size(),- read_data);+ auto read_data = std::make_shared<ov::AlignedBuffer>(read_data_length);+ external_data_stream.read(read_data->get_ptr<char>(), read_data_length);+ external_data_stream.close();+ return std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>(read_data->get_ptr<char>(),+ read_data->size(),+ read_data);+ };+ const auto get_lazy_buffer = [&]() {+ const auto lazy = std::make_shared<LazyBuffer>(full_path, m_offset, read_data_length);+ return std::make_shared<SharedBuffer<std::shared_ptr<AlignedBuffer>>>(+ static_cast<char*>(lazy->get_reserved_ptr()),+ lazy->size(),+ lazy);+ };- return buffer;+ constexpr size_t lazy_loading_threshold = 0x100000; // 1MB+ return read_data_length >= lazy_loading_threshold ? get_lazy_buffer() : get_now_buffer();}Buffer<ov::AlignedBuffer> TensorExternalData::load_external_mem_data() const {