Skip to content

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

[IE] Speed up hash calculation on ov::Model (#31924)

Pawel Raaszf352c90aeb08
diff --git a/src/common/transformations/include/transformations/hash.hpp b/src/common/transformations/include/transformations/hash.hpp
index 168e83750ef..7025b586ee6 100644
--- a/src/common/transformations/include/transformations/hash.hpp
+++ b/src/common/transformations/include/transformations/hash.hpp
@@ -27,11 +27,13 @@ public:
*
* @param output_hash_value Reference to output value. By applying hash pass on function, resulting hash value
* will be set to this variable
+ * @param skip_weights If set to true, simplifies the hashing process by excluding weights values.
*/
- Hash(uint64_t& output_hash_value);
+ Hash(uint64_t& output_hash_value, bool skip_weights = false);
private:
uint64_t& m_hash;
+ bool m_skip_weights;
};
} // namespace pass
diff --git a/src/core/src/pass/serialize.cpp b/src/core/src/pass/serialize.cpp
index 3c1ce93f826..4de66749b4f 100644
--- a/src/core/src/pass/serialize.cpp
+++ b/src/core/src/pass/serialize.cpp
@@ -14,6 +14,7 @@
#include "openvino/core/coordinate_diff.hpp"
#include "openvino/core/except.hpp"
#include "openvino/core/model.hpp"
+#include "openvino/core/model_util.hpp"
#include "openvino/core/parallel.hpp"
#include "openvino/core/type/float16.hpp"
#include "openvino/pass/constant_folding.hpp"
@@ -52,7 +53,8 @@ void serialize_func(std::ostream& xml_file,
std::ostream& bin_file,
std::shared_ptr<ov::Model> model,
ov::pass::Serialize::Version ver,
- bool deterministic = false) {
+ bool deterministic,
+ ov::util::ConstantWriter& constant_writer) {
auto version = static_cast<int64_t>(ver);
auto& rt_info = model->get_rt_info();
@@ -73,9 +75,8 @@ void serialize_func(std::ostream& xml_file,
std::string name = "net";
pugi::xml_document xml_doc;
pugi::xml_node net_node = xml_doc.append_child(name.c_str());
- ov::util::ConstantWriter constant_write_handler(bin_file);
ov::util::XmlSerializer
- visitor(net_node, name, constant_write_handler, version, deterministic, false, ov::element::dynamic, false);
+ visitor(net_node, name, constant_writer, version, deterministic, false, ov::element::dynamic, false);
visitor.on_attribute(name, model);
xml_doc.save(xml_file);
@@ -83,6 +84,14 @@ void serialize_func(std::ostream& xml_file,
bin_file.flush();
}
+void serialize_func(std::ostream& xml_file,
+ std::ostream& bin_file,
+ std::shared_ptr<ov::Model> model,
+ ov::pass::Serialize::Version ver,
+ bool deterministic = false) {
+ ov::util::ConstantWriter constant_write_handler(bin_file);
+ serialize_func(xml_file, bin_file, model, ver, deterministic, constant_write_handler);
+}
} // namespace
namespace ov {
@@ -283,8 +292,9 @@ bool pass::Hash::run_on_model(const std::shared_ptr<ov::Model>& model) {
std::ostream bin(&binHash);
// Determinism is important for hash calculation
- serialize_func(xml, bin, model, Serialize::Version::UNSPECIFIED, true);
-
+ // disable compression when skip weight to speed hash calculation
+ auto constant_writer = util::ConstantWriter(bin, !m_skip_weights);
+ serialize_func(xml, bin, model, Serialize::Version::UNSPECIFIED, true, constant_writer);
uint64_t seed = 0;
seed = util::u64_hash_combine(seed, xmlHash.getResult());
seed = util::u64_hash_combine(seed, binHash.get_result());
@@ -294,6 +304,8 @@ bool pass::Hash::run_on_model(const std::shared_ptr<ov::Model>& model) {
return false;
}
-pass::Hash::Hash(uint64_t& output_hash_value) : m_hash(output_hash_value) {}
+pass::Hash::Hash(uint64_t& output_hash_value, bool skip_weights)
+ : m_hash(output_hash_value),
+ m_skip_weights(skip_weights) {}
} // namespace ov
diff --git a/src/core/tests/pass/serialization/serialize.cpp b/src/core/tests/pass/serialization/serialize.cpp
index c941bc7d81a..2ac5ccced04 100644
--- a/src/core/tests/pass/serialization/serialize.cpp
+++ b/src/core/tests/pass/serialization/serialize.cpp
@@ -105,7 +105,7 @@ public:
std::string m_out_bin_path;
void CompareSerialized(std::function<void(const std::shared_ptr<ov::Model>&)> serializer) {
- auto expected = ov::test::readModel(m_model_path, m_binary_path);
+ auto expected = ov::Core{}.read_model(m_model_path, m_binary_path);
auto orig = expected->clone();
serializer(expected);
auto result = ov::test::readModel(m_out_xml_path, m_out_bin_path);
diff --git a/src/inference/dev_api/openvino/runtime/compilation_context.hpp b/src/inference/dev_api/openvino/runtime/compilation_context.hpp
index 504b7e34a2c..135541911d8 100644
--- a/src/inference/dev_api/openvino/runtime/compilation_context.hpp
+++ b/src/inference/dev_api/openvino/runtime/compilation_context.hpp
@@ -26,6 +26,9 @@ public:
static std::string compute_hash(const std::string& modeStr,
const ov::Tensor& data,
const ov::AnyMap& compileOptions);
+ static std::string compute_hash(const std::shared_ptr<const ov::Model>& model,
+ const std::filesystem::path& model_path,
+ const ov::AnyMap& compileOptions);
};
class CompiledBlobHeader final {
diff --git a/src/inference/include/openvino/runtime/properties.hpp b/src/inference/include/openvino/runtime/properties.hpp
index d914532fd9f..9fff55e0f78 100644
--- a/src/inference/include/openvino/runtime/properties.hpp
+++ b/src/inference/include/openvino/runtime/properties.hpp
@@ -727,6 +727,15 @@ static constexpr Property<std::string> cache_dir{"CACHE_DIR"};
*/
static constexpr Property<bool, PropertyMutability::RO> loaded_from_cache{"LOADED_FROM_CACHE"};
+/**
+ * @brief Write property to specify the origin path of compiled model to speed cache model ID calculation.
+ * @ingroup ov_runtime_cpp_prop_api
+ *
+ * The property has meaning when used in `core::compile_model(const std::shared_ptr<const ov::Model>& model, ...)` and
+ * cache feature is enabled.
+ */
+static inline constexpr Property<std::filesystem::path, PropertyMutability::WO> cache_model_path{"CACHE_MODEL_PATH"};
+
/**
* @brief Enum to define possible workload types
*
diff --git a/src/inference/src/dev/compilation_context.cpp b/src/inference/src/dev/compilation_context.cpp
index 3f3d54eb022..319570688ed 100644
--- a/src/inference/src/dev/compilation_context.cpp
+++ b/src/inference/src/dev/compilation_context.cpp
@@ -54,13 +54,20 @@ std::string ModelCache::calculate_file_info(const std::string& filePath) {
std::string ModelCache::compute_hash(const std::shared_ptr<const ov::Model>& model, const ov::AnyMap& compileOptions) {
OV_ITT_SCOPE(FIRST_INFERENCE, ov::itt::domains::ReadTime, "ModelCache::compute_hash - Model");
+ return compute_hash(model, {}, compileOptions);
+}
+
+std::string ModelCache::compute_hash(const std::shared_ptr<const ov::Model>& model,
+ const std::filesystem::path& model_path,
+ const ov::AnyMap& compileOptions) {
+ OV_ITT_SCOPE(FIRST_INFERENCE, ov::itt::domains::ReadTime, "ModelCache::compute_hash - Model and path");
OPENVINO_ASSERT(model);
uint64_t seed = 0;
- // 1. Calculate hash on function
+ // 1. Calculate hash on function, skipping weights if model path is provided
ov::pass::Manager m;
- m.register_pass<ov::pass::Hash>(seed);
+ m.register_pass<ov::pass::Hash>(seed, !model_path.empty());
m.run_passes(std::const_pointer_cast<ov::Model>(model));
// 2. Compute hash on serialized data and options
@@ -81,6 +88,11 @@ std::string ModelCache::compute_hash(const std::shared_ptr<const ov::Model>& mod
}
}
+ // 4. If model path is provided add file info to the hash
+ if (!model_path.empty()) {
+ seed = hash_combine(seed, compute_hash(model_path.string(), compileOptions));
+ }
+
return std::to_string(seed);
}
diff --git a/src/inference/src/dev/core_impl.cpp b/src/inference/src/dev/core_impl.cpp
index 26382f01256..6a047eda792 100644
--- a/src/inference/src/dev/core_impl.cpp
+++ b/src/inference/src/dev/core_impl.cpp
@@ -12,6 +12,7 @@
#include "model_reader.hpp"
#include "openvino/core/any.hpp"
#include "openvino/core/except.hpp"
+#include "openvino/core/model_util.hpp"
#include "openvino/core/op_extension.hpp"
#include "openvino/core/preprocess/pre_post_process.hpp"
#include "openvino/core/so_extension.hpp"
@@ -265,6 +266,11 @@ ov::SoPtr<ov::ICompiledModel> import_compiled_model(const ov::Plugin& plugin,
std::visit(apply_model_hint, model_hint);
return import_compiled_model(plugin, context, cfg);
}
+
+std::filesystem::path get_cache_model_path(const ov::AnyMap& config) {
+ const auto it = config.find(ov::cache_model_path.name());
+ return it == config.end() ? std::filesystem::path{} : it->second.as<std::filesystem::path>();
+}
} // namespace
bool ov::is_config_applicable(const std::string& user_device_name, const std::string& subprop_device_name) {
@@ -821,30 +827,32 @@ ov::SoPtr<ov::ICompiledModel> ov::CoreImpl::compile_model(const std::shared_ptr<
const std::string& device_name,
const ov::AnyMap& config) const {
OV_ITT_SCOPE(FIRST_INFERENCE, ov::itt::domains::LoadTime, "Core::compile_model::model");
- std::string deviceName = device_name;
- ov::AnyMap config_with_batch = config;
+ auto patched_device_name = device_name;
+ auto config_with_batch = config;
// if auto-batching is applicable, the below function will patch the device name and config accordingly:
- auto model = apply_auto_batching(model_, deviceName, config_with_batch);
+ const auto model = apply_auto_batching(model_, patched_device_name, config_with_batch);
- auto parsed = parseDeviceNameIntoConfig(deviceName, coreConfig, config_with_batch, is_proxy_device(deviceName));
+ auto parsed = parseDeviceNameIntoConfig(patched_device_name,
+ coreConfig,
+ config_with_batch,
+ is_proxy_device(patched_device_name));
auto plugin = get_plugin(parsed._deviceName);
// will consume ov::cache_dir if plugin not support it
- auto cacheManager = parsed._core_config.get_cache_config_for_device(plugin, parsed._config)._cacheManager;
+ const auto cache_manager = parsed._core_config.get_cache_config_for_device(plugin, parsed._config)._cacheManager;
auto res = import_compiled_model(plugin, {}, parsed._config, model);
// Skip caching for proxy plugin. HW plugin will load network from the cache
if (res) {
// hint::compiled_blob is set and imported skip compilation
- } else if (cacheManager && device_supports_model_caching(plugin, parsed._config) && !is_proxy_device(plugin)) {
- CacheContent cacheContent{cacheManager, parsed._core_config.get_enable_mmap()};
- cacheContent.blobId = ov::ModelCache::compute_hash(model, create_compile_config(plugin, parsed._config));
- cacheContent.model = model;
- std::unique_ptr<CacheGuardEntry> lock = cacheGuard.get_hash_lock(cacheContent.blobId);
- res = load_model_from_cache(cacheContent, plugin, parsed._config, ov::SoPtr<ov::IRemoteContext>{}, [&]() {
- return compile_model_and_cache(plugin,
- model,
- parsed._config,
- ov::SoPtr<ov::IRemoteContext>{},
- cacheContent);
+ } else if (cache_manager && device_supports_model_caching(plugin, parsed._config) && !is_proxy_device(plugin)) {
+ CacheContent cache_content{cache_manager,
+ parsed._core_config.get_enable_mmap(),
+ get_cache_model_path(config).string()};
+ const auto compiled_config = create_compile_config(plugin, parsed._config);
+ cache_content.blobId = ModelCache::compute_hash(model, cache_content.modelPath, compiled_config);
+ cache_content.model = model;
+ const auto lock = cacheGuard.get_hash_lock(cache_content.blobId);
+ res = load_model_from_cache(cache_content, plugin, parsed._config, {}, [&]() {
+ return compile_model_and_cache(plugin, model, parsed._config, {}, cache_content);
});
} else {
res = plugin.compile_model(model, parsed._config);
@@ -858,26 +866,28 @@ ov::SoPtr<ov::ICompiledModel> ov::CoreImpl::compile_model(const std::shared_ptr<
OV_ITT_SCOPE(FIRST_INFERENCE, ov::itt::domains::LoadTime, "Core::compile_model::RemoteContext");
if (!context)
OPENVINO_THROW("Remote context is null");
- std::string deviceName = context->get_device_name();
- ov::AnyMap config_with_batch = config;
+ auto device_name = context->get_device_name();
+ auto config_with_batch = config;
// if auto-batching is applicable, the below function will patch the device name and config accordingly:
- auto model = apply_auto_batching(model_, deviceName, config_with_batch);
+ const auto model = apply_auto_batching(model_, device_name, config_with_batch);
- auto parsed = parseDeviceNameIntoConfig(deviceName, coreConfig, config_with_batch, is_proxy_device(deviceName));
+ auto parsed = parseDeviceNameIntoConfig(device_name, coreConfig, config_with_batch, is_proxy_device(device_name));
auto plugin = get_plugin(parsed._deviceName);
// will consume ov::cache_dir if plugin not support it
- auto cacheManager = parsed._core_config.get_cache_config_for_device(plugin, parsed._config)._cacheManager;
+ const auto cache_manager = parsed._core_config.get_cache_config_for_device(plugin, parsed._config)._cacheManager;
auto res = import_compiled_model(plugin, context, parsed._config, model);
// Skip caching for proxy plugin. HW plugin will load network from the cache
if (res) {
// hint::compiled_blob is set and imported skip compilation
- } else if (cacheManager && device_supports_model_caching(plugin, parsed._config) && !is_proxy_device(plugin)) {
- CacheContent cacheContent{cacheManager, parsed._core_config.get_enable_mmap()};
- cacheContent.blobId = ov::ModelCache::compute_hash(model, create_compile_config(plugin, parsed._config));
- std::unique_ptr<CacheGuardEntry> lock = cacheGuard.get_hash_lock(cacheContent.blobId);
- cacheContent.model = model;
- res = load_model_from_cache(cacheContent, plugin, parsed._config, context, [&]() {
- return compile_model_and_cache(plugin, model, parsed._config, context, cacheContent);
+ } else if (cache_manager && device_supports_model_caching(plugin, parsed._config) && !is_proxy_device(plugin)) {
+ CacheContent cache_content{cache_manager,
+ parsed._core_config.get_enable_mmap(),
+ get_cache_model_path(config).string()};
+ const auto compiled_config = create_compile_config(plugin, parsed._config);
+ cache_content.blobId = ModelCache::compute_hash(model, cache_content.modelPath, compiled_config);
+ cache_content.model = model;
+ res = load_model_from_cache(cache_content, plugin, parsed._config, context, [&]() {
+ return compile_model_and_cache(plugin, model, parsed._config, context, cache_content);
});
} else {
res = plugin.compile_model(model, context, parsed._config);
@@ -893,23 +903,22 @@ ov::SoPtr<ov::ICompiledModel> ov::CoreImpl::compile_model(const std::string& mod
// in case of compile_model(file_name), we need to clear-up core-level properties
auto plugin = get_plugin(parsed._deviceName);
// will consume ov::cache_dir if plugin not support it
- auto cacheManager = parsed._core_config.get_cache_config_for_device(plugin, parsed._config)._cacheManager;
+ const auto cache_manager = parsed._core_config.get_cache_config_for_device(plugin, parsed._config)._cacheManager;
auto compiled_model = import_compiled_model(plugin, {}, parsed._config, model_path);
if (compiled_model) {
// hint::compiled_blob is set and imported skip compilation
- } else if (cacheManager && device_supports_model_caching(plugin, parsed._config) && !is_proxy_device(plugin)) {
+ } else if (cache_manager && device_supports_model_caching(plugin, parsed._config) && !is_proxy_device(plugin)) {
// Skip caching for proxy plugin. HW plugin will load network from the cache
CoreConfig::remove_core_skip_cache_dir(parsed._config);
- CacheContent cacheContent{cacheManager, parsed._core_config.get_enable_mmap(), model_path};
- cacheContent.blobId = ov::ModelCache::compute_hash(model_path, create_compile_config(plugin, parsed._config));
- std::unique_ptr<CacheGuardEntry> lock = cacheGuard.get_hash_lock(cacheContent.blobId);
- compiled_model =
- load_model_from_cache(cacheContent, plugin, parsed._config, ov::SoPtr<ov::IRemoteContext>{}, [&]() {
- const auto model =
- util::read_model(model_path, "", get_extensions_copy(), parsed._core_config.get_enable_mmap());
- return compile_model_and_cache(plugin, model, parsed._config, {}, cacheContent);
- });
+ CacheContent cache_content{cache_manager, parsed._core_config.get_enable_mmap(), model_path};
+ cache_content.blobId = ov::ModelCache::compute_hash(model_path, create_compile_config(plugin, parsed._config));
+ const auto lock = cacheGuard.get_hash_lock(cache_content.blobId);
+ compiled_model = load_model_from_cache(cache_content, plugin, parsed._config, {}, [&]() {
+ const auto model =
+ util::read_model(model_path, "", get_extensions_copy(), parsed._core_config.get_enable_mmap());
+ return compile_model_and_cache(plugin, model, parsed._config, {}, cache_content);
+ });
} else {
compiled_model = plugin.compile_model(model_path, parsed._config);
}
@@ -924,27 +933,22 @@ ov::SoPtr<ov::ICompiledModel> ov::CoreImpl::compile_model(const std::string& mod
auto parsed = parseDeviceNameIntoConfig(device_name, coreConfig, config);
auto plugin = get_plugin(parsed._deviceName);
// will consume ov::cache_dir if plugin not support it
- auto cacheManager = parsed._core_config.get_cache_config_for_device(plugin, parsed._config)._cacheManager;
+ const auto cache_manager = parsed._core_config.get_cache_config_for_device(plugin, parsed._config)._cacheManager;
auto compiled_model = import_compiled_model(plugin, {}, parsed._config);
// Skip caching for proxy plugin. HW plugin will load network from the cache
if (compiled_model) {
// hint::compiled_blob is set and imported skip compilation
- } else if (cacheManager && device_supports_model_caching(plugin, parsed._config) && !is_proxy_device(plugin)) {
- CacheContent cacheContent{cacheManager, parsed._core_config.get_enable_mmap()};
- cacheContent.blobId =
+ } else if (cache_manager && device_supports_model_caching(plugin, parsed._config) && !is_proxy_device(plugin)) {
+ CacheContent cache_content{cache_manager, parsed._core_config.get_enable_mmap()};
+ cache_content.blobId =
ov::ModelCache::compute_hash(model_str, weights, create_compile_config(plugin, parsed._config));
- std::unique_ptr<CacheGuardEntry> lock = cacheGuard.get_hash_lock(cacheContent.blobId);
- compiled_model =
- load_model_from_cache(cacheContent, plugin, parsed._config, ov::SoPtr<ov::IRemoteContext>{}, [&]() {
- auto model = read_model(model_str, weights);
- return compile_model_and_cache(plugin,
- model,
- parsed._config,
- ov::SoPtr<ov::IRemoteContext>{},
- cacheContent);
- });
+ const auto lock = cacheGuard.get_hash_lock(cache_content.blobId);
+ compiled_model = load_model_from_cache(cache_content, plugin, parsed._config, {}, [&]() {
+ const auto model = read_model(model_str, weights);
+ return compile_model_and_cache(plugin, model, parsed._config, {}, cache_content);
+ });
} else {
- auto model = read_model(model_str, weights);
+ const auto model = read_model(model_str, weights);
compiled_model = plugin.compile_model(model, parsed._config);
}
return compiled_model;
@@ -1713,7 +1717,7 @@ void ov::CoreConfig::remove_core(ov::AnyMap& config) {
}
void ov::CoreConfig::remove_core_skip_cache_dir(ov::AnyMap& config) {
- for (const auto& name : {ov::enable_mmap.name(), ov::force_tbb_terminate.name()}) {
+ for (const auto& name : {ov::enable_mmap.name(), ov::force_tbb_terminate.name(), ov::cache_model_path.name()}) {
config.erase(name);
}
}
diff --git a/src/inference/tests/functional/caching_test.cpp b/src/inference/tests/functional/caching_test.cpp
index 4dd243e5661..4e48df837be 100644
--- a/src/inference/tests/functional/caching_test.cpp
+++ b/src/inference/tests/functional/caching_test.cpp
@@ -2881,6 +2881,53 @@ TEST_P(CachingTest, import_from_compiled_blob_weights_path_property_is_supported
m_testFunctionWithCfg(core, config);
});
}
+
+TEST_P(CachingTest, import_from_cache_model_by_custom_model_rt_info) {
+ ON_CALL(*mockPlugin, import_model(A<const ov::Tensor&>(), _))
+ .WillByDefault(Invoke([&](const ov::Tensor& itensor, const ov::AnyMap& config) {
+ if (m_checkConfigCb) {
+ m_checkConfigCb(config);
+ }
+ EXPECT_EQ(config.count(ov::hint::compiled_blob.name()), 0);
+ EXPECT_EQ(config.count(ov::hint::model.name()), 0);
+ EXPECT_EQ(config.count(ov::weights_path.name()), 0);
+
+ size_t pos = 0;
+ auto name = getline_from_buffer(itensor.data<const char>(), itensor.get_byte_size(), pos);
+ std::lock_guard<std::mutex> lock(mock_creation_mutex);
+ return create_mock_compiled_model(m_models[name], mockPlugin);
+ }));
+ EXPECT_CALL(*mockPlugin, get_property(_, _)).Times(AnyNumber());
+ EXPECT_CALL(*mockPlugin, query_model(_, _)).Times(AnyNumber());
+ EXPECT_CALL(*mockPlugin, get_property(ov::device::architecture.name(), _)).Times(AnyNumber());
+ EXPECT_CALL(*mockPlugin, get_property(ov::internal::caching_properties.name(), _)).Times(AnyNumber());
+ if (m_remoteContext) {
+ return; // skip the remote Context test for Multi plugin
+ }
+ m_post_mock_net_callbacks.emplace_back([&](MockICompiledModelImpl& net) {
+ EXPECT_CALL(net, export_model(_)).Times(1);
+ });
+ MkDirGuard guard(m_cacheDir);
+ EXPECT_CALL(*mockPlugin, compile_model(_, _, _)).Times(0);
+ EXPECT_CALL(*mockPlugin, compile_model(A<const std::shared_ptr<const ov::Model>&>(), _)).Times(1);
+ EXPECT_CALL(*mockPlugin, import_model(A<std::istream&>(), _, _)).Times(1);
+ EXPECT_CALL(*mockPlugin, import_model(A<std::istream&>(), _)).Times(1);
+ EXPECT_CALL(*mockPlugin, import_model(A<const ov::Tensor&>(), _, _)).Times(0);
+ EXPECT_CALL(*mockPlugin, import_model(A<const ov::Tensor&>(), _)).Times(0);
+ testLoad([&](ov::Core& core) {
+ const auto config = ov::AnyMap{{ov::cache_dir(m_cacheDir)}, ov::cache_model_path(modelName)};
+
+ // read and load model with path hint
+ performReadAndLoad(core, config);
+
+ // load from cache without path hint
+ performReadAndLoadWithContext(core, config);
+
+ // load from cache with path hint
+ performReadAndLoad(core, config);
+ });
+}
+
#if defined(ENABLE_OV_IR_FRONTEND)
static std::string getTestCaseName(const testing::TestParamInfo<std::tuple<TestParam, std::string>>& obj) {