Skip to content

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

[CPU] Add HSM support for import/export model (#39251)

Pawel Raasz5dd49adcb014
diff --git a/src/inference/src/dev/hsm_reader.cpp b/src/inference/src/dev/hsm_reader.cpp
index e7e4d09f463..a4867518712 100644
--- a/src/inference/src/dev/hsm_reader.cpp
+++ b/src/inference/src/dev/hsm_reader.cpp
@@ -79,6 +79,11 @@ bool read_manifest(std::istream& stream,
}
}
+constexpr bool is_valid_offset(std::streamoff start, uint64_t container_size) noexcept {
+ constexpr auto max_offset = static_cast<uint64_t>(std::numeric_limits<std::streamoff>::max());
+ return container_size <= max_offset - static_cast<uint64_t>(start);
+}
+
bool has_container_size_bytes(std::istream& stream, std::streampos start, const Header& header) {
stream.seekg(start + static_cast<std::streamoff>(header.container_size - 1));
return stream.peek() != std::istream::traits_type::eof();
@@ -100,8 +105,9 @@ std::optional<Reader> Reader::open(std::istream& stream) {
std::vector<ManifestEntry> manifest;
if (start == std::streampos(-1) || !stream.read(reinterpret_cast<char*>(&header), sizeof(header)) ||
- !is_valid_header_fields(header) || !read_manifest(stream, start, header, manifest) ||
- !has_container_size_bytes(stream, start, header) ||
+ !is_valid_header_fields(header) ||
+ !is_valid_offset(static_cast<std::streamoff>(start), header.container_size) ||
+ !read_manifest(stream, start, header, manifest) || !has_container_size_bytes(stream, start, header) ||
!std::all_of(manifest.begin(), manifest.end(), [&header](const ManifestEntry& entry) {
return is_valid_section_bounds(entry, header) && section_size_fits_size_t(entry);
})) {
diff --git a/src/inference/tests/unit/hsm_reader.cpp b/src/inference/tests/unit/hsm_reader.cpp
index 836f044e8a4..b0a2a048ff5 100644
--- a/src/inference/tests/unit/hsm_reader.cpp
+++ b/src/inference/tests/unit/hsm_reader.cpp
@@ -1087,6 +1087,16 @@ TEST(HsmReaderStreamTest, rejects_container_size_exceeding_available_stream_byte
EXPECT_FALSE(hsm::Reader::open(stream).has_value());
}
+TEST(HsmReaderStreamTest, rejects_container_size_that_overflows_stream_offsets) {
+ auto blob = make_sample_reader_container();
+ auto header = hsm::Header::view(blob.data());
+ header.container_size = std::numeric_limits<uint64_t>::max();
+ std::memcpy(blob.data(), &header, sizeof(header));
+
+ auto stream = make_stream(blob, /*prefix_size=*/2);
+ EXPECT_FALSE(hsm::Reader::open(stream).has_value());
+}
+
TEST(HsmReaderStreamTest, rejects_invalid_section_offset) {
auto blob = make_sample_reader_container();
const auto header = hsm::Header::view(blob.data());
diff --git a/src/plugins/intel_cpu/sources.cmake b/src/plugins/intel_cpu/sources.cmake
index e98593e5eae..694546e27db 100644
--- a/src/plugins/intel_cpu/sources.cmake
+++ b/src/plugins/intel_cpu/sources.cmake
@@ -675,6 +675,11 @@ set(CPU_PLUGIN_SRCS
${CPU_SRC_DIR}/utils/general_utils.h
${CPU_SRC_DIR}/utils/graph_serializer/deserializer.cpp
${CPU_SRC_DIR}/utils/graph_serializer/deserializer.hpp
+ ${CPU_SRC_DIR}/utils/graph_serializer/hsm_common.hpp
+ ${CPU_SRC_DIR}/utils/graph_serializer/hsm_reader_handler.cpp
+ ${CPU_SRC_DIR}/utils/graph_serializer/hsm_reader_handler.hpp
+ ${CPU_SRC_DIR}/utils/graph_serializer/hsm_writer_handler.cpp
+ ${CPU_SRC_DIR}/utils/graph_serializer/hsm_writer_handler.hpp
${CPU_SRC_DIR}/utils/graph_serializer/serializer.cpp
${CPU_SRC_DIR}/utils/graph_serializer/serializer.hpp
${CPU_SRC_DIR}/utils/memory_stats_dump.hpp
diff --git a/src/plugins/intel_cpu/src/compiled_model.cpp b/src/plugins/intel_cpu/src/compiled_model.cpp
index a739a4ba420..19289b60a6f 100644
--- a/src/plugins/intel_cpu/src/compiled_model.cpp
+++ b/src/plugins/intel_cpu/src/compiled_model.cpp
@@ -25,6 +25,7 @@
#include "openvino/core/any.hpp"
#include "openvino/core/except.hpp"
#include "openvino/core/model.hpp"
+#include "openvino/runtime/hsm_deferred_writer.hpp"
#include "openvino/runtime/iasync_infer_request.hpp"
#include "openvino/runtime/icompiled_model.hpp"
#include "openvino/runtime/intel_cpu/properties.hpp"
@@ -38,6 +39,7 @@
#include "sub_memory_manager.hpp"
#include "utils/debug_capabilities.h"
#include "utils/general_utils.h"
+#include "utils/graph_serializer/hsm_writer_handler.hpp"
#include "utils/graph_serializer/serializer.hpp"
#ifdef CPU_DEBUG_CAPS
# include "utils/memory_stats_dump.hpp"
@@ -430,9 +432,19 @@ static void write_header(std::ostream& modelStream, const std::string& runtime_r
}
void CompiledModel::export_model(std::ostream& modelStream) const {
- write_header(modelStream, m_runtime_requirements);
- ModelSerializer serializer(modelStream, m_cfg.cacheEncrypt, m_cfg.m_cache_mode == ov::CacheMode::OPTIMIZE_SIZE);
- serializer << m_model;
+ const bool weightless_mode = m_cfg.m_cache_mode == ov::CacheMode::OPTIMIZE_SIZE;
+ if (m_cfg.exportHsmFormat) {
+ HsmWriterHandler handler{m_model, m_runtime_requirements, m_cfg.cacheEncrypt, weightless_mode};
+ auto writer = ov::runtime::hsm::DeferredWriter::open(modelStream);
+ OPENVINO_ASSERT(writer, "[CPU] Cannot export in HSM format: the output stream must be seekable.");
+ writer->add_sections({&handler});
+ const auto error = writer->finalize();
+ OPENVINO_ASSERT(!error, "[CPU] HSM export failed: ", error.message());
+ } else {
+ write_header(modelStream, m_runtime_requirements);
+ ModelSerializer serializer(modelStream, m_cfg.cacheEncrypt, weightless_mode);
+ serializer << m_model;
+ }
}
void CompiledModel::release_memory() {
diff --git a/src/plugins/intel_cpu/src/config.cpp b/src/plugins/intel_cpu/src/config.cpp
index 3972258cf3f..2ea0d7448d1 100644
--- a/src/plugins/intel_cpu/src/config.cpp
+++ b/src/plugins/intel_cpu/src/config.cpp
@@ -495,6 +495,16 @@ void Config::readProperties(const ov::AnyMap& prop, const ModelType modelType) {
} catch (ov::Exception&) {
OPENVINO_THROW("Wrong value for property key ", ov::intel_cpu::enable_sage_attn.name());
}
+ } else if (key == ov::intel_cpu::export_hsm_format.name()) {
+ try {
+ exportHsmFormat = val.as<bool>();
+ } catch (ov::Exception&) {
+ OPENVINO_THROW("Wrong value ",
+ val.as<std::string>(),
+ " for property key ",
+ ov::intel_cpu::export_hsm_format.name(),
+ ". Expected only true/false.");
+ }
} else if (key == ov::enable_weightless.name()) {
try {
enableWeightless = val.as<bool>();
diff --git a/src/plugins/intel_cpu/src/config.h b/src/plugins/intel_cpu/src/config.h
index 27c37a68ce6..19888f6da39 100644
--- a/src/plugins/intel_cpu/src/config.h
+++ b/src/plugins/intel_cpu/src/config.h
@@ -150,6 +150,7 @@ struct Config {
ov::CacheMode m_cache_mode = ov::CacheMode::OPTIMIZE_SPEED;
bool enableWeightless = false;
+ bool exportHsmFormat = false;
#ifdef CPU_DEBUG_CAPS
DebugCapsConfig debugCaps;
diff --git a/src/plugins/intel_cpu/src/internal_properties.hpp b/src/plugins/intel_cpu/src/internal_properties.hpp
index d5cf994ccc6..2c2cee8458d 100644
--- a/src/plugins/intel_cpu/src/internal_properties.hpp
+++ b/src/plugins/intel_cpu/src/internal_properties.hpp
@@ -80,4 +80,11 @@ static constexpr Property<bool, PropertyMutability::RW> enable_tensor_parallel{"
*/
static constexpr Property<bool, PropertyMutability::RW> enable_sage_attn{"ENABLE_SAGE_ATTN"};
+/**
+ * @brief Selects the export_model() blob format: true = HSM container, false = legacy layout (default).
+ * @note Transition switch; removed together with the legacy format. Set it on the plugin (not only per compile call)
+ * so that Core caching picks up the matching blob format.
+ */
+static constexpr Property<bool, PropertyMutability::RW> export_hsm_format{"CPU_EXPORT_HSM_FORMAT"};
+
} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/plugin.cpp b/src/plugins/intel_cpu/src/plugin.cpp
index 02d0149d537..946b8d66d5c 100644
--- a/src/plugins/intel_cpu/src/plugin.cpp
+++ b/src/plugins/intel_cpu/src/plugin.cpp
@@ -45,6 +45,7 @@
#include "openvino/op/scaled_dot_product_attention.hpp"
#include "openvino/runtime/aligned_buffer.hpp"
#include "openvino/runtime/common.hpp"
+#include "openvino/runtime/hsm_reader.hpp"
#include "openvino/runtime/icompiled_model.hpp"
#include "openvino/runtime/intel_cpu/properties.hpp"
#include "openvino/runtime/internal_properties.hpp"
@@ -64,6 +65,7 @@
#include "utils/debug_capabilities.h"
#include "utils/denormals.hpp"
#include "utils/graph_serializer/deserializer.hpp"
+#include "utils/graph_serializer/hsm_reader_handler.hpp"
#include "utils/graph_serializer/serializer.hpp"
#include "utils/precision_support.h"
#include "weights_cache.hpp"
@@ -556,6 +558,10 @@ ov::Any Plugin::get_property(const std::string& name, const ov::AnyMap& options)
return decltype(ov::enable_weightless)::value_type{engConfig.enableWeightless};
}
+ if (name == ov::internal::emit_hsm_format) {
+ return engConfig.exportHsmFormat;
+ }
+
return get_ro_property(name, options);
}
@@ -629,6 +635,7 @@ ov::Any Plugin::get_ro_property(const std::string& name, [[maybe_unused]] const
ov::PropertyName{ov::internal::caching_with_mmap.name(), ov::PropertyMutability::RO},
#endif
ov::PropertyName{ov::internal::exclusive_async_requests.name(), ov::PropertyMutability::RW},
+ ov::PropertyName{ov::internal::emit_hsm_format.name(), ov::PropertyMutability::RO},
ov::PropertyName{ov::internal::compiled_model_runtime_properties.name(), ov::PropertyMutability::RO},
ov::PropertyName{ov::internal::compiled_model_runtime_properties_supported.name(),
ov::PropertyMutability::RO}};
@@ -840,6 +847,14 @@ static void read_header(std::istream& model_stream) {
model_stream.seekg(-remaining_unread_bytes, std::ios_base::cur);
}
+static HsmModelDeserializer::Sections read_hsm_sections(const ov::runtime::hsm::Reader& reader,
+ std::shared_ptr<ov::AlignedBuffer> source_blob) {
+ HsmReaderHandler handler{std::move(source_blob)};
+ HsmReaderHandler::check_manifest(reader);
+ handler.read_sections(reader);
+ return {std::move(handler.model_struct), std::move(handler.weights)};
+}
+
std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& model_stream, const ov::AnyMap& config) const {
OV_ITT_SCOPE(FIRST_INFERENCE, itt::domains::ov_intel_cpu_LT, "import_model");
@@ -847,6 +862,20 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& model_str
auto decrypt_from_string = get_cache_decrypt_fn(config, decrypt);
const auto origin_weights_path = get_origin_weights_path(config);
+ const auto blob_start = model_stream.tellg();
+ if (auto reader = ov::runtime::hsm::Reader::open(model_stream)) {
+ HsmModelDeserializer deserializer(read_hsm_sections(*reader, nullptr),
+ get_core(),
+ decrypt,
+ decrypt_from_string,
+ origin_weights_path);
+ return deserialize_model(deserializer, config);
+ }
+
+ // Not an HSM container: rewind and read the legacy layout.
+ model_stream.clear();
+ model_stream.seekg(blob_start);
+
read_header(model_stream);
ModelDeserializer deserializer(model_stream, get_core(), decrypt, decrypt_from_string, origin_weights_path);
@@ -863,25 +892,32 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(const ov::Tensor& model
const auto origin_weights_path = get_origin_weights_path(config);
size_t total_bytes = model_tensor.get_byte_size();
- size_t offset = 0;
// `const_cast` intentionally used as AlignedBuffer requires non-const pointer
// but is used as read-only in deserializer
auto* base_ptr = reinterpret_cast<char*>(const_cast<void*>(model_tensor.data()));
- validate_runtime_requirements(base_ptr, total_bytes, offset);
+ if (auto reader = ov::runtime::hsm::Reader::open(reinterpret_cast<const std::byte*>(base_ptr), total_bytes)) {
+ auto source_blob = std::make_shared<ov::SharedBuffer<ov::Tensor>>(base_ptr, total_bytes, model_tensor);
+ HsmModelDeserializer deserializer(read_hsm_sections(*reader, std::move(source_blob)),
+ get_core(),
+ decrypt,
+ decrypt_from_string,
+ origin_weights_path);
+ return deserialize_model(deserializer, config);
+ }
- auto* model_data_ptr = base_ptr + offset;
- size_t remaining_bytes = total_bytes - offset;
+ size_t offset = 0;
+ validate_runtime_requirements(base_ptr, total_bytes, offset);
std::shared_ptr<ov::AlignedBuffer> model_buffer =
- std::make_shared<ov::SharedBuffer<ov::Tensor>>(model_data_ptr, remaining_bytes, model_tensor);
+ std::make_shared<ov::SharedBuffer<ov::Tensor>>(base_ptr + offset, total_bytes - offset, model_tensor);
ModelDeserializer deserializer(model_buffer, get_core(), decrypt, decrypt_from_string, origin_weights_path);
return deserialize_model(deserializer, config);
}
-std::shared_ptr<ov::ICompiledModel> Plugin::deserialize_model(ModelDeserializer& deserializer,
+std::shared_ptr<ov::ICompiledModel> Plugin::deserialize_model(ModelDeserializerBase& deserializer,
const ov::AnyMap& config) const {
std::shared_ptr<ov::Model> model;
deserializer >> model;
diff --git a/src/plugins/intel_cpu/src/plugin.h b/src/plugins/intel_cpu/src/plugin.h
index a0cb611c235..a2be36098e7 100644
--- a/src/plugins/intel_cpu/src/plugin.h
+++ b/src/plugins/intel_cpu/src/plugin.h
@@ -65,7 +65,7 @@ public:
std::shared_ptr<ov::threading::MessageManager> m_msg_manager;
private:
- std::shared_ptr<ov::ICompiledModel> deserialize_model(ModelDeserializer& deserializer,
+ std::shared_ptr<ov::ICompiledModel> deserialize_model(ModelDeserializerBase& deserializer,
const ov::AnyMap& config) const;
ov::Any get_ro_property(const std::string& name, const ov::AnyMap& options) const;
diff --git a/src/plugins/intel_cpu/src/utils/graph_serializer/deserializer.cpp b/src/plugins/intel_cpu/src/utils/graph_serializer/deserializer.cpp
index 7be70db6315..10b0ccdefc1 100644
--- a/src/plugins/intel_cpu/src/utils/graph_serializer/deserializer.cpp
+++ b/src/plugins/intel_cpu/src/utils/graph_serializer/deserializer.cpp
@@ -43,13 +43,11 @@
namespace ov::intel_cpu {
-ModelDeserializer::ModelDeserializer(std::shared_ptr<ov::AlignedBuffer>& model_buffer,
- const std::shared_ptr<ov::ICore>& core,
- const CacheDecrypt& decrypt_fn,
- bool decript_from_string,
- const std::string& origin_weights_path)
- : m_model(model_buffer),
- m_core(core),
+ModelDeserializerBase::ModelDeserializerBase(const std::shared_ptr<ov::ICore>& core,
+ const CacheDecrypt& decrypt_fn,
+ bool decript_from_string,
+ const std::string& origin_weights_path)
+ : m_core(core),
m_decript_from_string(decript_from_string) {
if (!origin_weights_path.empty() && std::filesystem::exists(origin_weights_path)) {
auto mmap = ov::load_mmap_object(ov::util::make_path(origin_weights_path));
@@ -64,26 +62,29 @@ ModelDeserializer::ModelDeserializer(std::shared_ptr<ov::AlignedBuffer>& model_b
}
}
+ModelDeserializer::ModelDeserializer(std::shared_ptr<ov::AlignedBuffer>& model_buffer,
+ const std::shared_ptr<ov::ICore>& core,
+ const CacheDecrypt& decrypt_fn,
+ bool decript_from_string,
+ const std::string& origin_weights_path)
+ : ModelDeserializerBase(core, decrypt_fn, decript_from_string, origin_weights_path),
+ m_model(model_buffer) {}
+
ModelDeserializer::ModelDeserializer(std::istream& model_stream,
const std::shared_ptr<ov::ICore>& core,
const CacheDecrypt& decrypt_fn,
bool decript_from_string,
const std::string& origin_weights_path)
- : m_model(model_stream),
- m_core(core),
- m_decript_from_string(decript_from_string) {
- if (!origin_weights_path.empty() && std::filesystem::exists(origin_weights_path)) {
- auto mmap = ov::load_mmap_object(ov::util::make_path(origin_weights_path));
- m_origin_weights_buf =
- std::make_shared<ov::SharedBuffer<std::shared_ptr<MappedMemory>>>(mmap->data(), mmap->size(), mmap);
- }
+ : ModelDeserializerBase(core, decrypt_fn, decript_from_string, origin_weights_path),
+ m_model(model_stream) {}
- if (m_decript_from_string) {
- m_cache_decrypt.m_decrypt_str = decrypt_fn.m_decrypt_str;
- } else {
- m_cache_decrypt.m_decrypt_char = decrypt_fn.m_decrypt_char;
- }
-}
+HsmModelDeserializer::HsmModelDeserializer(Sections sections,
+ const std::shared_ptr<ov::ICore>& core,
+ const CacheDecrypt& decrypt_fn,
+ bool decript_from_string,
+ const std::string& origin_weights_path)
+ : ModelDeserializerBase(core, decrypt_fn, decript_from_string, origin_weights_path),
+ m_sections(std::move(sections)) {}
void ModelDeserializer::set_info(pugi::xml_node& root, std::shared_ptr<ov::Model>& model) {}
@@ -95,7 +96,7 @@ void ModelDeserializer::operator>>(std::shared_ptr<ov::Model>& model) {
m_model);
}
-std::shared_ptr<ov::Model> ModelDeserializer::create_ov_model(
+std::shared_ptr<ov::Model> ModelDeserializerBase::create_ov_model(
const std::shared_ptr<ov::AlignedBuffer>& model_buf,
const std::shared_ptr<ov::AlignedBuffer>& weights,
const std::shared_ptr<ov::AlignedBuffer>& origin_weights) {
@@ -274,6 +275,23 @@ void ModelDeserializer::process_model(std::shared_ptr<ov::Model>& model,
set_info(root, model);
};
+void HsmModelDeserializer::operator>>(std::shared_ptr<ov::Model>& model) {
+ auto xml = m_sections.xml;
+ if (m_cache_decrypt) {
+ auto xml_string = std::make_shared<std::string>(xml->get_ptr<char>(), xml->size());
+ if (m_decript_from_string) {
+ *xml_string = m_cache_decrypt.m_decrypt_str(*xml_string);
+ } else {
+ m_cache_decrypt.m_decrypt_char(xml_string->data(), xml_string->data(), xml_string->size());
+ }
+ xml = std::make_shared<ov::SharedBuffer<std::shared_ptr<std::string>>>(xml_string->data(),
+ xml_string->size(),
+ xml_string);
+ }
+
+ model = create_ov_model(xml, m_sections.weights, m_origin_weights_buf);
+}
+
ov::Any XmlDeserializer::parse_weightless_cache_attribute(const pugi::xml_node& node) const {
if (auto rt_info = node.child("rt_info")) {
for (const auto& child : rt_info.children()) {
diff --git a/src/plugins/intel_cpu/src/utils/graph_serializer/deserializer.hpp b/src/plugins/intel_cpu/src/utils/graph_serializer/deserializer.hpp
index 0612bd18d46..1a5af0bbfc5 100644
--- a/src/plugins/intel_cpu/src/utils/graph_serializer/deserializer.hpp
+++ b/src/plugins/intel_cpu/src/utils/graph_serializer/deserializer.hpp
@@ -87,7 +87,31 @@ private:
std::shared_ptr<ov::AlignedBuffer> m_origin_weights;
};
-class ModelDeserializer {
+/// @brief Common base class for model deserializers, handling weightless-cache support and cache decryption setup.
+class ModelDeserializerBase {
+public:
+ virtual ~ModelDeserializerBase() = default;
+
+ virtual void operator>>(std::shared_ptr<ov::Model>& model) = 0;
+
+protected:
+ ModelDeserializerBase(const std::shared_ptr<ov::ICore>& core,
+ const CacheDecrypt& decrypt_fn,
+ bool decript_from_string,
+ const std::string& origin_weights_path);
+
+ std::shared_ptr<ov::Model> create_ov_model(const std::shared_ptr<ov::AlignedBuffer>& model,
+ const std::shared_ptr<ov::AlignedBuffer>& weights,
+ const std::shared_ptr<ov::AlignedBuffer>& origin_weights);
+
+ std::shared_ptr<ov::ICore> m_core;
+ CacheDecrypt m_cache_decrypt;
+ bool m_decript_from_string;
+ std::shared_ptr<ov::AlignedBuffer> m_origin_weights_buf;
+};
+
+/// Legacy blob: one stream with DataHeader, custom data, constants and the IR XML.
+class ModelDeserializer : public ModelDeserializerBase {
public:
ModelDeserializer(std::shared_ptr<ov::AlignedBuffer>& model_buffer,
const std::shared_ptr<ov::ICore>& core,
@@ -101,9 +125,7 @@ public:
bool decript_from_string,
const std::string& origin_weights_path = "");
- virtual ~ModelDeserializer() = default;
-
- void operator>>(std::shared_ptr<ov::Model>& model);
+ void operator>>(std::shared_ptr<ov::Model>& model) override;
protected:
static void set_info(pugi::xml_node& root, std::shared_ptr<ov::Model>& model);
@@ -112,15 +134,27 @@ protected:
void process_model(std::shared_ptr<ov::Model>& model, std::reference_wrapper<std::istream> model_stream);
- std::shared_ptr<ov::Model> create_ov_model(const std::shared_ptr<ov::AlignedBuffer>& model,
- const std::shared_ptr<ov::AlignedBuffer>& weights,
- const std::shared_ptr<ov::AlignedBuffer>& origin_weights);
-
std::variant<std::shared_ptr<ov::AlignedBuffer>, std::reference_wrapper<std::istream>> m_model;
- std::shared_ptr<ov::ICore> m_core;
- CacheDecrypt m_cache_decrypt;
- bool m_decript_from_string;
- std::shared_ptr<ov::AlignedBuffer> m_origin_weights_buf;
+};
+
+/// HSM blob: Deserializer sections into xml and weights.
+class HsmModelDeserializer final : public ModelDeserializerBase {
+public:
+ struct Sections {
+ std::shared_ptr<ov::AlignedBuffer> xml; //!< Encrypted when cache encryption is on.
+ std::shared_ptr<ov::AlignedBuffer> weights; //!< Null when the blob stores no constants.
+ };
+
+ HsmModelDeserializer(Sections sections,
+ const std::shared_ptr<ov::ICore>& core,
+ const CacheDecrypt& decrypt_fn,
+ bool decript_from_string,
+ const std::string& origin_weights_path = "");
+
+ void operator>>(std::shared_ptr<ov::Model>& model) override;
+
+private:
+ Sections m_sections;
};
} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_common.hpp b/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_common.hpp
new file mode 100644
index 00000000000..3ba2e51036d
--- /dev/null
+++ b/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_common.hpp
@@ -0,0 +1,58 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Wire contract of the CPU HSM blob, shared by HsmReaderHandler and HsmWriterHandler. Keep it free of reader and
+// writer code - the two handlers must stay independent. `hsm` is this plugin's own namespace; the runtime API is
+// spelled runtime::hsm.
+//
+// Layout of the container, in file order (the legacy stream was [DataHeader][Custom data][Blobs][IR] behind a
+// requirements prefix; the manifest now replaces the DataHeader, and the custom data is no longer written):
+//
+// [ HSM header ] 32 bytes
+// [ runtime_requirements ] common section, checked first so an incompatible blob is rejected before any payload
+// [ padding ]
+// [ weights ] page-aligned offset and slot size; may be empty (no constants, or weightless cache)
+// [ model_struct ] page-aligned offset and slot size; IR XML, encrypted when cache encryption is on
+// [ manifest ] one entry per section, starts on a page boundary
+//
+// The XML refers to constants by offset from the start of the weights section.
+
+#pragma once
+
+#include <cstdint>
+
+#include "openvino/runtime/hsm_format.hpp"
+
+namespace ov::intel_cpu::hsm {
+
+inline constexpr runtime::hsm::DeviceId device_id = runtime::hsm::cpu_device_id;
+
+struct SectionId {
+ runtime::hsm::DeviceId device{};
+ runtime::hsm::SectionTag tag{};
+};
+
+constexpr uint32_t section_key(runtime::hsm::DeviceId device, runtime::hsm::SectionTag tag) noexcept {
+ return (static_cast<uint32_t>(device) << 24) | (static_cast<uint32_t>(tag.value[0]) << 16) |
+ (static_cast<uint32_t>(tag.value[1]) << 8) | static_cast<uint32_t>(tag.value[2]);
+}
+
+constexpr uint32_t section_key(const SectionId& id) noexcept {
+ return section_key(id.device, id.tag);
+}
+
+/// Core-owned: the string checked by is_runtime_requirements_compatible() on import.
+// CVS-196454: use the common Runtime Requirements codec instead of the plain string.
+inline constexpr SectionId runtime_requirements{runtime::hsm::any_device_id, runtime::hsm::runtime_requirements_tag};
+/// Core-owned, inline.
+// The id algorithm is not defined yet, the writer stores a placeholder and the reader does not use it.
+inline constexpr SectionId model_id{runtime::hsm::any_device_id, runtime::hsm::model_id_tag};
+/// The compiled model's IR XML (encrypted when cache encryption is on), without constants.
+// CVS-196450: replace with the common Model Struct section once its payload is defined.
+// CVS-196452: add the common Compiled Options section; CPU keeps its options in the model rt_info until then.
+inline constexpr SectionId model_struct{device_id, runtime::hsm::model_tag};
+// CVS-196451: replace with the common Weights section once its payload is defined.
+inline constexpr SectionId weights{device_id, runtime::hsm::weights_tag};
+
+} // namespace ov::intel_cpu::hsm
diff --git a/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_reader_handler.cpp b/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_reader_handler.cpp
new file mode 100644
index 00000000000..60d54a702e2
--- /dev/null
+++ b/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_reader_handler.cpp
@@ -0,0 +1,124 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "utils/graph_serializer/hsm_reader_handler.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <map>
+#include <memory>
+#include <string>
+#include <unordered_set>
+#include <utility>
+
+#include "openvino/core/except.hpp"
+#include "openvino/runtime/aligned_buffer.hpp"
+#include "openvino/runtime/hsm_format.hpp"
+#include "openvino/runtime/hsm_model_id_codec.hpp"
+#include "openvino/runtime/hsm_reader.hpp"
+#include "openvino/runtime/shared_buffer.hpp"
+#include "utils/graph_serializer/hsm_common.hpp"
+#include "utils/graph_serializer/serializer.hpp"
+
+namespace ov::intel_cpu {
+
+namespace {
+
+std::string read_string(const runtime::hsm::Section& section) {
+ std::string value(section.size(), '\0');
+ OPENVINO_ASSERT(section.read(value.data()), "[CPU] Cannot import compiled blob: failed to read a section.");
+ return value;
+}
+
+// Maps the section from the source blob when the bytes are addressable and kept alive by it, otherwise copies.
+std::shared_ptr<ov::AlignedBuffer> read_buffer(const std::shared_ptr<ov::AlignedBuffer>& source_blob,
+ const runtime::hsm::Section& section) {
+ if (section.size() == 0) {
+ return nullptr;
+ }
+ if (const auto view = section.view(); source_blob && !view.empty()) {
+ return std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>(
+ const_cast<std::byte*>(view.data()),
+ view.size(),
+ source_blob);
+ }
+ auto buffer = std::make_shared<ov::AlignedBuffer>(section.size());
+ OPENVINO_ASSERT(section.read(buffer->get_ptr()), "[CPU] Cannot import compiled blob: failed to read a section.");
+ return buffer;
+}
+
+// Rejected before the payload sections that follow are read.
+std::string read_compatible_requirements(const runtime::hsm::Section& section) {
+ // CVS-196454: decode with the common Runtime Requirements codec.
+ OPENVINO_ASSERT(section.size() <= runtime_requirements_max_size,
+ "[CPU] Cannot import compiled blob: runtime requirements block is too large.");
+ auto requirements = read_string(section);
+ OPENVINO_ASSERT(is_runtime_requirements_compatible(requirements),
+ "[CPU] Cannot import compiled blob: incompatible runtime requirements, blob: ",
+ requirements,
+ ", current: ",
+ build_runtime_requirements());
+ return requirements;
+}
+
+constexpr uint32_t requirements_key = hsm::section_key(hsm::runtime_requirements);
+constexpr uint32_t model_struct_key = hsm::section_key(hsm::model_struct);
+
+} // namespace
+
+const std::map<uint32_t, HsmReaderHandler::Decoder> HsmReaderHandler::s_decoders = {
+ {hsm::section_key(hsm::model_id),
+ [](HsmReaderHandler& handler, const runtime::hsm::Section& section) {
+ handler.model_id = runtime::hsm::decode_model_id(section);
+ }},
+ {model_struct_key,
+ [](HsmReaderHandler& handler, const runtime::hsm::Section& section) {
+ handler.model_struct = read_buffer(handler.m_source_blob, section);
+ }},
+ {hsm::section_key(hsm::weights),
+ [](HsmReaderHandler& handler, const runtime::hsm::Section& section) {
+ // TODO: a mapped blob can prefetch these pages here so that reading a cold file overlaps the rest of the
+ // import.
+ handler.weights = read_buffer(handler.m_source_blob, section);
+ }},
+};
+
+HsmReaderHandler::HsmReaderHandler(std::shared_ptr<ov::AlignedBuffer> source_blob)
+ : m_source_blob(std::move(source_blob)) {}
+
+bool HsmReaderHandler::handle_section(const runtime::hsm::ManifestEntry& entry, const runtime::hsm::Section& section) {
+ if (const auto decoder = s_decoders.find(hsm::section_key(entry.device, entry.tag)); decoder != s_decoders.end()) {
+ decoder->second(*this, section);
+ return true;
+ }
+ return false;
+}
+
+void HsmReaderHandler::read_sections(const runtime::hsm::Reader& reader) {
+ // Not left to the manifest order: an incompatible blob is rejected before any payload is read.
+ const auto requirements = reader.section(hsm::runtime_requirements.device, hsm::runtime_requirements.tag.id());
+ OPENVINO_ASSERT(requirements, "[CPU] Cannot import compiled blob: missing runtime requirements section.");
+ runtime_requirements = read_compatible_requirements(*requirements);
+ reader.read_sections({this});
+ OPENVINO_ASSERT(model_struct, "[CPU] Cannot import compiled blob: empty model section.");
+}
+
+void HsmReaderHandler::check_manifest(const runtime::hsm::Reader& reader) {
+ std::unordered_set<uint32_t> seen;
+ for (const auto& entry : reader.entries()) {
+ const auto key = hsm::section_key(entry.device, entry.tag);
+ if (entry.device == hsm::runtime_requirements.device && entry.tag.id() == hsm::runtime_requirements.tag.id()) {
+ OPENVINO_ASSERT(key == requirements_key,
+ "[CPU] Cannot import compiled blob: unexpected runtime requirements section tag.");
+ }
+ if (key == requirements_key || s_decoders.count(key) != 0) {
+ OPENVINO_ASSERT(seen.insert(key).second, "[CPU] Cannot import compiled blob: duplicated section ", key);
+ }
+ }
+ OPENVINO_ASSERT(seen.count(requirements_key) != 0,
+ "[CPU] Cannot import compiled blob: missing runtime requirements section.");
+ OPENVINO_ASSERT(seen.count(model_struct_key) != 0, "[CPU] Cannot import compiled blob: missing model section.");
+}
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_reader_handler.hpp b/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_reader_handler.hpp
new file mode 100644
index 00000000000..9f86d169c24
--- /dev/null
+++ b/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_reader_handler.hpp
@@ -0,0 +1,44 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstdint>
+#include <map>
+#include <memory>
+#include <optional>
+#include <string>
+
+#include "openvino/runtime/aligned_buffer.hpp"
+#include "openvino/runtime/hsm_reader.hpp"
+
+namespace ov::intel_cpu {
+
+class HsmReaderHandler final : public runtime::hsm::ISectionReaderHandler {
+public:
+ /// @p source_blob keeps the memory behind the sections alive. Pass it when the Reader was opened over a buffer,
+ /// so the sections are mapped from it instead of copied.
+ explicit HsmReaderHandler(std::shared_ptr<ov::AlignedBuffer> source_blob = {});
+
+ bool handle_section(const runtime::hsm::ManifestEntry& entry, const runtime::hsm::Section& section) override;
+
+ /// Validates the manifest of @p reader. Throws if it is not acceptable. Call before read_sections().
+ static void check_manifest(const runtime::hsm::Reader& reader);
+
+ /// Decodes the sections of @p reader into the members below.
+ void read_sections(const runtime::hsm::Reader& reader);
+
+ std::optional<std::string> runtime_requirements;
+ std::optional<uint64_t> model_id; //!< See hsm::model_id;
+ std::shared_ptr<ov::AlignedBuffer> model_struct; //!< See hsm::model_struct.
+ std::shared_ptr<ov::AlignedBuffer> weights; //!< See hsm::weights; null if it is absent or empty.
+
+private:
+ using Decoder = void (*)(HsmReaderHandler&, const runtime::hsm::Section&);
+ static const std::map<uint32_t, Decoder> s_decoders;
+
+ std::shared_ptr<ov::AlignedBuffer> m_source_blob;
+};
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_writer_handler.cpp b/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_writer_handler.cpp
new file mode 100644
index 00000000000..47f777f857f
--- /dev/null
+++ b/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_writer_handler.cpp
@@ -0,0 +1,145 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "utils/graph_serializer/hsm_writer_handler.hpp"
+
+#include <cstddef>
+#include <functional>
+#include <ios>
+#include <memory>
+#include <optional>
+#include <ostream>
+#include <streambuf>
+#include <string>
+#include <utility>
+
+#include "openvino/core/except.hpp"
+#include "openvino/core/model.hpp"
+#include "openvino/runtime/hsm_writer.hpp"
+#include "openvino/util/memory.hpp"
+#include "utils/graph_serializer/hsm_common.hpp"
+#include "utils/graph_serializer/serializer.hpp"
+
+namespace ov::intel_cpu {
+
+namespace {
+// Page-aligned start and slot size: each section covers whole pages
+constexpr runtime::hsm::SectionAlignment section_alignment{ov::util::min_page_alignment, 0};
+
+// Forwards every written chunk to the sink without storing it; tellp() is the only position query it supports.
+class SinkStreamBuf final : public std::streambuf {
+public:
+ explicit SinkStreamBuf(runtime::hsm::SectionSink sink) : m_sink(std::move(sink)) {}
+
+protected:
+ std::streamsize xsputn(const char* s, std::streamsize n) override {
+ m_sink({reinterpret_cast<const std::byte*>(s), static_cast<size_t>(n)});
+ m_pos += n;
+ return n;
+ }
+
+ int_type overflow(int_type ch) override {
+ if (!traits_type::eq_int_type(ch, traits_type::eof())) {
+ const auto c = traits_type::to_char_type(ch);
+ xsputn(&c, 1);
+ }
+ return traits_type::not_eof(ch);
+ }
+
+ pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode /*mode*/) override {
+ return off == 0 && dir == std::ios_base::cur ? pos_type(m_pos) : pos_type(static_cast<off_type>(-1));
+ }
+
+private:
+ runtime::hsm::SectionSink m_sink;
+ off_type m_pos = 0;
+};
+
+// One serialization pass feeds both sections: write_weights() streams the constants out as they are produced and
+// keeps the (small) XML for write_model(), so the encoders must run in that order.
+class HsmModelSerialization {
+public:
+ HsmModelSerialization(std::shared_ptr<ov::Model> model,
+ ModelSerializer::CacheEncrypt encrypt_fn,
+ bool weightless_mode)
+ : m_model(std::move(model)),
+ m_encrypt_fn(std::move(encrypt_fn)),
+ m_weightless_mode(weightless_mode) {}
+
+ void write_weights(const runtime::hsm::SectionSink& sink) {
+ SinkStreamBuf weights_buf{sink};
+ std::ostream weights(&weights_buf);
+ std::string xml_text;
+ SinkStreamBuf xml_buf{[&xml_text](ov::util::MemoryView chunk) {
+ xml_text.append(reinterpret_cast<const char*>(chunk.data()), chunk.size());
+ }};
+ std::ostream xml(&xml_buf);
+ serialize_model(m_model, weights, xml, m_encrypt_fn, m_weightless_mode);
+ OPENVINO_ASSERT(weights.good() && xml.good(), "[CPU] Cannot serialize the model into the HSM blob.");
+ m_xml = std::move(xml_text);
+ }
+
+ void write_model(const runtime::hsm::SectionSink& sink) {
+ OPENVINO_ASSERT(m_xml, "[CPU] The weights section must be encoded before the model section.");
+ sink({reinterpret_cast<const std::byte*>(m_xml->data()), m_xml->size()});
+ m_xml.reset();
+ }
+
+private:
+ std::shared_ptr<ov::Model> m_model;
+ ModelSerializer::CacheEncrypt m_encrypt_fn;
+ bool m_weightless_mode;
+ std::optional<std::string> m_xml;
+};
+
+class FunctionEncoder final : public runtime::hsm::ISectionEncoder {
+public:
+ explicit FunctionEncoder(std::function<void(const runtime::hsm::SectionSink&)> encode)
+ : m_encode(std::move(encode)) {}
+
+ void encode(const runtime::hsm::SectionSink& sink) const override {
+ m_encode(sink);
+ }
+
+private:
+ std::function<void(const runtime::hsm::SectionSink&)> m_encode;
+};
+} // namespace
+
+HsmWriterHandler::HsmWriterHandler(std::shared_ptr<ov::Model> model,
+ std::string runtime_requirements,
+ ModelSerializer::CacheEncrypt encrypt_fn,
+ bool weightless_mode)
+ : m_runtime_requirements(std::move(runtime_requirements)) {
+ const auto serialization =
+ std::make_shared<HsmModelSerialization>(std::move(model), std::move(encrypt_fn), weightless_mode);
+ m_weights_encoder = std::make_shared<FunctionEncoder>([serialization](const runtime::hsm::SectionSink& sink) {
+ serialization->write_weights(sink);
+ });
+ m_model_encoder = std::make_shared<FunctionEncoder>([serialization](const runtime::hsm::SectionSink& sink) {
+ serialization->write_model(sink);
+ });
+}
+
+void HsmWriterHandler::handle_section(runtime::hsm::IWriter& writer) const {
+ const auto add = [&writer](const hsm::SectionId& id, auto&&... args) {
+ OPENVINO_ASSERT(writer.add_section(id.device, id.tag, std::forward<decltype(args)>(args)...),
+ "[CPU] Cannot add HSM section ",
+ id.tag.id());
+ };
+
+ // Requirements come first so that an import can reject an incompatible blob before reading any payload.
+ // CVS-196454: encode with the common Runtime Requirements codec.
+ add(hsm::runtime_requirements,
+ ov::util::MemoryView{reinterpret_cast<const std::byte*>(m_runtime_requirements.data()),
+ m_runtime_requirements.size()});
+ if (m_model_id) {
+ add(hsm::model_id, ov::util::as_memory_view(*m_model_id));
+ }
+ // The weights are encoded before the model, see HsmModelSerialization.
+ add(hsm::weights, m_weights_encoder, section_alignment);
+ add(hsm::model_struct, m_model_encoder, section_alignment);
+}
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_writer_handler.hpp b/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_writer_handler.hpp
new file mode 100644
index 00000000000..7fcde573fa2
--- /dev/null
+++ b/src/plugins/intel_cpu/src/utils/graph_serializer/hsm_writer_handler.hpp
@@ -0,0 +1,35 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstdint>
+#include <memory>
+#include <optional>
+#include <string>
+
+#include "openvino/core/model.hpp"
+#include "openvino/runtime/hsm_writer.hpp"
+#include "utils/graph_serializer/serializer.hpp"
+
+namespace ov::intel_cpu {
+
+class HsmWriterHandler final : public runtime::hsm::ISectionWriterHandler {
+public:
+ HsmWriterHandler(std::shared_ptr<ov::Model> model,
+ std::string runtime_requirements,
+ ModelSerializer::CacheEncrypt encrypt_fn,
+ bool weightless_mode);
+
+ /// The handler must outlive IWriter::finalize(): the model is serialized straight into the writer at that point.
+ void handle_section(runtime::hsm::IWriter& writer) const override;
+
+private:
+ std::string m_runtime_requirements;
+ std::optional<uint64_t> m_model_id;
+ runtime::hsm::SectionEncoderPtr m_weights_encoder;
+ runtime::hsm::SectionEncoderPtr m_model_encoder;
+};
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/utils/graph_serializer/serializer.cpp b/src/plugins/intel_cpu/src/utils/graph_serializer/serializer.cpp
index b7f1945e274..2a49d6a5401 100644
--- a/src/plugins/intel_cpu/src/utils/graph_serializer/serializer.cpp
+++ b/src/plugins/intel_cpu/src/utils/graph_serializer/serializer.cpp
@@ -8,6 +8,7 @@
#include <cstdint>
#include <cstring>
#include <functional>
+#include <ios>
#include <memory>
#include <ostream>
#include <sstream>
@@ -182,6 +183,46 @@ std::unique_ptr<util::XmlSerializer> ModelSerializer::make_serializer(pugi::xml_
m_weightless_mode);
}
+void serialize_model(std::shared_ptr<ov::Model> model,
+ std::ostream& weights,
+ std::ostream& xml,
+ const ModelSerializer::CacheEncrypt& encrypt_fn,
+ bool weightless_mode) {
+ auto version = static_cast<int64_t>(ov::pass::Serialize::Version::UNSPECIFIED);
+ if (const auto& rt_info = model->get_rt_info(); rt_info.count("version") != 0) {
+ version = rt_info.at("version").as<int64_t>();
+ }
+ if (version == static_cast<int64_t>(ov::pass::Serialize::Version::UNSPECIFIED)) {
+ version = static_cast<int64_t>(ov::pass::Serialize::Version::IR_V11);
+ }
+
+ const std::string name = "net";
+ pugi::xml_document xml_doc;
+ auto net_node = xml_doc.append_child(name.c_str());
+ util::ConstantWriter constant_writer(weights);
+ XmlSerializer visitor(net_node,
+ name,
+ constant_writer,
+ version,
+ /*deterministic=*/false,
+ /*compress_to_fp16=*/false,
+ /*output_element_type=*/ov::element::dynamic,
+ /*data_is_temporary=*/false,
+ weightless_mode);
+ visitor.on_attribute(name, model);
+
+ if (encrypt_fn) {
+ std::stringstream plain_xml;
+ xml_doc.save(plain_xml);
+ const auto encrypted_xml = encrypt_fn(plain_xml.str());
+ xml.write(encrypted_xml.data(), static_cast<std::streamsize>(encrypted_xml.size()));
+ } else {
+ xml_doc.save(xml);
+ }
+ weights.flush();
+ xml.flush();
+}
+
std::string build_runtime_requirements() {
std::ostringstream ss;
ss << "meta=1.0"
diff --git a/src/plugins/intel_cpu/src/utils/graph_serializer/serializer.hpp b/src/plugins/intel_cpu/src/utils/graph_serializer/serializer.hpp
index 6ea68a6233f..face8127df8 100644
--- a/src/plugins/intel_cpu/src/utils/graph_serializer/serializer.hpp
+++ b/src/plugins/intel_cpu/src/utils/graph_serializer/serializer.hpp
@@ -36,6 +36,23 @@ private:
bool m_weightless_mode;
};
+/**
+ * @brief Serializes @p model into two streams instead of the single legacy one: the constants go to @p weights as they
+ * are produced, the IR XML (encrypted when @p encrypt_fn is set) to @p xml. Offsets in the XML are relative to the
+ * start of @p weights.
+ *
+ * @param model Model to serialize, left unchanged.
+ * @param weights Receives the constants.
+ * @param xml Receives the IR XML.
+ * @param encrypt_fn Optional encryption of the XML text.
+ * @param weightless_mode Skip the constants that can be read from the original weights file on import.
+ */
+void serialize_model(std::shared_ptr<ov::Model> model,
+ std::ostream& weights,
+ std::ostream& xml,
+ const ModelSerializer::CacheEncrypt& encrypt_fn,
+ bool weightless_mode);
+
static constexpr uint64_t runtime_requirements_magic = 0x4F564350555F5252ULL; // "OVCPU_RR" in ASCII
static constexpr uint32_t runtime_requirements_version = 1;
static constexpr uint64_t runtime_requirements_max_size = 4096;
diff --git a/src/plugins/intel_cpu/tests/functional/custom/behavior/hsm_blob.cpp b/src/plugins/intel_cpu/tests/functional/custom/behavior/hsm_blob.cpp
new file mode 100644
index 00000000000..57b684fd53b
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/behavior/hsm_blob.cpp
@@ -0,0 +1,286 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <algorithm>
+#include <cstring>
+#include <fstream>
+#include <sstream>
+#include <string>
+
+#include "behavior/compiled_model/import_export.hpp"
+#include "common_test_utils/file_utils.hpp"
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "common_test_utils/subgraph_builders/conv_pool_relu.hpp"
+#include "common_test_utils/test_assertions.hpp"
+#include "internal_properties.hpp"
+#include "openvino/core/rt_info/weightless_caching_attributes.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/relu.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/runtime/core.hpp"
+#include "openvino/runtime/hsm_reader.hpp"
+#include "openvino/runtime/properties.hpp"
+#include "openvino/util/memory.hpp"
+#include "shared_test_classes/base/ov_behavior_test_utils.hpp"
+#include "utils/graph_serializer/hsm_common.hpp"
+
+namespace ov::test {
+
+namespace hsm = intel_cpu::hsm;
+using behavior::hsm_repack;
+using behavior::HsmEntry;
+using behavior::is_hsm;
+
+static bool has_section_id(runtime::hsm::DeviceId device, runtime::hsm::SectionTag tag, const hsm::SectionId& id) {
+ return hsm::section_key(device, tag) == hsm::section_key(id);
+}
+
+static bool is_page_aligned(size_t offset) {
+ return util::align_size_up(offset, util::min_page_alignment) == offset;
+}
+
+// TODO: when HSM becomes the default, compile() no longer needs export_hsm_format(true).
+class CpuHsmBlobTest : public ::testing::Test {
+protected:
+ void SetUp() override {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ model = utils::make_conv_pool_relu({1, 3, 16, 16}, element::f32);
+ }
+
+ CompiledModel compile(const std::shared_ptr<Model>& m, AnyMap config = {}) {
+ config.emplace(intel_cpu::export_hsm_format(true));
+ return core.compile_model(m, utils::DEVICE_CPU, config);
+ }
+
+ std::string export_blob(const std::shared_ptr<Model>& m, const AnyMap& config = {}) {
+ std::stringstream stream;
+ compile(m, config).export_model(stream);
+ return stream.str();
+ }
+
+ static Tensor infer(CompiledModel compiled, const Tensor& in) {
+ auto request = compiled.create_infer_request();
+ request.set_input_tensor(in);
+ request.infer();
+ const auto out = request.get_output_tensor();
+ Tensor result(out.get_element_type(), out.get_shape());
+ out.copy_to(result);
+ return result;
+ }
+
+ static size_t weights_section_size(const std::string& blob) {
+ const auto reader = runtime::hsm::Reader::open(reinterpret_cast<const std::byte*>(blob.data()), blob.size());
+ OPENVINO_ASSERT(reader.has_value(), "Not an HSM blob");
+ const auto section = reader->section(hsm::weights.device, hsm::weights.tag.id());
+ return section ? section->size() : 0;
+ }
+
+ std::string export_blob_without(const hsm::SectionId& id) {
+ return hsm_repack(export_blob(model), [&](std::vector<HsmEntry>& entries) {
+ entries.erase(std::remove_if(entries.begin(),
+ entries.end(),
+ [&](const HsmEntry& entry) {
+ return has_section_id(entry.device, entry.tag.tag, id);
+ }),
+ entries.end());
+ });
+ }
+
+ std::string export_blob_with_duplicate(const hsm::SectionId& id) {
+ return hsm_repack(export_blob(model), [&](std::vector<HsmEntry>& entries) {
+ const auto found = std::find_if(entries.begin(), entries.end(), [&](const HsmEntry& entry) {
+ return has_section_id(entry.device, entry.tag.tag, id);
+ });
+ ASSERT_NE(found, entries.end());
+ entries.push_back(*found);
+ });
+ }
+
+ // The writer does not produce a model id yet, so tests add the section themselves.
+ std::string export_blob_with_model_ids(size_t count, runtime::hsm::SectionTag tag = hsm::model_id.tag) {
+ return hsm_repack(export_blob(model), [&](std::vector<HsmEntry>& entries) {
+ const uint64_t id = 0x1234567890ABCDEFull;
+ const auto view = util::as_memory_view(id);
+ for (size_t i = 0; i < count; ++i) {
+ entries.push_back({hsm::model_id.device, {tag, {}}, std::vector<std::byte>(view.begin(), view.end())});
+ }
+ });
+ }
+
+ void expect_import_rejected(const std::string& blob) {
+ std::stringstream stream(blob);
+ EXPECT_THROW((void)core.import_model(stream, utils::DEVICE_CPU), Exception);
+
+ Tensor tensor(element::u8, Shape{blob.size()});
+ std::memcpy(tensor.data(), blob.data(), blob.size());
+ EXPECT_THROW((void)core.import_model(tensor, utils::DEVICE_CPU), Exception);
+ }
+
+ Core core;
+ std::shared_ptr<Model> model;
+};
+
+TEST_F(CpuHsmBlobTest, exported_blob_is_hsm_with_cpu_sections) {
+ const auto blob = export_blob(model);
+ ASSERT_TRUE(is_hsm(blob));
+
+ const auto reader = runtime::hsm::Reader::open(reinterpret_cast<const std::byte*>(blob.data()), blob.size());
+ ASSERT_TRUE(reader.has_value());
+ EXPECT_EQ(reader->count(hsm::runtime_requirements.device, hsm::runtime_requirements.tag.id()), 1u);
+ EXPECT_EQ(reader->count(hsm::model_id.device, hsm::model_id.tag.id()), 0u);
+ EXPECT_EQ(reader->count(hsm::model_struct.device, hsm::model_struct.tag.id()), 1u);
+ EXPECT_EQ(reader->count(hsm::weights.device, hsm::weights.tag.id()), 1u);
+
+ const auto requirements = reader->section(hsm::runtime_requirements.device, hsm::runtime_requirements.tag.id());
+ ASSERT_TRUE(requirements.has_value());
+ const auto bytes = requirements->to_bytes();
+ ASSERT_TRUE(bytes.has_value());
+ EXPECT_EQ(std::string(reinterpret_cast<const char*>(bytes->data()), bytes->size()),
+ compile(model).get_property(runtime_requirements));
+}
+
+TEST_F(CpuHsmBlobTest, weights_and_model_are_separate_page_aligned_sections) {
+ const auto blob = export_blob(model);
+ const auto reader = runtime::hsm::Reader::open(reinterpret_cast<const std::byte*>(blob.data()), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto find_manifest_entry = [&](const hsm::SectionId& id) {
+ const auto found = std::find_if(reader->entries().begin(), reader->entries().end(), [&](const auto& entry) {
+ return has_section_id(entry.device, entry.tag, id);
+ });
+ EXPECT_NE(found, reader->entries().end());
+ return *found;
+ };
+ const auto weights = find_manifest_entry(hsm::weights);
+ const auto model_struct = find_manifest_entry(hsm::model_struct);
+
+ EXPECT_GT(weights.size, 0u);
+ EXPECT_GT(model_struct.size, 0u);
+ EXPECT_TRUE(is_page_aligned(weights.offset));
+ EXPECT_TRUE(is_page_aligned(model_struct.offset));
+ EXPECT_LE(weights.offset + weights.size, model_struct.offset);
+ // The model slot is padded to whole pages, so the manifest after it starts on a page boundary.
+ EXPECT_TRUE(is_page_aligned(runtime::hsm::Header::view(blob.data()).manifest_offset));
+}
+
+TEST_F(CpuHsmBlobTest, model_without_constants_has_an_empty_weights_section_and_round_trips) {
+ auto parameter = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, 8});
+ auto relu = std::make_shared<op::v0::Relu>(parameter);
+ auto no_constants =
+ std::make_shared<Model>(std::make_shared<op::v0::Result>(relu), ParameterVector{parameter}, "no_constants");
+ const auto blob = export_blob(no_constants);
+ EXPECT_EQ(weights_section_size(blob), 0u);
+
+ std::stringstream stream(blob);
+ auto imported = core.import_model(stream, utils::DEVICE_CPU);
+
+ const auto in = utils::create_and_fill_tensor(element::f32, Shape{1, 8});
+ utils::compare(infer(compile(no_constants), in), infer(imported, in));
+}
+
+TEST_F(CpuHsmBlobTest, weightless_constants_are_not_stored_in_the_weights_section) {
+ // The first constant is weightless and restored from a file on import; the second has no attribute, so it is
+ // still exported.
+ const auto weightless_data = utils::create_and_fill_tensor(element::f32, Shape{256, 512});
+ const auto plain_data = utils::create_and_fill_tensor(element::f32, Shape{512, 128});
+ auto weightless_constant = std::make_shared<op::v0::Constant>(weightless_data);
+ weightless_constant->get_rt_info()[WeightlessCacheAttribute::get_type_info_static()] =
+ WeightlessCacheAttribute(weightless_data.get_byte_size(), 0, element::f32);
+ auto parameter = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, 256});
+ auto first = std::make_shared<op::v0::MatMul>(parameter, weightless_constant);
+ auto second = std::make_shared<op::v0::MatMul>(first, std::make_shared<op::v0::Constant>(plain_data));
+ auto weightless_model =
+ std::make_shared<Model>(std::make_shared<op::v0::Result>(second), ParameterVector{parameter}, "weightless");
+ const auto in = utils::create_and_fill_tensor(element::f32, Shape{1, 256});
+ const auto expected = infer(compile(weightless_model), in);
+
+ const auto weights_file = utils::generateTestFilePrefix() + "_weights.bin";
+ std::ofstream(weights_file, std::ios::binary)
+ .write(static_cast<const char*>(weightless_data.data()),
+ static_cast<std::streamsize>(weightless_data.get_byte_size()));
+
+ const AnyMap weightless_config{cache_mode(CacheMode::OPTIMIZE_SIZE)};
+ const auto blob = export_blob(weightless_model, weightless_config);
+ EXPECT_GE(weights_section_size(blob), plain_data.get_byte_size());
+ EXPECT_LT(weights_section_size(blob), weightless_data.get_byte_size());
+
+ std::stringstream stream(blob);
+ auto import_config = weightless_config;
+ import_config.emplace(weights_path(weights_file));
+ utils::compare(expected, infer(core.import_model(stream, utils::DEVICE_CPU, import_config), in));
+ utils::removeFile(weights_file);
+}
+
+TEST_F(CpuHsmBlobTest, import_rejects_blob_without_runtime_requirements) {
+ expect_import_rejected(export_blob_without(hsm::runtime_requirements));
+}
+
+TEST_F(CpuHsmBlobTest, import_rejects_blob_without_model_struct) {
+ expect_import_rejected(export_blob_without(hsm::model_struct));
+}
+
+TEST_F(CpuHsmBlobTest, import_rejects_blob_without_the_weights_of_a_model_with_constants) {
+ expect_import_rejected(export_blob_without(hsm::weights));
+}
+
+TEST_F(CpuHsmBlobTest, import_accepts_blob_with_model_id) {
+ std::stringstream stream(export_blob_with_model_ids(1));
+ EXPECT_NO_THROW(std::ignore = core.import_model(stream, utils::DEVICE_CPU));
+}
+
+TEST_F(CpuHsmBlobTest, import_rejects_duplicated_model_id) {
+ expect_import_rejected(export_blob_with_model_ids(2));
+}
+
+TEST_F(CpuHsmBlobTest, import_ignores_sections_with_unexpected_inline_flag) {
+ // Duplicates would be rejected if they matched the model id section.
+ const auto pointer_mode_id = runtime::hsm::SectionTag::make(hsm::model_id.tag.id(), /*is_inline=*/false);
+ std::stringstream stream(export_blob_with_model_ids(2, pointer_mode_id));
+ EXPECT_NO_THROW(std::ignore = core.import_model(stream, utils::DEVICE_CPU));
+}
+
+TEST_F(CpuHsmBlobTest, import_rejects_requirements_repeated_with_unexpected_inline_flag) {
+ const auto inline_tag = runtime::hsm::SectionTag::make(hsm::runtime_requirements.tag.id(), /*is_inline=*/true);
+ const auto blob = hsm_repack(export_blob(model), [&](std::vector<HsmEntry>& entries) {
+ entries.insert(entries.begin(),
+ {hsm::runtime_requirements.device, {inline_tag, {}}, std::vector<std::byte>(8, std::byte{0})});
+ });
+
+ expect_import_rejected(blob);
+}
+
+TEST_F(CpuHsmBlobTest, import_rejects_blob_with_model_struct_of_unexpected_inline_flag) {
+ const auto blob = hsm_repack(export_blob(model), [](std::vector<HsmEntry>& entries) {
+ for (auto& entry : entries) {
+ if (has_section_id(entry.device, entry.tag.tag, hsm::model_struct)) {
+ entry.tag.tag = runtime::hsm::SectionTag::make(hsm::model_struct.tag.id(), /*is_inline=*/true);
+ entry.payload.resize(24);
+ }
+ }
+ });
+ expect_import_rejected(blob);
+}
+
+TEST_F(CpuHsmBlobTest, import_rejects_duplicated_model_struct) {
+ expect_import_rejected(export_blob_with_duplicate(hsm::model_struct));
+}
+
+TEST_F(CpuHsmBlobTest, import_rejects_duplicated_weights) {
+ expect_import_rejected(export_blob_with_duplicate(hsm::weights));
+}
+
+TEST_F(CpuHsmBlobTest, import_rejects_mismatched_runtime_requirements) {
+ const auto repacked = hsm_repack(export_blob(model), [](std::vector<HsmEntry>& entries) {
+ for (auto& entry : entries) {
+ if (has_section_id(entry.device, entry.tag.tag, hsm::runtime_requirements)) {
+ entry.payload.front() ^= std::byte{0x01};
+ }
+ }
+ });
+ expect_import_rejected(repacked);
+}
+
+} // namespace ov::test
diff --git a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/behavior/compiled_model/import_export.cpp b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/behavior/compiled_model/import_export.cpp
index 776d5784bb5..812f9e9af6c 100644
--- a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/behavior/compiled_model/import_export.cpp
+++ b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/behavior/compiled_model/import_export.cpp
@@ -4,6 +4,7 @@
#include "behavior/compiled_model/import_export.hpp"
#include "common_test_utils/test_constants.hpp"
+#include "internal_properties.hpp"
#include "openvino/core/model_util.hpp"
#include "openvino/op/interpolate.hpp"
#include "openvino/op/is_inf.hpp"
@@ -88,13 +89,23 @@ TEST_P(OVClassCompiledModelImportExportTestP, importExportModelWithTypeRelaxedEx
EXPECT_EQ(elementType, importedCompiledModel.output("result").get_element_type());
}
+// TODO: when HSM becomes the default and the legacy format and export_hsm_format are dropped, remove the second config -
+// the default one then covers HSM.
INSTANTIATE_TEST_SUITE_P(smoke_serialization,
OVCompiledGraphImportExportTest,
::testing::Combine(::testing::ValuesIn(netPrecisions),
::testing::Values(ov::test::utils::DEVICE_CPU),
- ::testing::Values(empty_property)),
+ ::testing::Values(empty_property,
+ ov::AnyMap{ov::intel_cpu::export_hsm_format(true)})),
OVCompiledGraphImportExportTest::getTestCaseName);
+// TODO: when HSM becomes the default and export_hsm_format is dropped, use an empty config here.
+INSTANTIATE_TEST_SUITE_P(smoke_serialization,
+ OVCompiledModelHsmBlobTest,
+ ::testing::Combine(::testing::Values(ov::test::utils::DEVICE_CPU),
+ ::testing::Values(ov::AnyMap{ov::intel_cpu::export_hsm_format(true)})),
+ OVCompiledModelHsmBlobTest::getTestCaseName);
+
TEST_P(OVCompiledModelGraphUniqueNodeNamesTest, CheckUniqueNodeNames) {
std::shared_ptr<ov::Core> core = ov::test::utils::PluginCache::get().core();
auto compiled_model = core->compile_model(model, target_device);
diff --git a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/behavior/compiled_model/model_cache.cpp b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/behavior/compiled_model/model_cache.cpp
index 0b12f3347e6..17adee01eb0 100644
--- a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/behavior/compiled_model/model_cache.cpp
+++ b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/behavior/compiled_model/model_cache.cpp
@@ -4,10 +4,13 @@
#include "behavior/compiled_model/model_cache.hpp"
#include "common_test_utils/test_constants.hpp"
+#include "internal_properties.hpp"
#include "openvino/runtime/properties.hpp"
using namespace ov::test::behavior;
+// when HSM becomes the default and the legacy format and export_hsm_format are dropped, remove the
+// export_hsm_format(true) configs - the default ones then cover HSM.
INSTANTIATE_TEST_SUITE_P(smoke_,
WeightlessCacheAccuracy,
::testing::Combine(::testing::Bool(),
@@ -17,10 +20,16 @@ INSTANTIATE_TEST_SUITE_P(smoke_,
::testing::Values(ov::AnyMap{ov::enable_weightless("ON"),
ov::cache_mode("OPTIMIZE_SPEED")},
ov::AnyMap{ov::cache_mode("OPTIMIZE_SIZE")},
- ov::AnyMap{ov::enable_weightless("OFF")}),
+ ov::AnyMap{ov::enable_weightless("OFF")},
+ ov::AnyMap{ov::enable_weightless("ON"),
+ ov::cache_mode("OPTIMIZE_SPEED"),
+ ov::intel_cpu::export_hsm_format(true)},
+ ov::AnyMap{ov::cache_mode("OPTIMIZE_SIZE"),
+ ov::intel_cpu::export_hsm_format(true)}),
::testing::Values(ov::test::utils::DEVICE_CPU)),
WeightlessCacheAccuracy::get_test_case_name);
+// same as above for the export_hsm_format(true) config.
INSTANTIATE_TEST_SUITE_P(smoke_,
WeightlessCacheAccuracyLowPrecision,
::testing::Combine(::testing::Bool(),
@@ -29,6 +38,8 @@ INSTANTIATE_TEST_SUITE_P(smoke_,
::testing::ValuesIn(low_precision_dtypes),
::testing::Values(ov::AnyMap{ov::enable_weightless("ON"),
ov::cache_mode("OPTIMIZE_SPEED")},
- ov::AnyMap{ov::cache_mode("OPTIMIZE_SIZE")}),
+ ov::AnyMap{ov::cache_mode("OPTIMIZE_SIZE")},
+ ov::AnyMap{ov::cache_mode("OPTIMIZE_SIZE"),
+ ov::intel_cpu::export_hsm_format(true)}),
::testing::Values(ov::test::utils::DEVICE_CPU)),
WeightlessCacheAccuracy::get_test_case_name);
diff --git a/src/plugins/intel_cpu/tests/functional/sources.cmake b/src/plugins/intel_cpu/tests/functional/sources.cmake
index ed25ce98821..63f6a8ba215 100644
--- a/src/plugins/intel_cpu/tests/functional/sources.cmake
+++ b/src/plugins/intel_cpu/tests/functional/sources.cmake
@@ -410,6 +410,7 @@ set(CPU_FUNC_TESTS_X64_SRCS
set(CPU_FUNC_TESTS_SRCS
${CMAKE_CURRENT_LIST_DIR}/custom/behavior/compatibility_string.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/behavior/export_import.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/behavior/hsm_blob.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/behavior/ov_executable_network/concurent_release_memory.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/behavior/ov_executable_network/input_tensor_initialization.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/behavior/ov_executable_network/properties.cpp