Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

Fix HETERO compiled blob export/import (#36704)

guozhong wangf603e489ca30
diff --git a/src/plugins/hetero/src/blob_serialization.cpp b/src/plugins/hetero/src/blob_serialization.cpp
new file mode 100644
index 00000000000..c75b2993b11
--- /dev/null
+++ b/src/plugins/hetero/src/blob_serialization.cpp
@@ -0,0 +1,515 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "blob_serialization.hpp"
+
+#include <algorithm>
+#include <array>
+#include <limits>
+#include <sstream>
+
+#include "openvino/core/except.hpp"
+#include "openvino/pass/serialize.hpp"
+#include "openvino/runtime/compiled_model.hpp"
+#include "openvino/runtime/icore.hpp"
+#include "openvino/runtime/tensor.hpp"
+
+namespace ov::hetero {
+namespace {
+
+std::streamsize checked_stream_size(std::uint64_t size, const char* fieldName) {
+ OPENVINO_ASSERT(size <= static_cast<std::uint64_t>(std::numeric_limits<std::streamsize>::max()),
+ "HETERO compiled blob ",
+ fieldName,
+ " size is too large: ",
+ size);
+ return static_cast<std::streamsize>(size);
+}
+
+std::streamoff checked_stream_offset(std::uint64_t offset, const char* fieldName) {
+ OPENVINO_ASSERT(offset <= static_cast<std::uint64_t>(std::numeric_limits<std::streamoff>::max()),
+ "HETERO compiled blob ",
+ fieldName,
+ " offset is too large: ",
+ offset);
+ return static_cast<std::streamoff>(offset);
+}
+
+void write_bytes(std::ostream& stream, const char* data, std::uint64_t size, const char* fieldName) {
+ stream.write(data, checked_stream_size(size, fieldName));
+ OPENVINO_ASSERT(stream, "Failed to write HETERO compiled blob ", fieldName);
+}
+
+std::uint64_t read_size(std::istream& stream, const char* fieldName) {
+ std::uint64_t size = 0;
+ read_payload_bytes(stream, reinterpret_cast<char*>(&size), sizeof(size), fieldName);
+ return size;
+}
+
+void consume_payload_bytes(std::uint64_t& remainingPayloadSize, std::uint64_t size, const char* fieldName) {
+ if (remainingPayloadSize == std::numeric_limits<std::uint64_t>::max()) {
+ return;
+ }
+
+ OPENVINO_ASSERT(size <= remainingPayloadSize,
+ "HETERO compiled blob ",
+ fieldName,
+ " size exceeds remaining IR payload: ",
+ size,
+ " > ",
+ remainingPayloadSize);
+ remainingPayloadSize -= size;
+}
+
+std::uint64_t remaining_stream_bytes(std::istream& stream) {
+ const auto currentPos = stream.tellg();
+ if (currentPos == std::streampos(-1)) {
+ return std::numeric_limits<std::uint64_t>::max();
+ }
+
+ stream.clear();
+ stream.seekg(0, std::ios_base::end);
+ const auto endPos = stream.tellg();
+ stream.clear();
+ stream.seekg(currentPos);
+
+ if (endPos == std::streampos(-1) || endPos < currentPos || !stream) {
+ stream.clear();
+ return std::numeric_limits<std::uint64_t>::max();
+ }
+
+ return static_cast<std::uint64_t>(endPos - currentPos);
+}
+
+void write_size(std::ostream& stream, std::uint64_t size, const char* fieldName) {
+ stream.write(reinterpret_cast<const char*>(&size), sizeof(size));
+ OPENVINO_ASSERT(stream, "Failed to write HETERO compiled blob ", fieldName);
+}
+
+} // namespace
+
+BoundedStreamBuffer::BoundedStreamBuffer(std::istream& stream, std::uint64_t size)
+ : _stream(stream),
+ _start(stream.tellg()),
+ _size(size) {
+ _seekable = _start != std::streampos(-1);
+ checked_stream_offset(_size, "payload");
+}
+
+std::streampos BoundedStreamBuffer::end_pos() const {
+ OPENVINO_ASSERT(_seekable, "HETERO compiled blob input stream is not seekable");
+ return _start + checked_stream_offset(_size, "payload");
+}
+
+void BoundedStreamBuffer::consume_remaining_payload() {
+ std::uint64_t remaining = _size - _pos;
+ if (remaining == 0) {
+ return;
+ }
+
+ if (_has_current) {
+ _has_current = false;
+ ++_pos;
+ --remaining;
+ }
+
+ std::array<char, 4096> scratch{};
+ while (remaining > 0) {
+ const auto chunk = static_cast<std::streamsize>(
+ std::min<std::uint64_t>(remaining, static_cast<std::uint64_t>(scratch.size())));
+ _stream.read(scratch.data(), chunk);
+ const auto read = _stream.gcount();
+ OPENVINO_ASSERT(read == chunk && !_stream.bad(),
+ "Failed to consume remaining HETERO compiled blob payload bytes");
+ _pos += static_cast<std::uint64_t>(read);
+ remaining -= static_cast<std::uint64_t>(read);
+ }
+}
+
+std::streamsize BoundedStreamBuffer::xsgetn(char* data, std::streamsize count) {
+ if (count <= 0 || _pos >= _size) {
+ return 0;
+ }
+
+ std::streamsize totalRead = 0;
+ if (_has_current) {
+ *data = _current;
+ _has_current = false;
+ ++_pos;
+ ++data;
+ --count;
+ ++totalRead;
+ }
+
+ if (count <= 0 || _pos >= _size) {
+ return totalRead;
+ }
+
+ const auto bytesToRead = std::min(static_cast<std::uint64_t>(count), _size - _pos);
+ _stream.read(data, static_cast<std::streamsize>(bytesToRead));
+
+ const auto bytesRead = _stream.gcount();
+ _pos += static_cast<std::uint64_t>(bytesRead);
+ totalRead += bytesRead;
+ return totalRead;
+}
+
+BoundedStreamBuffer::int_type BoundedStreamBuffer::uflow() {
+ if (_has_current) {
+ _has_current = false;
+ ++_pos;
+ return traits_type::to_int_type(_current);
+ }
+
+ if (_pos >= _size) {
+ return traits_type::eof();
+ }
+
+ _stream.read(&_current, 1);
+ if (_stream.gcount() != 1) {
+ return traits_type::eof();
+ }
+
+ ++_pos;
+ return traits_type::to_int_type(_current);
+}
+
+BoundedStreamBuffer::int_type BoundedStreamBuffer::underflow() {
+ if (_has_current) {
+ return traits_type::to_int_type(_current);
+ }
+
+ if (_pos >= _size) {
+ return traits_type::eof();
+ }
+
+ _stream.read(&_current, 1);
+ if (_stream.gcount() != 1) {
+ return traits_type::eof();
+ }
+
+ _has_current = true;
+ return traits_type::to_int_type(_current);
+}
+
+std::streamsize BoundedStreamBuffer::showmanyc() {
+ const auto available = _size - _pos;
+ return static_cast<std::streamsize>(
+ std::min<std::uint64_t>(available, static_cast<std::uint64_t>(std::numeric_limits<std::streamsize>::max())));
+}
+
+BoundedStreamBuffer::pos_type BoundedStreamBuffer::seekoff(off_type off,
+ std::ios_base::seekdir dir,
+ std::ios_base::openmode which) {
+ if ((which & std::ios_base::in) == 0) {
+ return pos_type(off_type(-1));
+ }
+
+ if (!_seekable) {
+ if (dir == std::ios_base::cur && off == 0) {
+ return pos_type(static_cast<off_type>(_pos));
+ }
+ return pos_type(off_type(-1));
+ }
+
+ off_type base = 0;
+ if (dir == std::ios_base::cur) {
+ base = static_cast<off_type>(_pos);
+ } else if (dir == std::ios_base::end) {
+ base = static_cast<off_type>(_size);
+ } else if (dir != std::ios_base::beg) {
+ return pos_type(off_type(-1));
+ }
+
+ const auto newPos = base + off;
+ if (newPos < 0 || static_cast<std::uint64_t>(newPos) > _size) {
+ return pos_type(off_type(-1));
+ }
+
+ _pos = static_cast<std::uint64_t>(newPos);
+ _has_current = false;
+ _stream.clear();
+ _stream.seekg(_start + checked_stream_offset(_pos, "payload position"));
+ if (!_stream) {
+ return pos_type(off_type(-1));
+ }
+ setg(nullptr, nullptr, nullptr);
+ return pos_type(static_cast<off_type>(_pos));
+}
+
+BoundedStreamBuffer::pos_type BoundedStreamBuffer::seekpos(pos_type pos, std::ios_base::openmode which) {
+ return seekoff(static_cast<off_type>(pos), std::ios_base::beg, which);
+}
+
+void read_payload_bytes(std::istream& stream, char* data, std::uint64_t size, const char* fieldName) {
+ const auto streamSize = checked_stream_size(size, fieldName);
+ if (streamSize == 0) {
+ return;
+ }
+ stream.read(data, streamSize);
+ OPENVINO_ASSERT(stream.gcount() == streamSize && !stream.bad(), "Failed to read HETERO compiled blob ", fieldName);
+}
+
+FramedPayloadOutputBuffer::FramedPayloadOutputBuffer(std::ostream& stream)
+ : _stream(stream),
+ _start(stream.tellp()),
+ _underlyingPos(_start) {
+ OPENVINO_ASSERT(_start != std::streampos(-1), "HETERO compiled blob output stream is not seekable");
+}
+
+std::uint64_t FramedPayloadOutputBuffer::written_size() const {
+ return _writtenSize;
+}
+
+std::streamsize FramedPayloadOutputBuffer::xsputn(const char* data, std::streamsize count) {
+ if (count <= 0) {
+ return 0;
+ }
+
+ const auto bytes = static_cast<std::uint64_t>(count);
+ OPENVINO_ASSERT(_pos <= std::numeric_limits<std::uint64_t>::max() - bytes,
+ "HETERO compiled blob payload position overflow");
+ const auto newPos = _pos + bytes;
+ checked_stream_offset(newPos, "payload position");
+
+ _stream.clear();
+ const auto writePos = _start + checked_stream_offset(_pos, "payload position");
+ if (_underlyingPos != writePos) {
+ _stream.seekp(writePos);
+ _underlyingPos = writePos;
+ }
+ _stream.write(data, count);
+ OPENVINO_ASSERT(_stream, "Failed to write HETERO compiled blob payload data");
+
+ _pos = newPos;
+ _underlyingPos = _start + checked_stream_offset(_pos, "payload position");
+ _writtenSize = std::max(_writtenSize, _pos);
+ return count;
+}
+
+FramedPayloadOutputBuffer::int_type FramedPayloadOutputBuffer::overflow(int_type ch) {
+ if (traits_type::eq_int_type(ch, traits_type::eof())) {
+ return traits_type::not_eof(ch);
+ }
+
+ const char c = traits_type::to_char_type(ch);
+ return xsputn(&c, 1) == 1 ? ch : traits_type::eof();
+}
+
+FramedPayloadOutputBuffer::pos_type FramedPayloadOutputBuffer::seekoff(off_type off,
+ std::ios_base::seekdir dir,
+ std::ios_base::openmode which) {
+ if ((which & std::ios_base::out) == 0) {
+ return pos_type(off_type(-1));
+ }
+
+ off_type base = 0;
+ if (dir == std::ios_base::cur) {
+ base = static_cast<off_type>(_pos);
+ } else if (dir == std::ios_base::end) {
+ base = static_cast<off_type>(_writtenSize);
+ } else if (dir != std::ios_base::beg) {
+ return pos_type(off_type(-1));
+ }
+
+ const auto newPos = base + off;
+ if (newPos < 0) {
+ return pos_type(off_type(-1));
+ }
+
+ if (static_cast<std::uint64_t>(newPos) > _writtenSize) {
+ return pos_type(off_type(-1));
+ }
+ const auto uNewPos = static_cast<std::uint64_t>(newPos);
+ checked_stream_offset(uNewPos, "payload position");
+ _pos = uNewPos;
+ return pos_type(static_cast<off_type>(_pos));
+}
+
+FramedPayloadOutputBuffer::pos_type FramedPayloadOutputBuffer::seekpos(pos_type pos, std::ios_base::openmode which) {
+ return seekoff(static_cast<off_type>(pos), std::ios_base::beg, which);
+}
+
+BoundedStringOutputBuffer::BoundedStringOutputBuffer(std::uint64_t maxSize) : _maxSize(maxSize) {
+ checked_stream_size(maxSize, "buffered payload");
+}
+
+const std::string& BoundedStringOutputBuffer::str() const {
+ return _data;
+}
+
+std::streamsize BoundedStringOutputBuffer::xsputn(const char* data, std::streamsize count) {
+ if (count <= 0) {
+ return 0;
+ }
+
+ const auto writeSize = static_cast<std::uint64_t>(count);
+ const auto currentSize = static_cast<std::uint64_t>(_data.size());
+ if (currentSize > _maxSize || writeSize > (_maxSize - currentSize)) {
+ // Signal iostream failure (short write) instead of throwing from inside the streambuf.
+ return 0;
+ }
+
+ _data.append(data, static_cast<std::string::size_type>(count));
+ return count;
+}
+
+BoundedStringOutputBuffer::int_type BoundedStringOutputBuffer::overflow(int_type ch) {
+ if (traits_type::eq_int_type(ch, traits_type::eof())) {
+ return traits_type::not_eof(ch);
+ }
+
+ const char c = traits_type::to_char_type(ch);
+ return xsputn(&c, 1) == 1 ? ch : traits_type::eof();
+}
+
+bool is_output_stream_seekable(std::ostream& model_stream) {
+ const auto pos = model_stream.tellp();
+ if (pos == std::streampos(-1)) {
+ return false;
+ }
+
+ const auto state = model_stream.rdstate();
+ model_stream.clear();
+ model_stream.seekp(pos);
+ const bool seekable = static_cast<bool>(model_stream);
+ model_stream.clear(state);
+ return seekable;
+}
+
+PayloadFrame start_framed_payload(std::ostream& model_stream, char payloadType) {
+ const auto frameStartPos = model_stream.tellp();
+ OPENVINO_ASSERT(frameStartPos != std::streampos(-1), "HETERO compiled blob output stream is not seekable");
+
+ write_bytes(model_stream, &payloadType, sizeof(payloadType), "payload type");
+ const auto sizePos = model_stream.tellp();
+ OPENVINO_ASSERT(sizePos != std::streampos(-1), "HETERO compiled blob output stream is not seekable");
+
+ write_size(model_stream, 0, "payload size");
+ const auto payloadStartPos = model_stream.tellp();
+ OPENVINO_ASSERT(payloadStartPos != std::streampos(-1), "HETERO compiled blob output stream is not seekable");
+
+ return {frameStartPos, sizePos, payloadStartPos};
+}
+
+void finish_framed_payload(std::ostream& model_stream, const PayloadFrame& payloadFrame) {
+ const auto payloadEndPos = model_stream.tellp();
+ OPENVINO_ASSERT(payloadEndPos != std::streampos(-1), "HETERO compiled blob output stream is not seekable");
+ OPENVINO_ASSERT(payloadEndPos >= payloadFrame.payload_start_pos,
+ "HETERO compiled blob payload end position is before payload start");
+
+ const auto payloadSize = static_cast<std::uint64_t>(payloadEndPos - payloadFrame.payload_start_pos);
+
+ finish_framed_payload(model_stream, payloadFrame, payloadSize);
+}
+
+void finish_framed_payload(std::ostream& model_stream, const PayloadFrame& payloadFrame, std::uint64_t payloadSize) {
+ const auto payloadEndPos = payloadFrame.payload_start_pos + checked_stream_offset(payloadSize, "payload");
+
+ model_stream.clear();
+ model_stream.seekp(payloadFrame.size_pos);
+ write_size(model_stream, payloadSize, "payload size");
+
+ model_stream.clear();
+ model_stream.seekp(payloadEndPos);
+ OPENVINO_ASSERT(model_stream, "Failed to restore HETERO compiled blob output stream position");
+}
+
+void write_framed_payload(std::ostream& model_stream, char payloadType, const std::string& payload) {
+ write_bytes(model_stream, &payloadType, sizeof(payloadType), "payload type");
+ write_size(model_stream, static_cast<std::uint64_t>(payload.size()), "payload size");
+ write_bytes(model_stream, payload.data(), payload.size(), "payload data");
+}
+
+void write_framed_payload(std::ostream& model_stream,
+ char payloadType,
+ std::istream& payloadStream,
+ std::uint64_t payloadSize) {
+ write_bytes(model_stream, &payloadType, sizeof(payloadType), "payload type");
+ write_size(model_stream, payloadSize, "payload size");
+
+ std::array<char, 4096> buffer{};
+ std::uint64_t remaining = payloadSize;
+ while (remaining > 0) {
+ const auto chunk = std::min<std::uint64_t>(remaining, static_cast<std::uint64_t>(buffer.size()));
+ read_payload_bytes(payloadStream, buffer.data(), chunk, "payload data");
+ write_bytes(model_stream, buffer.data(), chunk, "payload data");
+ remaining -= chunk;
+ }
+}
+
+PayloadHeader read_payload_header(std::istream& model_stream) {
+ PayloadHeader payloadHeader;
+ read_payload_bytes(model_stream, &payloadHeader.type, sizeof(payloadHeader.type), "payload type");
+ payloadHeader.size = read_size(model_stream, "payload size");
+ return payloadHeader;
+}
+
+void read_ir_payload(std::istream& model,
+ const std::shared_ptr<ov::ICore>& core,
+ const std::string& device,
+ const ov::AnyMap& loadConfig,
+ std::shared_ptr<ov::Model>& ov_model,
+ ov::SoPtr<ov::ICompiledModel>& compiled_model,
+ std::uint64_t payloadSize) {
+ const auto hasPayloadBoundary = payloadSize != std::numeric_limits<std::uint64_t>::max();
+ auto remainingPayloadSize = hasPayloadBoundary ? payloadSize : remaining_stream_bytes(model);
+
+ std::string xmlString;
+ consume_payload_bytes(remainingPayloadSize, sizeof(std::uint64_t), "IR XML size");
+ auto dataSize = read_size(model, "IR XML size");
+ consume_payload_bytes(remainingPayloadSize, dataSize, "IR XML content");
+ OPENVINO_ASSERT(dataSize <= static_cast<std::uint64_t>(std::numeric_limits<std::string::size_type>::max()),
+ "HETERO compiled blob IR XML size is too large: ",
+ dataSize);
+ checked_stream_size(dataSize, "IR XML content");
+ xmlString.resize(static_cast<std::string::size_type>(dataSize));
+ read_payload_bytes(model, xmlString.data(), dataSize, "IR XML content");
+
+ ov::Tensor weights;
+ consume_payload_bytes(remainingPayloadSize, sizeof(std::uint64_t), "IR weights size");
+ dataSize = read_size(model, "IR weights size");
+ consume_payload_bytes(remainingPayloadSize, dataSize, "IR weights content");
+ if (dataSize != 0) {
+ OPENVINO_ASSERT(dataSize <= static_cast<std::uint64_t>(std::numeric_limits<ov::Shape::size_type>::max()),
+ "HETERO compiled blob IR weights size is too large: ",
+ dataSize);
+ checked_stream_size(dataSize, "IR weights content");
+ weights = ov::Tensor(ov::element::u8, ov::Shape{static_cast<ov::Shape::size_type>(dataSize)});
+ read_payload_bytes(model,
+ reinterpret_cast<char*>(weights.data<std::uint8_t>()),
+ dataSize,
+ "IR weights content");
+ }
+
+ OPENVINO_ASSERT(!hasPayloadBoundary || remainingPayloadSize == 0,
+ "HETERO compiled blob IR payload has unexpected trailing data: ",
+ remainingPayloadSize);
+
+ ov_model = core->read_model(xmlString, weights);
+ compiled_model = core->compile_model(ov_model, device, loadConfig);
+}
+
+void write_ir_payload(std::ostream& model_stream, const std::shared_ptr<ov::Model>& model) {
+ if (!model) {
+ OPENVINO_THROW("OpenVINO Model is empty");
+ }
+
+ std::stringstream xmlFile, binFile;
+ ov::pass::Serialize serializer(xmlFile, binFile);
+ serializer.run_on_model(model);
+
+ auto constants = binFile.str();
+ auto model_str = xmlFile.str();
+
+ auto dataSize = static_cast<std::uint64_t>(model_str.size());
+ write_size(model_stream, dataSize, "IR XML size");
+ write_bytes(model_stream, model_str.data(), dataSize, "IR XML content");
+
+ dataSize = static_cast<std::uint64_t>(constants.size());
+ write_size(model_stream, dataSize, "IR weights size");
+ write_bytes(model_stream, constants.data(), dataSize, "IR weights content");
+}
+
+} // namespace ov::hetero
diff --git a/src/plugins/hetero/src/blob_serialization.hpp b/src/plugins/hetero/src/blob_serialization.hpp
new file mode 100644
index 00000000000..f8f0ba28d30
--- /dev/null
+++ b/src/plugins/hetero/src/blob_serialization.hpp
@@ -0,0 +1,125 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstdint>
+#include <ios>
+#include <istream>
+#include <memory>
+#include <ostream>
+#include <streambuf>
+#include <string>
+
+#include "openvino/core/any.hpp"
+#include "openvino/runtime/so_ptr.hpp"
+
+namespace ov {
+class ICore;
+class ICompiledModel;
+class Model;
+} // namespace ov
+
+namespace ov::hetero {
+
+constexpr std::uint32_t HETERO_BLOB_FORMAT_VERSION = 2;
+constexpr const char* HETERO_BLOB_FORMAT_VERSION_ATTR = "blob_format_version";
+constexpr char COMPILED_BLOB_PAYLOAD = 'B';
+constexpr char IR_PAYLOAD = 'I';
+constexpr std::uint64_t MAX_IN_MEMORY_COMPILED_PAYLOAD_SIZE = 64ULL * 1024ULL * 1024ULL;
+
+class BoundedStreamBuffer : public std::streambuf {
+public:
+ BoundedStreamBuffer(std::istream& stream, std::uint64_t size);
+
+ std::streampos end_pos() const;
+ void consume_remaining_payload();
+
+protected:
+ std::streamsize xsgetn(char* data, std::streamsize count) override;
+ int_type uflow() override;
+ int_type underflow() override;
+ std::streamsize showmanyc() override;
+ pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) override;
+ pos_type seekpos(pos_type pos, std::ios_base::openmode which) override;
+
+private:
+ std::istream& _stream;
+ std::streampos _start;
+ bool _seekable = false;
+ std::uint64_t _size = 0;
+ std::uint64_t _pos = 0;
+ char _current = 0;
+ bool _has_current = false;
+};
+
+class FramedPayloadOutputBuffer : public std::streambuf {
+public:
+ explicit FramedPayloadOutputBuffer(std::ostream& stream);
+
+ std::uint64_t written_size() const;
+
+protected:
+ std::streamsize xsputn(const char* data, std::streamsize count) override;
+ int_type overflow(int_type ch) override;
+ pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) override;
+ pos_type seekpos(pos_type pos, std::ios_base::openmode which) override;
+
+private:
+ std::ostream& _stream;
+ std::streampos _start;
+ std::streampos _underlyingPos;
+ std::uint64_t _pos = 0;
+ std::uint64_t _writtenSize = 0;
+};
+
+class BoundedStringOutputBuffer : public std::streambuf {
+public:
+ explicit BoundedStringOutputBuffer(std::uint64_t maxSize);
+
+ const std::string& str() const;
+
+protected:
+ std::streamsize xsputn(const char* data, std::streamsize count) override;
+ int_type overflow(int_type ch) override;
+
+private:
+ std::uint64_t _maxSize = 0;
+ std::string _data;
+};
+
+struct PayloadHeader {
+ char type = 0;
+ std::uint64_t size = 0;
+};
+
+struct PayloadFrame {
+ std::streampos frame_start_pos;
+ std::streampos size_pos;
+ std::streampos payload_start_pos;
+};
+
+bool is_output_stream_seekable(std::ostream& model_stream);
+PayloadFrame start_framed_payload(std::ostream& model_stream, char payloadType);
+void finish_framed_payload(std::ostream& model_stream, const PayloadFrame& payloadFrame, std::uint64_t payloadSize);
+void finish_framed_payload(std::ostream& model_stream, const PayloadFrame& payloadFrame);
+void write_framed_payload(std::ostream& model_stream, char payloadType, const std::string& payload);
+void write_framed_payload(std::ostream& model_stream,
+ char payloadType,
+ std::istream& payloadStream,
+ std::uint64_t payloadSize);
+PayloadHeader read_payload_header(std::istream& model_stream);
+void read_payload_bytes(std::istream& stream, char* data, std::uint64_t size, const char* fieldName);
+
+void read_ir_payload(std::istream& model,
+ const std::shared_ptr<ov::ICore>& core,
+ const std::string& device,
+ const ov::AnyMap& loadConfig,
+ std::shared_ptr<ov::Model>& ov_model,
+ ov::SoPtr<ov::ICompiledModel>& compiled_model,
+ std::uint64_t payloadSize);
+
+void write_ir_payload(std::ostream& model_stream, const std::shared_ptr<ov::Model>& model);
+
+} // namespace ov::hetero
diff --git a/src/plugins/hetero/src/compiled_model.cpp b/src/plugins/hetero/src/compiled_model.cpp
index 828facb509b..c46bea974d3 100644
--- a/src/plugins/hetero/src/compiled_model.cpp
+++ b/src/plugins/hetero/src/compiled_model.cpp
@@ -4,10 +4,16 @@
#include "compiled_model.hpp"
+#include <algorithm>
#include <chrono>
+#include <cstdint>
+#include <limits>
#include <memory>
+#include <sstream>
+#include <string>
#include "async_infer_request.hpp"
+#include "blob_serialization.hpp"
#include "graph_debug_dump.hpp"
#include "itt.hpp"
#include "op/device_subgraph.hpp"
@@ -21,6 +27,105 @@
#include "perf_log.hpp"
#include "properties.hpp"
+namespace {
+
+class CountingOutputBuffer : public std::streambuf {
+public:
+ std::uint64_t size() const {
+ return _size;
+ }
+
+protected:
+ std::streamsize xsputn(const char*, std::streamsize count) override {
+ if (count <= 0) {
+ return 0;
+ }
+
+ const auto bytes = static_cast<std::uint64_t>(count);
+ OPENVINO_ASSERT(_size <= std::numeric_limits<std::uint64_t>::max() - bytes,
+ "HETERO compiled blob payload size is too large");
+ _size += bytes;
+ return count;
+ }
+
+ int_type overflow(int_type ch) override {
+ if (traits_type::eq_int_type(ch, traits_type::eof())) {
+ return traits_type::not_eof(ch);
+ }
+
+ OPENVINO_ASSERT(_size < std::numeric_limits<std::uint64_t>::max(),
+ "HETERO compiled blob payload size is too large");
+ ++_size;
+ return ch;
+ }
+
+private:
+ std::uint64_t _size = 0;
+};
+
+template <typename ExportPayload>
+void write_framed_payload_two_pass(std::ostream& modelStream,
+ char payloadType,
+ ExportPayload exportPayload,
+ const char* fieldName) {
+ CountingOutputBuffer countingBuffer;
+ std::ostream countingStream(&countingBuffer);
+ exportPayload(countingStream);
+ OPENVINO_ASSERT(countingStream, "Failed to export HETERO compiled blob ", fieldName);
+
+ const auto payloadSize = countingBuffer.size();
+ modelStream.write(&payloadType, sizeof(payloadType));
+ OPENVINO_ASSERT(modelStream, "Failed to write HETERO compiled blob payload type");
+ modelStream.write(reinterpret_cast<const char*>(&payloadSize), sizeof(payloadSize));
+ OPENVINO_ASSERT(modelStream, "Failed to write HETERO compiled blob payload size");
+
+ try {
+ exportPayload(modelStream);
+ } catch (const ov::NotImplemented&) {
+ OPENVINO_THROW("Cannot continue HETERO compiled blob export after starting framed payload ",
+ fieldName,
+ ". Child plugin reported NotImplemented during streaming pass");
+ }
+ OPENVINO_ASSERT(modelStream, "Failed to write HETERO compiled blob ", fieldName);
+}
+
+void write_ir_framed_payload(std::ostream& modelStream, const std::shared_ptr<ov::Model>& model) {
+ write_framed_payload_two_pass(
+ modelStream,
+ ov::hetero::IR_PAYLOAD,
+ [&](std::ostream& payloadStream) {
+ ov::hetero::write_ir_payload(payloadStream, model);
+ },
+ "IR payload");
+}
+
+template <typename ExportPayload>
+void write_framed_payload_via_seekable_stream(std::ostream& modelStream,
+ char payloadType,
+ ExportPayload exportPayload,
+ const char* fieldName) {
+ std::stringstream payloadStream(std::ios::in | std::ios::out | std::ios::binary);
+ exportPayload(payloadStream);
+ OPENVINO_ASSERT(payloadStream, "Failed to export HETERO compiled blob ", fieldName);
+
+ payloadStream.clear();
+ payloadStream.seekp(0, std::ios::end);
+ const auto payloadEndPos = payloadStream.tellp();
+ OPENVINO_ASSERT(payloadEndPos != std::streampos(-1),
+ "Failed to determine HETERO compiled blob ",
+ fieldName,
+ " size");
+
+ const auto payloadSize = static_cast<std::uint64_t>(payloadEndPos);
+ payloadStream.clear();
+ payloadStream.seekg(0, std::ios::beg);
+ OPENVINO_ASSERT(payloadStream, "Failed to rewind HETERO compiled blob ", fieldName);
+
+ ov::hetero::write_framed_payload(modelStream, payloadType, payloadStream, payloadSize);
+}
+
+} // namespace
+
ov::hetero::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
const std::vector<ov::hetero::SubmodelInfo>& submodels,
const SubgraphsMappingInfo& mapping_info,
@@ -162,6 +267,23 @@ ov::hetero::CompiledModel::CompiledModel(std::istream& model,
pugi::xml_node heteroNode = heteroXmlDoc.document_element();
m_name = get_str_attr(heteroNode, "name");
+ const auto version_attr = heteroNode.attribute(HETERO_BLOB_FORMAT_VERSION_ATTR);
+ std::uint32_t blob_format_version = 1;
+ if (version_attr) {
+ const std::string version_str = version_attr.value();
+ if (version_str == "1") {
+ blob_format_version = 1;
+ } else if (version_str == std::to_string(HETERO_BLOB_FORMAT_VERSION)) {
+ blob_format_version = HETERO_BLOB_FORMAT_VERSION;
+ } else {
+ OPENVINO_THROW("Unsupported HETERO compiled blob format version: ",
+ version_str,
+ ". Supported versions are 1 (legacy unframed) and ",
+ HETERO_BLOB_FORMAT_VERSION,
+ " (framed). ");
+ }
+ }
+ const bool is_framed_blob = blob_format_version == HETERO_BLOB_FORMAT_VERSION;
ov::AnyMap properties;
auto heteroConfigsNode = heteroNode.child("hetero_config");
@@ -183,26 +305,40 @@ ov::hetero::CompiledModel::CompiledModel(std::istream& model,
ov::SoPtr<ov::ICompiledModel> compiled_model;
std::shared_ptr<ov::Model> ov_model;
- if (get_plugin()->get_core()->device_supports_model_caching(device)) {
- compiled_model = plugin->get_core()->import_model(model, device, loadConfig);
- } else {
- // read XML content
- std::string xmlString;
- std::uint64_t dataSize = 0;
- model.read(reinterpret_cast<char*>(&dataSize), sizeof(dataSize));
- xmlString.resize(dataSize);
- model.read(const_cast<char*>(xmlString.c_str()), dataSize);
-
- /// read blob content
- ov::Tensor weights;
- model.read(reinterpret_cast<char*>(&dataSize), sizeof(dataSize));
- if (0 != dataSize) {
- weights = ov::Tensor(ov::element::from<char>(), ov::Shape{static_cast<ov::Shape::size_type>(dataSize)});
- model.read(weights.data<char>(), dataSize);
+ const auto& core = plugin->get_core();
+ if (is_framed_blob) {
+ const auto payloadHeader = read_payload_header(model);
+
+ if (payloadHeader.type == COMPILED_BLOB_PAYLOAD &&
+ payloadHeader.size <= MAX_IN_MEMORY_COMPILED_PAYLOAD_SIZE) {
+ OPENVINO_ASSERT(payloadHeader.size <=
+ static_cast<std::uint64_t>(std::numeric_limits<std::string::size_type>::max()),
+ "HETERO compiled blob compiled submodel payload size is too large: ",
+ payloadHeader.size);
+ std::string payload(static_cast<std::string::size_type>(payloadHeader.size), '\0');
+ ov::hetero::read_payload_bytes(model, payload.data(), payloadHeader.size, "compiled submodel payload");
+ std::istringstream payloadStream(payload);
+ compiled_model = core->import_model(payloadStream, device, loadConfig);
+ } else if (payloadHeader.type == IR_PAYLOAD) {
+ read_ir_payload(model, core, device, loadConfig, ov_model, compiled_model, payloadHeader.size);
+ } else if (payloadHeader.type == COMPILED_BLOB_PAYLOAD) {
+ BoundedStreamBuffer buffer{model, payloadHeader.size};
+ std::istream payloadStream{&buffer};
+ compiled_model = core->import_model(payloadStream, device, loadConfig);
+ buffer.consume_remaining_payload();
+ } else {
+ OPENVINO_THROW("Unsupported HETERO compiled submodel payload type: ", payloadHeader.type);
}
-
- ov_model = plugin->get_core()->read_model(xmlString, weights);
- compiled_model = plugin->get_core()->compile_model(ov_model, device, loadConfig);
+ } else if (core->device_supports_model_caching(device)) {
+ compiled_model = core->import_model(model, device, loadConfig);
+ } else {
+ read_ir_payload(model,
+ core,
+ device,
+ loadConfig,
+ ov_model,
+ compiled_model,
+ std::numeric_limits<std::uint64_t>::max());
}
m_compiled_submodels.emplace_back(ov::hetero::CompiledModel::CompiledModelDesc{
@@ -389,6 +525,7 @@ void ov::hetero::CompiledModel::export_model(std::ostream& model_stream) const {
pugi::xml_document doc;
auto heteroNode = doc.append_child("hetero");
heteroNode.append_attribute("name").set_value(m_name.c_str());
+ heteroNode.append_attribute(HETERO_BLOB_FORMAT_VERSION_ATTR).set_value(HETERO_BLOB_FORMAT_VERSION);
auto inputs_map_node = heteroNode.append_child("inputs_to_submodels_inputs");
for (const auto& it : m_mapping_info._inputs_to_submodels_inputs) {
@@ -429,35 +566,62 @@ void ov::hetero::CompiledModel::export_model(std::ostream& model_stream) const {
doc.reset();
model_stream << std::endl;
+ const bool seekable_output = is_output_stream_seekable(model_stream);
+
for (const auto& comp_model_desc : m_compiled_submodels) {
OPENVINO_ASSERT(comp_model_desc.compiled_model);
if (get_plugin()->get_core()->device_supports_model_caching(comp_model_desc.device)) {
+ if (seekable_output) {
+ const auto payloadFrame = start_framed_payload(model_stream, COMPILED_BLOB_PAYLOAD);
+ FramedPayloadOutputBuffer payloadBuffer(model_stream);
+ std::ostream payloadStream(&payloadBuffer);
+ try {
+ // Batch plugin reports property of low level plugin
+ // If we use Batch plugin inside hetero, we won't be able to call export
+ // Auto batch plugin will throw NOT_IMPLEMENTED
+ comp_model_desc.compiled_model->export_model(payloadStream);
+ OPENVINO_ASSERT(payloadStream, "Failed to export HETERO compiled blob compiled submodel payload");
+ finish_framed_payload(model_stream, payloadFrame, payloadBuffer.written_size());
+ continue;
+ } catch (ov::NotImplemented&) {
+ OPENVINO_ASSERT(
+ payloadBuffer.written_size() == 0,
+ "Cannot fall back to IR serialization after partially writing a compiled submodel blob");
+ model_stream.clear();
+ model_stream.seekp(payloadFrame.frame_start_pos);
+ OPENVINO_ASSERT(model_stream,
+ "Failed to rewind HETERO compiled blob output stream for IR fallback");
+ }
+
+ const auto irPayloadFrame = start_framed_payload(model_stream, IR_PAYLOAD);
+ write_ir_payload(model_stream, comp_model_desc.model);
+ finish_framed_payload(model_stream, irPayloadFrame);
+ continue;
+ }
+
try {
- // Batch plugin reports property of low level plugin
- // If we use Batch plugin inside hetero, we won't be able to call export
- // Auto batch plugin will throw NOT_IMPLEMENTED
- comp_model_desc.compiled_model->export_model(model_stream);
+ write_framed_payload_via_seekable_stream(
+ model_stream,
+ COMPILED_BLOB_PAYLOAD,
+ [&](std::ostream& payloadStream) {
+ comp_model_desc.compiled_model->export_model(payloadStream);
+ },
+ "compiled submodel payload");
continue;
} catch (ov::NotImplemented&) {
}
- }
- auto& model = comp_model_desc.model;
- if (!model)
- OPENVINO_THROW("OpenVINO Model is empty");
-
- std::stringstream xmlFile, binFile;
- ov::pass::Serialize serializer(xmlFile, binFile);
- serializer.run_on_model(model);
- auto constants = binFile.str();
- auto model_str = xmlFile.str();
+ write_ir_framed_payload(model_stream, comp_model_desc.model);
+ continue;
+ }
- auto dataSize = static_cast<std::uint64_t>(model_str.size());
- model_stream.write(reinterpret_cast<char*>(&dataSize), sizeof(dataSize));
- model_stream.write(model_str.c_str(), dataSize);
+ if (seekable_output) {
+ const auto payloadFrame = start_framed_payload(model_stream, IR_PAYLOAD);
+ write_ir_payload(model_stream, comp_model_desc.model);
+ finish_framed_payload(model_stream, payloadFrame);
+ continue;
+ }
- dataSize = static_cast<std::uint64_t>(constants.size());
- model_stream.write(reinterpret_cast<char*>(&dataSize), sizeof(dataSize));
- model_stream.write(reinterpret_cast<char*>(&constants[0]), dataSize);
+ write_ir_framed_payload(model_stream, comp_model_desc.model);
}
}
diff --git a/src/plugins/hetero/tests/functional/CMakeLists.txt b/src/plugins/hetero/tests/functional/CMakeLists.txt
index cd46b459aa8..15cf56c1e45 100644
--- a/src/plugins/hetero/tests/functional/CMakeLists.txt
+++ b/src/plugins/hetero/tests/functional/CMakeLists.txt
@@ -23,6 +23,10 @@ ov_add_test_target(
OV HETERO
)
+target_sources(${TARGET_NAME} PRIVATE
+ $<TARGET_PROPERTY:openvino_hetero_plugin,SOURCE_DIR>/src/blob_serialization.cpp
+)
+
if(ENABLE_INTEL_CPU)
add_dependencies(${TARGET_NAME} openvino_intel_cpu_plugin)
endif()
diff --git a/src/plugins/hetero/tests/functional/hetero_tests.cpp b/src/plugins/hetero/tests/functional/hetero_tests.cpp
index 602c3466876..262af682a98 100644
--- a/src/plugins/hetero/tests/functional/hetero_tests.cpp
+++ b/src/plugins/hetero/tests/functional/hetero_tests.cpp
@@ -664,7 +664,7 @@ public:
} else if (name == ov::internal::exclusive_async_requests) {
return decltype(ov::internal::exclusive_async_requests)::value_type{exclusive_async_requests};
} else if (name == ov::device::uuid) {
- ov::device::UUID uuid;
+ ov::device::UUID uuid{};
for (size_t i = 0; i < uuid.MAX_UUID_SIZE; i++) {
if (device_id == device_ids[0])
uuid.uuid[i] = static_cast<uint8_t>(i);
@@ -747,7 +747,7 @@ public:
return decltype(ov::internal::supported_properties)::value_type(
{ov::PropertyName{ov::internal::caching_properties.name(), ov::PropertyMutability::RO}});
} else if (name == ov::device::uuid) {
- ov::device::UUID uuid;
+ ov::device::UUID uuid{};
for (size_t i = 0; i < uuid.MAX_UUID_SIZE; i++) {
if (device_id == device_ids[0])
uuid.uuid[i] = static_cast<uint8_t>(i * 2);
@@ -775,6 +775,91 @@ public:
}
};
+class MockPluginNoExportImport : public MockPluginBase {
+public:
+ MockPluginNoExportImport(const std::string& name)
+ : MockPluginBase(name, {"Parameter", "Result", "Add", "Constant", "Reshape"}, true) {}
+
+ const ov::Version& get_const_version() override {
+ static const ov::Version version = {CI_BUILD_NUMBER, "openvino_mock_no_export_import_plugin"};
+ return version;
+ }
+
+ void set_property(const ov::AnyMap& properties) override {
+ for (const auto& it : properties) {
+ if (it.first == ov::num_streams.name())
+ num_streams = it.second.as<int32_t>();
+ else if (it.first == ov::enable_profiling.name())
+ m_profiling = it.second.as<bool>();
+ else if (it.first == ov::internal::exclusive_async_requests.name())
+ exclusive_async_requests = it.second.as<bool>();
+ else if (it.first == ov::device::id.name())
+ continue;
+ else
+ OPENVINO_THROW(get_device_name(), " set config: " + it.first);
+ }
+ }
+
+ ov::Any get_property(const std::string& name, const ov::AnyMap& arguments) const override {
+ const static std::vector<std::string> device_ids = {"0"};
+ const static std::vector<ov::PropertyName> roProperties{
+ RO_property(ov::supported_properties.name()),
+ RO_property(ov::available_devices.name()),
+ RO_property(ov::loaded_from_cache.name()),
+ RO_property(ov::device::capabilities.name()),
+ RO_property(ov::device::uuid.name()),
+ };
+ const static std::vector<ov::PropertyName> rwProperties{
+ RW_property(ov::num_streams.name()),
+ RW_property(ov::enable_profiling.name()),
+ };
+
+ std::string device_id;
+ if (arguments.find(ov::device::id.name()) != arguments.end()) {
+ device_id = arguments.find(ov::device::id.name())->second.as<std::string>();
+ }
+ if (name == ov::supported_properties) {
+ std::vector<ov::PropertyName> supportedProperties;
+ supportedProperties.reserve(roProperties.size() + rwProperties.size());
+ supportedProperties.insert(supportedProperties.end(), roProperties.begin(), roProperties.end());
+ supportedProperties.insert(supportedProperties.end(), rwProperties.begin(), rwProperties.end());
+
+ return decltype(ov::supported_properties)::value_type(supportedProperties);
+ } else if (name == ov::internal::supported_properties) {
+ return decltype(ov::internal::supported_properties)::value_type(
+ {ov::PropertyName{ov::internal::caching_properties.name(), ov::PropertyMutability::RO},
+ ov::PropertyName{ov::internal::exclusive_async_requests.name(), ov::PropertyMutability::RW}});
+ } else if (name == ov::internal::exclusive_async_requests) {
+ return decltype(ov::internal::exclusive_async_requests)::value_type{exclusive_async_requests};
+ } else if (name == ov::device::uuid) {
+ ov::device::UUID uuid{};
+ for (size_t i = 0; i < uuid.MAX_UUID_SIZE; i++) {
+ if (device_id == device_ids[0])
+ uuid.uuid[i] = static_cast<uint8_t>(i * 7);
+ }
+ return decltype(ov::device::uuid)::value_type{uuid};
+ } else if (name == ov::available_devices) {
+ return decltype(ov::available_devices)::value_type(device_ids);
+ } else if (name == ov::device::capabilities) {
+ return decltype(ov::device::capabilities)::value_type{};
+ } else if (ov::internal::caching_properties == name) {
+ std::vector<ov::PropertyName> caching_properties = {ov::device::uuid};
+ return decltype(ov::internal::caching_properties)::value_type(caching_properties);
+ } else if (name == ov::loaded_from_cache.name()) {
+ return m_loaded_from_cache;
+ } else if (name == ov::enable_profiling.name()) {
+ return decltype(ov::enable_profiling)::value_type{m_profiling};
+ } else if (name == ov::streams::num.name()) {
+ return decltype(ov::streams::num)::value_type{num_streams};
+ }
+ OPENVINO_THROW("Unsupported property: ", name);
+ }
+
+private:
+ int32_t num_streams{0};
+ bool exclusive_async_requests = false;
+};
+
class MockPluginGPU : public MockPluginBase {
public:
MockPluginGPU(const std::string& name)
@@ -834,7 +919,7 @@ public:
} else if (name == ov::internal::exclusive_async_requests) {
return decltype(ov::internal::exclusive_async_requests)::value_type{exclusive_async_requests};
} else if (name == ov::device::uuid) {
- ov::device::UUID uuid;
+ ov::device::UUID uuid{};
for (size_t i = 0; i < uuid.MAX_UUID_SIZE; i++) {
if (device_id == device_ids[0])
uuid.uuid[i] = static_cast<uint8_t>(i);
@@ -911,6 +996,7 @@ void ov::hetero::tests::HeteroTests::SetUp() {
reg_plugin_type<MockPluginReshape>("MOCK0");
reg_plugin_type<MockPluginSubtract>("MOCK1");
reg_plugin_type<MockPluginGPU>("MOCKGPU");
+ reg_plugin_type<MockPluginNoExportImport>("MOCKIR");
}
}
diff --git a/src/plugins/hetero/tests/functional/import_model_tests.cpp b/src/plugins/hetero/tests/functional/import_model_tests.cpp
index ef9ca294504..66ab53ec275 100644
--- a/src/plugins/hetero/tests/functional/import_model_tests.cpp
+++ b/src/plugins/hetero/tests/functional/import_model_tests.cpp
@@ -2,6 +2,14 @@
// SPDX-License-Identifier: Apache-2.0
//
+#include <cctype>
+#include <cstdlib>
+#include <limits>
+#include <sstream>
+#include <stdexcept>
+#include <string>
+
+#include "blob_serialization.hpp"
#include "common_test_utils/test_constants.hpp"
#include "hetero_tests.hpp"
@@ -9,6 +17,275 @@ namespace ov {
namespace hetero {
namespace tests {
+namespace {
+
+struct TestPayloadHeader {
+ char type = 0;
+ std::uint64_t size = 0;
+};
+
+class ScopedEnvVarOverride {
+public:
+ ScopedEnvVarOverride(const char* name, const std::string& value) : m_name(name) {
+ const char* current_value = std::getenv(m_name.c_str());
+ if (current_value != nullptr) {
+ m_has_old_value = true;
+ m_old_value = current_value;
+ }
+ set(value);
+ }
+
+ ~ScopedEnvVarOverride() {
+ if (m_has_old_value) {
+ set(m_old_value);
+ return;
+ }
+ unset();
+ }
+
+private:
+ void set(const std::string& value) {
+#if defined(_WIN32)
+ _putenv_s(m_name.c_str(), value.c_str());
+#else
+ setenv(m_name.c_str(), value.c_str(), 1);
+#endif
+ }
+
+ void unset() {
+#if defined(_WIN32)
+ _putenv_s(m_name.c_str(), "");
+#else
+ unsetenv(m_name.c_str());
+#endif
+ }
+
+ std::string m_name;
+ std::string m_old_value;
+ bool m_has_old_value = false;
+};
+
+class NonSeekableOutputBuffer : public std::streambuf {
+public:
+ const std::string& str() const {
+ return _data;
+ }
+
+protected:
+ std::streamsize xsputn(const char* data, std::streamsize count) override {
+ if (count <= 0) {
+ return 0;
+ }
+ _data.append(data, static_cast<std::string::size_type>(count));
+ return count;
+ }
+
+ int_type overflow(int_type ch) override {
+ if (traits_type::eq_int_type(ch, traits_type::eof())) {
+ return traits_type::not_eof(ch);
+ }
+ _data.push_back(traits_type::to_char_type(ch));
+ return ch;
+ }
+
+ pos_type seekoff(off_type, std::ios_base::seekdir, std::ios_base::openmode) override {
+ return pos_type(off_type(-1));
+ }
+
+ pos_type seekpos(pos_type, std::ios_base::openmode) override {
+ return pos_type(off_type(-1));
+ }
+
+private:
+ std::string _data;
+};
+
+class SeekCountingOutputBuffer : public std::streambuf {
+public:
+ const std::string& str() const {
+ return _data;
+ }
+
+ std::size_t seek_count() const {
+ return _seek_count;
+ }
+
+ void reset_seek_count() {
+ _seek_count = 0;
+ }
+
+protected:
+ std::streamsize xsputn(const char* data, std::streamsize count) override {
+ if (count <= 0) {
+ return 0;
+ }
+
+ const auto offset = static_cast<std::string::size_type>(_pos);
+ const auto size = static_cast<std::string::size_type>(count);
+ if (offset + size > _data.size()) {
+ _data.resize(offset + size);
+ }
+ for (std::string::size_type i = 0; i < size; ++i) {
+ _data[offset + i] = data[i];
+ }
+ _pos += count;
+ return count;
+ }
+
+ int_type overflow(int_type ch) override {
+ if (traits_type::eq_int_type(ch, traits_type::eof())) {
+ return traits_type::not_eof(ch);
+ }
+
+ const char c = traits_type::to_char_type(ch);
+ return xsputn(&c, 1) == 1 ? ch : traits_type::eof();
+ }
+
+ pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) override {
+ if ((which & std::ios_base::out) == 0) {
+ return pos_type(off_type(-1));
+ }
+
+ ++_seek_count;
+
+ off_type base = 0;
+ if (dir == std::ios_base::cur) {
+ base = _pos;
+ } else if (dir == std::ios_base::end) {
+ base = static_cast<off_type>(_data.size());
+ } else if (dir != std::ios_base::beg) {
+ return pos_type(off_type(-1));
+ }
+
+ const auto new_pos = base + off;
+ if (new_pos < 0) {
+ return pos_type(off_type(-1));
+ }
+ _pos = new_pos;
+ return pos_type(_pos);
+ }
+
+ pos_type seekpos(pos_type pos, std::ios_base::openmode which) override {
+ return seekoff(static_cast<off_type>(pos), std::ios_base::beg, which);
+ }
+
+private:
+ std::string _data;
+ off_type _pos = 0;
+ std::size_t _seek_count = 0;
+};
+
+std::string export_compiled_model(ov::CompiledModel compiled_model) {
+ std::stringstream model_stream;
+ compiled_model.export_model(model_stream);
+ return model_stream.str();
+}
+
+TestPayloadHeader read_test_payload_header(std::istream& model_stream) {
+ TestPayloadHeader payload_header;
+ model_stream.read(&payload_header.type, sizeof(payload_header.type));
+ model_stream.read(reinterpret_cast<char*>(&payload_header.size), sizeof(payload_header.size));
+ if (!model_stream) {
+ throw std::runtime_error("Failed to read HETERO test payload header");
+ }
+ return payload_header;
+}
+
+void append_test_size(std::string& blob, std::uint64_t size) {
+ blob.append(reinterpret_cast<const char*>(&size), sizeof(size));
+}
+
+std::string make_framed_ir_blob(const std::string& hetero_xml_header, const std::string& payload) {
+ auto blob = hetero_xml_header;
+ blob.push_back(IR_PAYLOAD);
+ append_test_size(blob, payload.size());
+ blob += payload;
+ return blob;
+}
+
+std::string remove_blob_format_version(std::string header) {
+ const auto key_pos = header.find(HETERO_BLOB_FORMAT_VERSION_ATTR);
+ if (key_pos == std::string::npos) {
+ throw std::runtime_error("Failed to find HETERO blob format version attribute");
+ }
+
+ auto erase_begin = key_pos;
+ if (erase_begin > 0 && std::isspace(static_cast<unsigned char>(header[erase_begin - 1]))) {
+ --erase_begin;
+ }
+
+ const auto eq_pos = header.find('=', key_pos + std::char_traits<char>::length(HETERO_BLOB_FORMAT_VERSION_ATTR));
+ if (eq_pos == std::string::npos) {
+ throw std::runtime_error("Failed to parse HETERO blob format version attribute");
+ }
+
+ const auto value_begin = header.find_first_not_of(" \t", eq_pos + 1);
+ if (value_begin == std::string::npos || (header[value_begin] != '"' && header[value_begin] != '\'')) {
+ throw std::runtime_error("Failed to parse HETERO blob format version attribute value");
+ }
+
+ const auto quote = header[value_begin];
+ const auto value_end = header.find(quote, value_begin + 1);
+ if (value_end == std::string::npos) {
+ throw std::runtime_error("Failed to parse HETERO blob format version attribute value");
+ }
+
+ header.erase(erase_begin, value_end - erase_begin + 1);
+ return header;
+}
+
+std::string get_hetero_xml_header(const std::string& blob) {
+ const auto header_end = blob.find('\n');
+ if (header_end == std::string::npos) {
+ throw std::runtime_error("Failed to find HETERO blob XML header");
+ }
+ return blob.substr(0, header_end + 1);
+}
+
+std::string make_legacy_unframed_blob_from_framed_blob(const std::string& framed_blob, char expected_payload_type) {
+ auto legacy_blob = remove_blob_format_version(get_hetero_xml_header(framed_blob));
+
+ std::stringstream framed_stream(framed_blob);
+ std::string hetero_xml_header;
+ std::getline(framed_stream, hetero_xml_header);
+
+ const auto payload_header = read_test_payload_header(framed_stream);
+ if (payload_header.type != expected_payload_type) {
+ throw std::runtime_error("Unexpected HETERO test payload type");
+ }
+ if (payload_header.size > static_cast<std::uint64_t>(std::numeric_limits<std::streamsize>::max())) {
+ throw std::runtime_error("HETERO test payload is too large");
+ }
+
+ std::string legacy_payload(static_cast<std::string::size_type>(payload_header.size), '\0');
+ if (!legacy_payload.empty()) {
+ framed_stream.read(&legacy_payload[0], static_cast<std::streamsize>(payload_header.size));
+ if (!framed_stream) {
+ throw std::runtime_error("Failed to read HETERO test payload");
+ }
+ }
+
+ legacy_blob += legacy_payload;
+ return legacy_blob;
+}
+
+void expect_compiled_model_runs(HeteroTests& fixture, ov::CompiledModel compiled_model) {
+ ASSERT_EQ(1, compiled_model.inputs().size());
+ ASSERT_EQ(1, compiled_model.outputs().size());
+
+ auto infer_request = compiled_model.create_infer_request();
+ auto input_tensor =
+ fixture.create_and_fill_tensor(compiled_model.input().get_element_type(), compiled_model.input().get_shape());
+ infer_request.set_input_tensor(input_tensor);
+ ASSERT_NO_THROW(infer_request.infer());
+
+ auto output_tensor = infer_request.get_output_tensor();
+ EXPECT_EQ(compiled_model.output().get_shape(), output_tensor.get_shape());
+ EXPECT_EQ(compiled_model.output().get_element_type(), output_tensor.get_element_type());
+}
+
+} // namespace
+
// IR frontend is needed for import
#ifdef IR_FRONTEND_ENABLED
TEST_F(HeteroTests, import_single_plugins) {
@@ -32,6 +309,278 @@ TEST_F(HeteroTests, import_single_plugins) {
EXPECT_EQ(input_tensor.get_element_type(), model->input().get_element_type());
}
+TEST_F(HeteroTests, export_single_plugin_uses_framed_payload) {
+ auto model = create_model_with_reshape();
+ const auto compiled_model =
+ core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0"));
+ auto blob = export_compiled_model(compiled_model);
+ std::stringstream model_stream(blob);
+
+ std::string hetero_xml_header;
+ std::getline(model_stream, hetero_xml_header);
+ EXPECT_NE(hetero_xml_header.find(HETERO_BLOB_FORMAT_VERSION_ATTR), std::string::npos);
+
+ const auto payload_header = read_test_payload_header(model_stream);
+ EXPECT_TRUE(payload_header.type == COMPILED_BLOB_PAYLOAD || payload_header.type == IR_PAYLOAD);
+ EXPECT_GT(payload_header.size, 0);
+
+ std::stringstream import_stream(blob);
+ auto imported_model = core.import_model(import_stream, ov::test::utils::DEVICE_HETERO, {});
+ EXPECT_EQ(1, imported_model.inputs().size());
+ EXPECT_EQ(1, imported_model.outputs().size());
+}
+
+TEST_F(HeteroTests, export_single_plugin_without_export_import_uses_framed_ir_payload) {
+ auto model = create_model_with_reshape();
+ EXPECT_NO_THROW(core.get_available_devices());
+ auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCKIR"));
+ auto blob = export_compiled_model(compiled_model);
+ std::stringstream model_stream(blob);
+
+ std::string hetero_xml_header;
+ std::getline(model_stream, hetero_xml_header);
+ EXPECT_NE(hetero_xml_header.find(HETERO_BLOB_FORMAT_VERSION_ATTR), std::string::npos);
+
+ const auto payload_header = read_test_payload_header(model_stream);
+ EXPECT_EQ(IR_PAYLOAD, payload_header.type);
+ EXPECT_GT(payload_header.size, 0);
+
+ std::stringstream import_stream(blob);
+ auto imported_model = core.import_model(import_stream, ov::test::utils::DEVICE_HETERO, {});
+ expect_compiled_model_runs(*this, imported_model);
+}
+
+TEST_F(HeteroTests, export_single_plugin_to_non_seekable_stream) {
+ auto model = create_model_with_reshape();
+ auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0"));
+
+ NonSeekableOutputBuffer output_buffer;
+ std::ostream model_stream(&output_buffer);
+ compiled_model.export_model(model_stream);
+ EXPECT_TRUE(model_stream);
+
+ std::stringstream import_stream(output_buffer.str());
+ auto imported_model = core.import_model(import_stream, ov::test::utils::DEVICE_HETERO, {});
+ EXPECT_EQ(1, imported_model.inputs().size());
+ EXPECT_EQ(1, imported_model.outputs().size());
+}
+
+TEST_F(HeteroTests, export_ir_payload_to_non_seekable_stream) {
+ auto model = create_model_with_reshape();
+ EXPECT_NO_THROW(core.get_available_devices());
+ auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCKIR"));
+
+ NonSeekableOutputBuffer output_buffer;
+ std::ostream model_stream(&output_buffer);
+ compiled_model.export_model(model_stream);
+ EXPECT_TRUE(model_stream);
+
+ std::stringstream model_blob(output_buffer.str());
+ std::string hetero_xml_header;
+ std::getline(model_blob, hetero_xml_header);
+ EXPECT_NE(hetero_xml_header.find(HETERO_BLOB_FORMAT_VERSION_ATTR), std::string::npos);
+ const auto payload_header = read_test_payload_header(model_blob);
+ EXPECT_EQ(IR_PAYLOAD, payload_header.type);
+ EXPECT_GT(payload_header.size, 0);
+
+ std::stringstream import_stream(output_buffer.str());
+ auto imported_model = core.import_model(import_stream, ov::test::utils::DEVICE_HETERO, {});
+ expect_compiled_model_runs(*this, imported_model);
+}
+
+TEST_F(HeteroTests, export_ir_payload_does_not_depend_on_temp_directory_environment) {
+ auto model = create_model_with_reshape();
+ EXPECT_NO_THROW(core.get_available_devices());
+ auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCKIR"));
+
+ const std::string invalid_temp_dir = "__ov_hetero_export_ir_payload_tmpdir_must_not_be_used__/missing/subdir";
+ ScopedEnvVarOverride tmpdir("TMPDIR", invalid_temp_dir);
+ ScopedEnvVarOverride tmp("TMP", invalid_temp_dir);
+ ScopedEnvVarOverride temp("TEMP", invalid_temp_dir);
+ ScopedEnvVarOverride tempdir("TEMPDIR", invalid_temp_dir);
+
+ std::stringstream model_stream;
+ EXPECT_NO_THROW(compiled_model.export_model(model_stream));
+
+ auto blob = model_stream.str();
+ std::stringstream payload_stream(blob);
+ std::string hetero_xml_header;
+ std::getline(payload_stream, hetero_xml_header);
+ EXPECT_NE(hetero_xml_header.find(HETERO_BLOB_FORMAT_VERSION_ATTR), std::string::npos);
+ const auto payload_header = read_test_payload_header(payload_stream);
+ EXPECT_EQ(IR_PAYLOAD, payload_header.type);
+ EXPECT_GT(payload_header.size, 0);
+
+ std::stringstream import_stream(blob);
+ auto imported_model = core.import_model(import_stream, ov::test::utils::DEVICE_HETERO, {});
+ expect_compiled_model_runs(*this, imported_model);
+}
+
+TEST_F(HeteroTests, framed_payload_output_buffer_rejects_forward_seek_beyond_written_data) {
+ std::stringstream model_stream;
+ const auto payload_frame = start_framed_payload(model_stream, COMPILED_BLOB_PAYLOAD);
+
+ FramedPayloadOutputBuffer payload_buffer(model_stream);
+ std::ostream payload_stream(&payload_buffer);
+
+ payload_stream.write("abc", 3);
+ ASSERT_TRUE(payload_stream);
+
+ payload_stream.seekp(10, std::ios::beg);
+ EXPECT_TRUE(payload_stream.fail());
+
+ payload_stream.clear();
+ payload_stream.seekp(0, std::ios::end);
+ ASSERT_TRUE(payload_stream);
+ payload_stream.write("d", 1);
+ ASSERT_TRUE(payload_stream);
+
+ finish_framed_payload(model_stream, payload_frame, payload_buffer.written_size());
+
+ std::stringstream verify_stream(model_stream.str());
+ const auto payload_header = read_test_payload_header(verify_stream);
+ ASSERT_EQ(COMPILED_BLOB_PAYLOAD, payload_header.type);
+ ASSERT_EQ(4, payload_header.size);
+
+ std::string payload(static_cast<std::string::size_type>(payload_header.size), '\0');
+ verify_stream.read(payload.data(), static_cast<std::streamsize>(payload_header.size));
+ ASSERT_TRUE(verify_stream);
+ EXPECT_EQ("abcd", payload);
+}
+
+TEST_F(HeteroTests, framed_payload_output_buffer_avoids_seeks_for_sequential_writes) {
+ SeekCountingOutputBuffer output_buffer;
+ std::ostream model_stream(&output_buffer);
+
+ FramedPayloadOutputBuffer payload_buffer(model_stream);
+ std::ostream payload_stream(&payload_buffer);
+
+ output_buffer.reset_seek_count();
+ payload_stream.write("abc", 3);
+ payload_stream.write("def", 3);
+ ASSERT_TRUE(payload_stream);
+
+ EXPECT_EQ(0U, output_buffer.seek_count());
+ EXPECT_EQ(6, payload_buffer.written_size());
+ EXPECT_EQ("abcdef", output_buffer.str());
+}
+
+TEST_F(HeteroTests, bounded_string_output_buffer_rejects_payload_larger_than_limit) {
+ BoundedStringOutputBuffer payload_buffer(3);
+ std::ostream payload_stream(&payload_buffer);
+
+ payload_stream.write("abc", 3);
+ ASSERT_TRUE(payload_stream);
+
+ payload_stream.write("d", 1);
+ EXPECT_FALSE(payload_stream);
+ EXPECT_EQ("abc", payload_buffer.str());
+}
+
+TEST_F(HeteroTests, import_large_compiled_payload_uses_bounded_stream_and_throws) {
+ auto model = create_model_with_reshape();
+ const auto compiled_model =
+ core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0"));
+ const auto hetero_xml_header = get_hetero_xml_header(export_compiled_model(compiled_model));
+
+ std::string blob = hetero_xml_header;
+ blob.push_back(COMPILED_BLOB_PAYLOAD);
+ append_test_size(blob, MAX_IN_MEMORY_COMPILED_PAYLOAD_SIZE + 1);
+
+ std::stringstream model_stream(blob);
+ EXPECT_THROW(core.import_model(model_stream, ov::test::utils::DEVICE_HETERO, {}), ov::Exception);
+}
+
+TEST_F(HeteroTests, import_single_plugin_legacy_unframed_blob_without_format_version) {
+ auto model = create_model_with_reshape();
+ const auto hetero_compiled_model =
+ core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0"));
+ const auto framed_blob = export_compiled_model(hetero_compiled_model);
+ auto legacy_blob = remove_blob_format_version(get_hetero_xml_header(framed_blob));
+
+ std::stringstream framed_stream(framed_blob);
+ std::string hetero_xml_header;
+ std::getline(framed_stream, hetero_xml_header);
+
+ const auto payload_header = read_test_payload_header(framed_stream);
+ ASSERT_GT(payload_header.size, 0);
+ ASSERT_LE(payload_header.size, static_cast<std::uint64_t>(std::numeric_limits<std::streamsize>::max()));
+
+ std::string legacy_payload(static_cast<std::string::size_type>(payload_header.size), '\0');
+ framed_stream.read(legacy_payload.data(), static_cast<std::streamsize>(payload_header.size));
+ ASSERT_TRUE(framed_stream);
+ legacy_blob += legacy_payload;
+
+ std::stringstream model_stream(legacy_blob);
+ auto imported_model = core.import_model(model_stream, ov::test::utils::DEVICE_HETERO, {});
+ EXPECT_EQ(1, imported_model.inputs().size());
+ EXPECT_EQ(1, imported_model.outputs().size());
+}
+
+TEST_F(HeteroTests, import_single_plugin_legacy_unframed_ir_blob_without_format_version) {
+ auto model = create_model_with_reshape();
+ EXPECT_NO_THROW(core.get_available_devices());
+ const auto hetero_compiled_model =
+ core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCKIR"));
+ const auto framed_blob = export_compiled_model(hetero_compiled_model);
+ const auto legacy_blob = make_legacy_unframed_blob_from_framed_blob(framed_blob, IR_PAYLOAD);
+
+ std::stringstream model_stream(legacy_blob);
+ auto imported_model = core.import_model(model_stream, ov::test::utils::DEVICE_HETERO, {});
+ expect_compiled_model_runs(*this, imported_model);
+}
+
+TEST_F(HeteroTests, import_truncated_framed_payload_throws) {
+ auto model = create_model_with_reshape();
+ const auto compiled_model =
+ core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0"));
+ auto blob = export_compiled_model(compiled_model);
+ ASSERT_FALSE(blob.empty());
+ blob.pop_back();
+
+ std::stringstream model_stream(blob);
+ EXPECT_THROW(core.import_model(model_stream, ov::test::utils::DEVICE_HETERO, {}), ov::Exception);
+}
+
+TEST_F(HeteroTests, import_truncated_framed_cpu_payload_throws) {
+ auto model = create_model_with_reshape();
+ const auto compiled_model =
+ core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities(ov::test::utils::DEVICE_CPU));
+ auto blob = export_compiled_model(compiled_model);
+ ASSERT_FALSE(blob.empty());
+ blob.pop_back();
+
+ std::stringstream model_stream(blob);
+ EXPECT_THROW(core.import_model(model_stream, ov::test::utils::DEVICE_HETERO, {}), ov::Exception);
+}
+
+TEST_F(HeteroTests, import_framed_ir_payload_with_oversized_xml_size_throws) {
+ auto model = create_model_with_reshape();
+ const auto compiled_model =
+ core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0"));
+ const auto hetero_xml_header = get_hetero_xml_header(export_compiled_model(compiled_model));
+
+ std::string payload;
+ append_test_size(payload, std::numeric_limits<std::uint64_t>::max());
+ std::stringstream model_stream(make_framed_ir_blob(hetero_xml_header, payload));
+
+ EXPECT_THROW(core.import_model(model_stream, ov::test::utils::DEVICE_HETERO, {}), ov::Exception);
+}
+
+TEST_F(HeteroTests, import_framed_ir_payload_with_oversized_weights_size_throws) {
+ auto model = create_model_with_reshape();
+ const auto compiled_model =
+ core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0"));
+ const auto hetero_xml_header = get_hetero_xml_header(export_compiled_model(compiled_model));
+
+ std::string payload;
+ append_test_size(payload, 0);
+ append_test_size(payload, std::numeric_limits<std::uint64_t>::max());
+ std::stringstream model_stream(make_framed_ir_blob(hetero_xml_header, payload));
+
+ EXPECT_THROW(core.import_model(model_stream, ov::test::utils::DEVICE_HETERO, {}), ov::Exception);
+}
+
TEST_F(HeteroTests, import_several_plugins) {
std::stringstream model_stream;
auto model = create_model_with_subtract();