Skip to content

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

[NPU] Create compiler adapter class (#27006)

Bogdan Pereanucaa1e6af1313
diff --git a/src/plugins/intel_npu/README.md b/src/plugins/intel_npu/README.md
index b7508c68704..980faa71a15 100644
--- a/src/plugins/intel_npu/README.md
+++ b/src/plugins/intel_npu/README.md
@@ -78,7 +78,7 @@ There is currently no support for multiple devices, which means only one level-z
### Inference pipeline
-The result of the model compilation is represented through a NetworkDescription. This model description is passed by the plugin to the driver to create a level zero graph instance and obtain a graph handle that can later be used to execute multiple inferences in parallel for the same model. Since the same model instance is shared across all subsequent inference objects, this initialization step is performed by default right after the model is compiled and it can be postponed until the creation of the first inference request through the use of an environment variable: "IE_NPU_CREATE_EXECUTOR" (IE_NPU_CREATE_EXECUTOR=0 to postpone the initialization).
+The result of the model compilation is represented through an IGraph object, which contains a valid level zero graph handle that can later be used to execute multiple inferences in parallel for the same model. By default, weights are loaded into the NPU memory right after the model is compiled, but this step can be postponed until the creation of the first inference request through the use of an internal NPU property: "NPU_DEFER_WEIGHTS_LOAD".
Users can create one or more inference requests for a compiled model using OpenVINO API:
diff --git a/src/plugins/intel_npu/cmake/features.cmake b/src/plugins/intel_npu/cmake/features.cmake
index 0dde0f9d67f..7d34c52c6d1 100644
--- a/src/plugins/intel_npu/cmake/features.cmake
+++ b/src/plugins/intel_npu/cmake/features.cmake
@@ -4,29 +4,10 @@
ov_option(ENABLE_MLIR_COMPILER "Enable compilation of npu_mlir_compiler libraries" ON)
-ov_option(ENABLE_NPU_RUNTIME_COMMON "Enable compilation of npu runtime common libraries" ON)
+ov_option(ENABLE_NPU_PLUGIN_ENGINE "Enable compilation of NPU plugin engine" ON)
-# if ENABLE_ZEROAPI_BACKEND=ON, it adds the ze_loader dependency for driver compiler
-ov_dependent_option(ENABLE_NPU_PLUGIN_ENGINE "Enable compilation of NPU plugin engine" ON "ENABLE_NPU_RUNTIME_COMMON" OFF)
-
-ov_dependent_option(ENABLE_ZEROAPI_BACKEND "Enable zero-api as a plugin backend" ON "ENABLE_NPU_RUNTIME_COMMON;ENABLE_NPU_PLUGIN_ENGINE" OFF)
-
-ov_dependent_option(ENABLE_DRIVER_COMPILER_ADAPTER "Enable NPU Compiler inside driver" ON "ENABLE_ZEROAPI_BACKEND" OFF)
-
-if((NOT ENABLE_NPU_PLUGIN_ENGINE OR NOT ENABLE_NPU_RUNTIME_COMMON) AND ENABLE_TESTS)
- message(FATAL_ERROR "Tests depends on npu plugin engine and npu runtime common libraries!")
-endif()
-
-if((NOT ENABLE_NPU_PLUGIN_ENGINE OR NOT ENABLE_NPU_RUNTIME_COMMON) AND ENABLE_ZEROAPI_BACKEND)
- message(FATAL_ERROR "Zero backend depends on npu plugin engine and npu common libraries!")
-endif()
-
-if(NOT ENABLE_ZEROAPI_BACKEND AND ENABLE_DRIVER_COMPILER_ADAPTER)
- message(FATAL_ERROR "Compiler adapter depends on zero backend to use same context!")
-endif()
-
-if(NOT BUILD_SHARED_LIBS AND NOT ENABLE_MLIR_COMPILER AND NOT ENABLE_DRIVER_COMPILER_ADAPTER)
- message(FATAL_ERROR "No compiler found for static build!")
+if(NOT ENABLE_NPU_PLUGIN_ENGINE AND ENABLE_TESTS)
+ message(FATAL_ERROR "Tests depends on npu plugin engine!")
endif()
ov_dependent_option(ENABLE_IMD_BACKEND "Enable InferenceManagerDemo based NPU AL backend" OFF "NOT WIN32;NOT CMAKE_CROSSCOMPILING" OFF)
diff --git a/src/plugins/intel_npu/src/CMakeLists.txt b/src/plugins/intel_npu/src/CMakeLists.txt
index 5530eb1f3e5..f5d1fd5b412 100644
--- a/src/plugins/intel_npu/src/CMakeLists.txt
+++ b/src/plugins/intel_npu/src/CMakeLists.txt
@@ -9,18 +9,9 @@ add_subdirectory(utils)
add_subdirectory(al)
-if (ENABLE_NPU_RUNTIME_COMMON)
+if (ENABLE_NPU_PLUGIN_ENGINE)
add_subdirectory(common)
-endif()
-
-if(ENABLE_DRIVER_COMPILER_ADAPTER AND ENABLE_ZEROAPI_BACKEND)
- add_subdirectory(compiler)
-endif()
-
-if(ENABLE_ZEROAPI_BACKEND)
+ add_subdirectory(compiler_adapter)
add_subdirectory(backend)
-endif()
-
-if (ENABLE_NPU_PLUGIN_ENGINE)
add_subdirectory(plugin)
endif()
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/runtime.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/config/runtime.hpp
index d52c25f6a3e..510ab7fc43b 100644
--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/runtime.hpp
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/runtime.hpp
@@ -131,6 +131,38 @@ struct CREATE_EXECUTOR final : OptionBase<CREATE_EXECUTOR, int64_t> {
}
};
+//
+// DEFER_WEIGHTS_LOAD
+//
+
+struct DEFER_WEIGHTS_LOAD final : OptionBase<DEFER_WEIGHTS_LOAD, bool> {
+ static std::string_view key() {
+ return ov::intel_npu::defer_weights_load.name();
+ }
+
+ static int64_t defaultValue() {
+ return false;
+ }
+
+ static constexpr std::string_view getTypeName() {
+ return "bool";
+ }
+
+#ifdef NPU_PLUGIN_DEVELOPER_BUILD
+ static std::string_view envVar() {
+ return "OV_NPU_DEFER_WEIGHTS_LOAD";
+ }
+#endif
+
+ static bool isPublic() {
+ return false;
+ }
+
+ static OptionMode mode() {
+ return OptionMode::RunTime;
+ }
+};
+
//
// NUM_STREAMS
//
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/icompiler.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/icompiler.hpp
index e0a02f12aa2..53696396603 100644
--- a/src/plugins/intel_npu/src/al/include/intel_npu/icompiler.hpp
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/icompiler.hpp
@@ -6,128 +6,12 @@
#pragma once
-#include <cstddef>
-#include <memory>
-#include <set>
-#include <string>
-#include <string_view>
-#include <unordered_map>
-#include <unordered_set>
-
#include "intel_npu/config/config.hpp"
-#include "openvino/core/partial_shape.hpp"
-#include "openvino/core/type/element_type.hpp"
-#include "openvino/runtime/common.hpp"
+#include "intel_npu/network_metadata.hpp"
#include "openvino/runtime/profiling_info.hpp"
namespace intel_npu {
-/**
- * @brief A helper structure used for storing metadata corresponding to one input/output entry.
- */
-struct IODescriptor {
- /**
- * @brief The name of the input/output assigned by the compiler.
- * @details This value may differ from other name attributes:
- * - The compiler could have created additional inputs/outputs (e.g. for representing states). These are not
- * found in the original IR model.
- * - The compiler may append indices to names in the case where duplicate names are found.
- * @note The prefixes introduced by the compiler in order to differentiate the special cases (e.g. states and shape
- * tensors) were removed prior to initializing this field.
- */
- std::string nameFromCompiler;
-
- ov::element::Type precision;
-
- ov::PartialShape shapeFromCompiler;
-
- /**
- * @brief If set to "true", the current object describes a buffer which may be used for altering a state tensor.
- * @details This flag is set if the compiler prefixed the name using a "read value" prefix. The state input and
- * state output descriptors are also tied using the "relatedDescriptorIndex" attribute.
- */
- bool isStateInput = false;
-
- /**
- * @brief If set to "true", the current object describes a buffer which reflects the value of a state tensor.
- * @details This flag is set if the compiler prefixed the name using an "assign" prefix. The state input and
- * state output descriptors are also tied using the "relatedDescriptorIndex" attribute.
- */
- bool isStateOutput = false;
-
- /**
- * @brief If set to "true", the buffer of the tensor described here contains as value the shape of the referenced
- * tensor.
- * @details This flag is set if the compiler prefixed the name using a "shape" prefix.
- *
- * The referenced tensor bears the same name ("nameFromCompiler"), but its "isShapeTensor" value is set to
- * "false". The two descriptors are also tied using the "relatedDescriptorIndex" attribute.
- */
- bool isShapeTensor = false;
-
- /**
- * @brief Points towards a related descriptor.
- * @details The related descriptors are defined by (state input, state output) or (dynamic tensor, shape tensor)
- * pairs.
- */
- std::optional<size_t> relatedDescriptorIndex;
-
- /**
- * @brief The friendly name of the node extracted from the IR model.
- * @details In some cases, this field is required for constructing a dummy model which uses the same input/output
- * metadata as the original IR model.
- *
- * This field may be empty if the I/O entry is not found in the original IR model (i.e. the entry was added by the
- * compiler).
- */
- std::string nodeFriendlyName;
-
- /**
- * @brief The names of the output tensors extracted from the IR model.
- * @details In some cases, this field is required for constructing a dummy model which uses the same input/output
- * metadata as the original IR model.
- *
- * This field may be empty if the I/O entry is not found in the original IR model (i.e. the entry was added by the
- * compiler).
- */
- std::unordered_set<std::string> outputTensorNames;
-
- /**
- * @brief The shape extracted from the IR model.
- * @details The values may differ from the ones found in "shapeFromCompiler" if batching is to be handled by the
- * plugin.
- *
- * This field may be empty if the I/O entry is not found in the original IR model (i.e. the entry was added
- * by the compiler).
- */
- std::optional<ov::PartialShape> shapeFromIRModel = std::nullopt;
-};
-
-struct NetworkMetadata final {
- std::string name;
-
- std::vector<IODescriptor> inputs;
- std::vector<IODescriptor> outputs;
- std::vector<IODescriptor> profilingOutputs;
-
- size_t numStreams = 1;
-
- // Used primarily in the CID path to pass the level zero graph handle from compiler to the backend executor
- void* graphHandle = nullptr;
-
- /**
- * @brief Binds the (state input, state output) and (dynamic tensor, shape tensor) pairs using the
- * "relatedDescriptorIndex" attribute.
- * @details For state inputs, the "relatedDescriptorIndex" value is set to the index of the output which bears the
- * same name. The reverse is also applied.
- *
- * For shape tensors, the lookup is performed in the same container (inputs or outputs). The value is once again set
- * to the index of the entry which bears the same name.
- */
- void bindRelatedDescriptors();
-
-}; // namespace intel_npu
-
/**
* @struct NetworkDescription
* @brief The object returned by the compiler
@@ -138,7 +22,6 @@ struct NetworkDescription final {
NetworkDescription(std::vector<uint8_t>&& compiledNetwork, NetworkMetadata&& metadata)
: compiledNetwork(std::move(compiledNetwork)),
metadata(std::move(metadata)) {}
- NetworkDescription(NetworkMetadata&& metadata) : metadata(std::move(metadata)) {}
// Force move semantics to prevent blob copies
NetworkDescription(const NetworkDescription&) = delete;
NetworkDescription(NetworkDescription&&) = default;
@@ -151,32 +34,6 @@ struct NetworkDescription final {
NetworkMetadata metadata;
};
-/**
- * @struct CompiledNetwork
- * @brief Custom container for compiled network, used for export
- * @var CompiledNetwork::data
- * Pointer to the address of compiled network
- * @var CompiledNetwork:size
- * Size of the compiled network
- * @var CompiledNetwork::ownedStorage
- * Plugin owned compiled network storage that is required in case of a driver that
- * doesn't support graph extension 1.7, as in this case plugin must create a copy of the compiled network.
- * @note It's unsafe to store either data or size outside of the compiled network object as its destructor
- * would release the owning container
- */
-
-struct CompiledNetwork {
- const uint8_t* data;
- size_t size;
- CompiledNetwork(const uint8_t* data, size_t size, std::vector<uint8_t> storage)
- : data(data),
- size(size),
- ownedStorage(std::move(storage)) {}
-
-private:
- std::vector<uint8_t> ownedStorage;
-};
-
/**
* @interface ICompiler
* @brief An interface to be implemented by a concrete compiler to provide
@@ -184,12 +41,6 @@ private:
*/
class ICompiler : public std::enable_shared_from_this<ICompiler> {
public:
- /**
- * @brief Returns the maximum OpenVino opset version supported by the compiler
- * @return opset version e.g. 11 for opset11
- */
- virtual uint32_t getSupportedOpsetVersion() const = 0;
-
/**
* @brief Transforms a network from the OpenVINO model representation to a format executable
* by a NPU device
@@ -216,8 +67,6 @@ public:
* @param config a reference to NPUConfig containing plugin config options
* Note: compilation options will be ignored,
* since the network is already compiled
- * @param netName a reference to the string describing network name
- * to be used for creating network description
* @return a shared pointer on an object implementing NetworkDescription interface
*/
virtual NetworkMetadata parse(const std::vector<uint8_t>& network, const Config& config) const = 0;
@@ -226,15 +75,6 @@ public:
const std::vector<uint8_t>& network,
const Config& config) const = 0;
- // Driver compiler can use this to release graphHandle, if we do not have executor
- virtual void release([[maybe_unused]] std::shared_ptr<const NetworkDescription> networkDescription){};
-
- virtual CompiledNetwork getCompiledNetwork(const NetworkDescription& networkDescription) {
- return CompiledNetwork(networkDescription.compiledNetwork.data(),
- networkDescription.compiledNetwork.size(),
- networkDescription.compiledNetwork);
- }
-
protected:
virtual ~ICompiler() = default;
};
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/network_metadata.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/network_metadata.hpp
new file mode 100644
index 00000000000..b7a78b3dfd4
--- /dev/null
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/network_metadata.hpp
@@ -0,0 +1,127 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Compiler Interface
+
+#pragma once
+
+#include <cstddef>
+#include <memory>
+#include <set>
+#include <string>
+#include <string_view>
+#include <unordered_map>
+#include <unordered_set>
+
+#include "intel_npu/config/config.hpp"
+#include "openvino/core/partial_shape.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/runtime/common.hpp"
+
+namespace intel_npu {
+
+/**
+ * @brief A helper structure used for storing metadata corresponding to one input/output entry.
+ */
+struct IODescriptor {
+ /**
+ * @brief The name of the input/output assigned by the compiler.
+ * @details This value may differ from other name attributes:
+ * - The compiler could have created additional inputs/outputs (e.g. for representing states). These are not
+ * found in the original IR model.
+ * - The compiler may append indices to names in the case where duplicate names are found.
+ * @note The prefixes introduced by the compiler in order to differentiate the special cases (e.g. states and shape
+ * tensors) were removed prior to initializing this field.
+ */
+ std::string nameFromCompiler;
+
+ ov::element::Type precision;
+
+ ov::PartialShape shapeFromCompiler;
+
+ /**
+ * @brief If set to "true", the current object describes a buffer which may be used for altering a state tensor.
+ * @details This flag is set if the compiler prefixed the name using a "read value" prefix. The state input and
+ * state output descriptors are also tied using the "relatedDescriptorIndex" attribute.
+ */
+ bool isStateInput = false;
+
+ /**
+ * @brief If set to "true", the current object describes a buffer which reflects the value of a state tensor.
+ * @details This flag is set if the compiler prefixed the name using an "assign" prefix. The state input and
+ * state output descriptors are also tied using the "relatedDescriptorIndex" attribute.
+ */
+ bool isStateOutput = false;
+
+ /**
+ * @brief If set to "true", the buffer of the tensor described here contains as value the shape of the referenced
+ * tensor.
+ * @details This flag is set if the compiler prefixed the name using a "shape" prefix.
+ *
+ * The referenced tensor bears the same name ("nameFromCompiler"), but its "isShapeTensor" value is set to
+ * "false". The two descriptors are also tied using the "relatedDescriptorIndex" attribute.
+ */
+ bool isShapeTensor = false;
+
+ /**
+ * @brief Points towards a related descriptor.
+ * @details The related descriptors are defined by (state input, state output) or (dynamic tensor, shape tensor)
+ * pairs.
+ */
+ std::optional<size_t> relatedDescriptorIndex;
+
+ /**
+ * @brief The friendly name of the node extracted from the IR model.
+ * @details In some cases, this field is required for constructing a dummy model which uses the same input/output
+ * metadata as the original IR model.
+ *
+ * This field may be empty if the I/O entry is not found in the original IR model (i.e. the entry was added by the
+ * compiler).
+ */
+ std::string nodeFriendlyName;
+
+ /**
+ * @brief The names of the output tensors extracted from the IR model.
+ * @details In some cases, this field is required for constructing a dummy model which uses the same input/output
+ * metadata as the original IR model.
+ *
+ * This field may be empty if the I/O entry is not found in the original IR model (i.e. the entry was added by the
+ * compiler).
+ */
+ std::unordered_set<std::string> outputTensorNames;
+
+ /**
+ * @brief The shape extracted from the IR model.
+ * @details The values may differ from the ones found in "shapeFromCompiler" if batching is to be handled by the
+ * plugin.
+ *
+ * This field may be empty if the I/O entry is not found in the original IR model (i.e. the entry was added
+ * by the compiler).
+ */
+ std::optional<ov::PartialShape> shapeFromIRModel = std::nullopt;
+};
+
+struct NetworkMetadata final {
+ std::string name;
+
+ std::vector<IODescriptor> inputs;
+ std::vector<IODescriptor> outputs;
+ std::vector<IODescriptor> profilingOutputs;
+
+ size_t numStreams = 1;
+
+ /**
+ * @brief Binds the (state input, state output) and (dynamic tensor, shape tensor) pairs using the
+ * "relatedDescriptorIndex" attribute.
+ * @details For state inputs, the "relatedDescriptorIndex" value is set to the index of the output which bears the
+ * same name. The reverse is also applied.
+ *
+ * For shape tensors, the lookup is performed in the same container (inputs or outputs). The value is once again set
+ * to the index of the entry which bears the same name.
+ */
+ void bindRelatedDescriptors();
+
+}; // namespace intel_npu
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/npu_private_properties.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/npu_private_properties.hpp
index 0c5a04ce0c0..d8fabee177b 100644
--- a/src/plugins/intel_npu/src/al/include/intel_npu/npu_private_properties.hpp
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/npu_private_properties.hpp
@@ -351,6 +351,13 @@ static constexpr ov::Property<BatchMode> batch_mode{"NPU_BATCH_MODE"};
*/
static constexpr ov::Property<int64_t> create_executor{"NPU_CREATE_EXECUTOR"};
+/**
+ * @brief [Only for NPU Plugin]
+ * Type: boolean, default is false
+ * This option allows to omit loading the weights until inference is created
+ */
+static constexpr ov::Property<bool> defer_weights_load{"NPU_DEFER_WEIGHTS_LOAD"};
+
/**
* @brief Read-only property to get the name of used backend
*/
diff --git a/src/plugins/intel_npu/src/al/src/config/runtime.cpp b/src/plugins/intel_npu/src/al/src/config/runtime.cpp
index 10f9b4a7c72..759956b6f59 100644
--- a/src/plugins/intel_npu/src/al/src/config/runtime.cpp
+++ b/src/plugins/intel_npu/src/al/src/config/runtime.cpp
@@ -21,6 +21,7 @@ void intel_npu::registerRunTimeOptions(OptionsDesc& desc) {
desc.add<PROFILING_TYPE>();
desc.add<MODEL_PRIORITY>();
desc.add<CREATE_EXECUTOR>();
+ desc.add<DEFER_WEIGHTS_LOAD>();
desc.add<NUM_STREAMS>();
desc.add<ENABLE_CPU_PINNING>();
desc.add<WORKLOAD_TYPE>();
diff --git a/src/plugins/intel_npu/src/backend/CMakeLists.txt b/src/plugins/intel_npu/src/backend/CMakeLists.txt
index 01465a8179d..5a1585c0a63 100644
--- a/src/plugins/intel_npu/src/backend/CMakeLists.txt
+++ b/src/plugins/intel_npu/src/backend/CMakeLists.txt
@@ -25,7 +25,6 @@ target_link_libraries(${TARGET_NAME}
PRIVATE
openvino::npu_al
openvino::npu_common
- openvino_npu_zero_result_parser
ze_loader
)
@@ -33,31 +32,3 @@ target_link_libraries(${TARGET_NAME}
# targets install
#
ov_install_static_lib(${TARGET_NAME} ${NPU_INTERNAL_COMPONENT})
-
-if(TARGET ze_loader)
- if(NOT BUILD_SHARED_LIBS)
- # Support link of static runtime in case system does not have ze_loader
- install(TARGETS ze_loader EXPORT OpenVINOTargets
- RUNTIME DESTINATION ${OV_CPACK_RUNTIMEDIR} COMPONENT ${NPU_PLUGIN_COMPONENT}
- ARCHIVE DESTINATION ${OV_CPACK_ARCHIVEDIR} COMPONENT ${NPU_PLUGIN_COMPONENT}
- LIBRARY DESTINATION ${OV_CPACK_LIBRARYDIR} COMPONENT ${NPU_PLUGIN_COMPONENT})
-
- install(TARGETS utils EXPORT OpenVINOTargets
- RUNTIME DESTINATION ${OV_CPACK_RUNTIMEDIR} COMPONENT ${NPU_PLUGIN_COMPONENT}
- ARCHIVE DESTINATION ${OV_CPACK_ARCHIVEDIR} COMPONENT ${NPU_PLUGIN_COMPONENT}
- LIBRARY DESTINATION ${OV_CPACK_LIBRARYDIR} COMPONENT ${NPU_PLUGIN_COMPONENT})
-
- # export to local tree to build against static build tree
- export(TARGETS ze_loader NAMESPACE openvino::
- APPEND FILE "${CMAKE_BINARY_DIR}/OpenVINOTargets.cmake")
-
- export(TARGETS utils NAMESPACE openvino::
- APPEND FILE "${CMAKE_BINARY_DIR}/OpenVINOTargets.cmake")
- endif()
-
- # Support tests to run with ze_loader
- install(TARGETS ze_loader
- RUNTIME DESTINATION tests COMPONENT tests EXCLUDE_FROM_ALL
- LIBRARY DESTINATION tests COMPONENT tests EXCLUDE_FROM_ALL)
-endif()
-
diff --git a/src/plugins/intel_npu/src/backend/include/zero_backend.hpp b/src/plugins/intel_npu/src/backend/include/zero_backend.hpp
index 68e4f943441..038c7c1d2d9 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_backend.hpp
+++ b/src/plugins/intel_npu/src/backend/include/zero_backend.hpp
@@ -9,7 +9,7 @@
#include "intel_npu/common/npu.hpp"
#include "intel_npu/utils/logger/logger.hpp"
-#include "zero_init.hpp"
+#include "intel_npu/utils/zero/zero_init.hpp"
namespace intel_npu {
class ZeroEngineBackend final : public IEngineBackend {
@@ -29,15 +29,14 @@ public:
bool isCommandQueueExtSupported() const override;
bool isLUIDExtSupported() const override;
+ const std::shared_ptr<ZeroInitStructsHolder>& getInitStruct() const;
+
void* getContext() const override;
- void* getDriverHandle() const;
- void* getDeviceHandle() const;
- ze_graph_dditable_ext_curr_t& getGraphDdiTable() const;
void updateInfo(const Config& config) override;
private:
- std::shared_ptr<ZeroInitStructsHolder> _instance;
+ std::shared_ptr<ZeroInitStructsHolder> _initStruct;
std::map<std::string, std::shared_ptr<IDevice>> _devices{};
Logger _logger;
diff --git a/src/plugins/intel_npu/src/backend/include/zero_device.hpp b/src/plugins/intel_npu/src/backend/include/zero_device.hpp
index e87a602613a..50f0d28ed21 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_device.hpp
+++ b/src/plugins/intel_npu/src/backend/include/zero_device.hpp
@@ -10,9 +10,9 @@
#include "intel_npu/common/icompiled_model.hpp"
#include "intel_npu/common/npu.hpp"
#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/zero/zero_init.hpp"
+#include "intel_npu/utils/zero/zero_types.hpp"
#include "openvino/runtime/intel_npu/remote_properties.hpp"
-#include "zero_init.hpp"
-#include "zero_types.hpp"
namespace intel_npu {
@@ -20,9 +20,6 @@ class ZeroDevice : public IDevice {
public:
ZeroDevice(const std::shared_ptr<ZeroInitStructsHolder>& initStructs);
- std::shared_ptr<IExecutor> createExecutor(const std::shared_ptr<const NetworkDescription>& networkDescription,
- const Config& config) override;
-
std::string getName() const override;
std::string getFullDeviceName() const override;
Uuid getUuid() const override;
@@ -36,7 +33,6 @@ public:
ov::device::Type getDeviceType() const override;
std::shared_ptr<SyncInferRequest> createInferRequest(const std::shared_ptr<const ICompiledModel>& compiledModel,
- const std::shared_ptr<IExecutor>& executor,
const Config& config) override;
void updateInfo(const Config& config) override {
log.setLevel(config.get<LOG_LEVEL>());
@@ -76,8 +72,6 @@ private:
{ov::element::u8, 0.f},
{ov::element::i8, 0.f}};
- uint32_t _group_ordinal;
-
Logger log;
};
} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/backend/include/zero_executor.hpp b/src/plugins/intel_npu/src/backend/include/zero_executor.hpp
deleted file mode 100644
index eeb96defc16..00000000000
--- a/src/plugins/intel_npu/src/backend/include/zero_executor.hpp
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright (C) 2018-2024 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#pragma once
-
-#include <ze_api.h>
-#include <ze_graph_ext.h>
-
-#include <mutex>
-
-#include "intel_npu/common/npu.hpp"
-#include "intel_npu/utils/logger/logger.hpp"
-#include "openvino/runtime/properties.hpp"
-#include "zero_init.hpp"
-#include "zero_wrappers.hpp"
-
-namespace intel_npu {
-
-class ZeroExecutor final : public IExecutor {
-public:
- ZeroExecutor(const std::shared_ptr<const ZeroInitStructsHolder>& initStructs,
- const std::shared_ptr<const NetworkDescription>& networkDescription,
- const Config& config,
- const uint32_t& group_ordinal);
-
- ZeroExecutor(const ZeroExecutor&) = delete;
- ZeroExecutor& operator=(const ZeroExecutor&) = delete;
-
- ~ZeroExecutor() override;
-
- struct ArgumentDescriptor {
- ze_graph_argument_properties_3_t info;
- uint32_t idx;
- };
-
- void setArgumentValue(uint32_t argi_, const void* argv_) const;
- void setWorkloadType(const ov::WorkloadType workloadType) const override;
- void mutexLock() const;
- void mutexUnlock() const;
- inline ze_graph_handle_t graph() const {
- return _graph;
- }
- inline std::shared_ptr<const ZeroInitStructsHolder> getInitStructs() const {
- return _initStructs;
- }
- inline const std::shared_ptr<const NetworkDescription>& getNetworkDesc() const {
- return _networkDesc;
- }
- inline const std::shared_ptr<CommandQueue>& getCommandQueue() const {
- return _command_queues;
- }
- inline const uint32_t& get_group_ordinal() const {
- return _group_ordinal;
- }
- inline const std::vector<ArgumentDescriptor>& get_input_descriptors() const {
- return _input_descriptors;
- }
- inline const std::vector<ArgumentDescriptor>& get_output_descriptors() const {
- return _output_descriptors;
- }
-
-private:
- void initialize_graph_through_command_list() const;
-
- const Config _config;
- Logger _logger;
-
- const std::shared_ptr<const ZeroInitStructsHolder> _initStructs;
- std::shared_ptr<const NetworkDescription> _networkDesc;
-
- ze_graph_dditable_ext_curr_t& _graph_ddi_table_ext;
-
- const uint32_t _group_ordinal;
-
- ze_graph_handle_t _graph = nullptr;
-
- std::vector<ArgumentDescriptor> _input_descriptors;
- std::vector<ArgumentDescriptor> _output_descriptors;
-
- std::shared_ptr<CommandQueue> _command_queues;
-
- mutable std::mutex _mutex;
-};
-
-} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/backend/include/zero_host_tensor.hpp b/src/plugins/intel_npu/src/backend/include/zero_host_tensor.hpp
index 52000930e2a..a214c8e2cb2 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_host_tensor.hpp
+++ b/src/plugins/intel_npu/src/backend/include/zero_host_tensor.hpp
@@ -5,8 +5,8 @@
#pragma once
#include "intel_npu/config/config.hpp"
+#include "intel_npu/utils/zero/zero_init.hpp"
#include "openvino/runtime/itensor.hpp"
-#include "zero_init.hpp"
#include "zero_remote_tensor.hpp"
namespace intel_npu {
diff --git a/src/plugins/intel_npu/src/backend/include/zero_infer_request.hpp b/src/plugins/intel_npu/src/backend/include/zero_infer_request.hpp
index 48aad52010a..31248b58225 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_infer_request.hpp
+++ b/src/plugins/intel_npu/src/backend/include/zero_infer_request.hpp
@@ -11,19 +11,17 @@
#include "intel_npu/common/sync_infer_request.hpp"
#include "intel_npu/utils/logger/logger.hpp"
#include "intel_npu/utils/zero/zero_utils.hpp"
-#include "zero_executor.hpp"
+#include "intel_npu/utils/zero/zero_wrappers.hpp"
#include "zero_pipeline.hpp"
#include "zero_profiling.hpp"
#include "zero_remote_tensor.hpp"
-#include "zero_wrappers.hpp"
namespace intel_npu {
class ZeroInferRequest final : public SyncInferRequest {
public:
- explicit ZeroInferRequest(const std::shared_ptr<ZeroInitStructsHolder>& backendPtr,
+ explicit ZeroInferRequest(const std::shared_ptr<ZeroInitStructsHolder>& initStructs,
const std::shared_ptr<const ICompiledModel>& compiledModel,
- const std::shared_ptr<const IExecutor>& executor,
const Config& config);
ov::SoPtr<ov::ITensor> get_tensor(const ov::Output<const ov::Node>& port) const override;
@@ -85,8 +83,7 @@ private:
std::vector<std::optional<TensorData>>& get_input_tensors_data(size_t index) const;
const std::shared_ptr<ZeroInitStructsHolder> _initStructs;
- const std::shared_ptr<const IExecutor> _executorPtr;
- const ZeroExecutor* _executor;
+ const std::shared_ptr<IGraph> _graph;
const Config _config;
Logger _logger;
diff --git a/src/plugins/intel_npu/src/backend/include/zero_memory.hpp b/src/plugins/intel_npu/src/backend/include/zero_memory.hpp
index 6ecbde0d546..992f409b86a 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_memory.hpp
+++ b/src/plugins/intel_npu/src/backend/include/zero_memory.hpp
@@ -11,7 +11,7 @@
#include <string>
#include "intel_npu/utils/logger/logger.hpp"
-#include "zero_init.hpp"
+#include "intel_npu/utils/zero/zero_init.hpp"
namespace {
diff --git a/src/plugins/intel_npu/src/backend/include/zero_pipeline.hpp b/src/plugins/intel_npu/src/backend/include/zero_pipeline.hpp
index 62c8481d28a..92a473a9fc4 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_pipeline.hpp
+++ b/src/plugins/intel_npu/src/backend/include/zero_pipeline.hpp
@@ -4,11 +4,11 @@
#pragma once
+#include "intel_npu/common/igraph.hpp"
#include "intel_npu/utils/zero/zero_utils.hpp"
-#include "zero_executor.hpp"
+#include "intel_npu/utils/zero/zero_wrappers.hpp"
#include "zero_memory.hpp"
#include "zero_profiling.hpp"
-#include "zero_wrappers.hpp"
namespace intel_npu {
@@ -21,13 +21,15 @@ struct TensorData {
struct Pipeline {
public:
Pipeline(const Config& config,
- const std::shared_ptr<const IExecutor>& executorPtr,
+ const std::shared_ptr<ZeroInitStructsHolder>& initStructs,
+ const std::shared_ptr<IGraph>& graph,
zeroProfiling::ProfilingPool& profiling_pool,
zeroProfiling::ProfilingQuery& profiling_query,
std::shared_ptr<zeroProfiling::NpuInferProfiling> npu_profiling,
const std::vector<std::vector<std::optional<TensorData>>>& inputTensorsData,
const std::vector<std::optional<TensorData>>& outputTensorsData,
- const size_t numberOfCommandLists);
+ size_t numberOfCommandLists,
+ uint32_t group_ordinal);
Pipeline(const Pipeline&) = delete;
Pipeline& operator=(const Pipeline&) = delete;
@@ -42,8 +44,7 @@ public:
protected:
const Config _config;
- const ZeroExecutor* _executor;
- CommandQueue& _command_queue;
+ std::shared_ptr<CommandQueue> _command_queue;
std::vector<std::unique_ptr<CommandList>> _command_lists;
std::vector<std::unique_ptr<Fence>> _fences;
EventPool _event_pool;
diff --git a/src/plugins/intel_npu/src/backend/include/zero_profiling.hpp b/src/plugins/intel_npu/src/backend/include/zero_profiling.hpp
index 505a7f0185e..17e263a7aaf 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_profiling.hpp
+++ b/src/plugins/intel_npu/src/backend/include/zero_profiling.hpp
@@ -12,8 +12,8 @@
#include "intel_npu/config/compiler.hpp"
#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/zero/zero_types.hpp"
#include "openvino/runtime/profiling_info.hpp"
-#include "zero_types.hpp"
namespace intel_npu {
namespace zeroProfiling {
diff --git a/src/plugins/intel_npu/src/backend/include/zero_remote_tensor.hpp b/src/plugins/intel_npu/src/backend/include/zero_remote_tensor.hpp
index 0211bd5bd08..5b08643704b 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_remote_tensor.hpp
+++ b/src/plugins/intel_npu/src/backend/include/zero_remote_tensor.hpp
@@ -9,8 +9,8 @@
#include <string>
#include "intel_npu/common/remote_tensor.hpp"
+#include "intel_npu/utils/zero/zero_init.hpp"
#include "openvino/runtime/intel_npu/remote_properties.hpp"
-#include "zero_init.hpp"
namespace intel_npu {
diff --git a/src/plugins/intel_npu/src/backend/src/zero_backend.cpp b/src/plugins/intel_npu/src/backend/src/zero_backend.cpp
index 86af62d414b..55aaad102e8 100644
--- a/src/plugins/intel_npu/src/backend/src/zero_backend.cpp
+++ b/src/plugins/intel_npu/src/backend/src/zero_backend.cpp
@@ -14,31 +14,31 @@ namespace intel_npu {
ZeroEngineBackend::ZeroEngineBackend(const Config& config) : _logger("ZeroEngineBackend", Logger::global().level()) {
_logger.debug("ZeroEngineBackend - initialize started");
- _instance = std::make_shared<ZeroInitStructsHolder>();
+ _initStruct = std::make_shared<ZeroInitStructsHolder>();
- auto device = std::make_shared<ZeroDevice>(_instance);
+ auto device = std::make_shared<ZeroDevice>(_initStruct);
_devices.emplace(std::make_pair(device->getName(), device));
_logger.debug("ZeroEngineBackend - initialize completed");
}
uint32_t ZeroEngineBackend::getDriverVersion() const {
- return _instance->getDriverVersion();
+ return _initStruct->getDriverVersion();
}
uint32_t ZeroEngineBackend::getGraphExtVersion() const {
- return _instance->getGraphDdiTable().version();
+ return _initStruct->getGraphDdiTable().version();
}
bool ZeroEngineBackend::isBatchingSupported() const {
- return _instance->isExtensionSupported("ZE_extension_graph_1_6", ZE_MAKE_VERSION(1, 6));
+ return _initStruct->isExtensionSupported("ZE_extension_graph_1_6", ZE_MAKE_VERSION(1, 6));
}
bool ZeroEngineBackend::isCommandQueueExtSupported() const {
- return _instance->isExtensionSupported(std::string(ZE_COMMAND_QUEUE_NPU_EXT_NAME), ZE_MAKE_VERSION(1, 0));
+ return _initStruct->isExtensionSupported(std::string(ZE_COMMAND_QUEUE_NPU_EXT_NAME), ZE_MAKE_VERSION(1, 0));
}
bool ZeroEngineBackend::isLUIDExtSupported() const {
- return _instance->isExtensionSupported(std::string(ZE_DEVICE_LUID_EXT_NAME), ZE_MAKE_VERSION(1, 0));
+ return _initStruct->isExtensionSupported(std::string(ZE_DEVICE_LUID_EXT_NAME), ZE_MAKE_VERSION(1, 0));
}
ZeroEngineBackend::~ZeroEngineBackend() = default;
@@ -69,19 +69,11 @@ const std::vector<std::string> ZeroEngineBackend::getDeviceNames() const {
}
void* ZeroEngineBackend::getContext() const {
- return _instance->getContext();
+ return _initStruct->getContext();
}
-void* ZeroEngineBackend::getDriverHandle() const {
- return _instance->getDriver();
-}
-
-void* ZeroEngineBackend::getDeviceHandle() const {
- return _instance->getDevice();
-}
-
-ze_graph_dditable_ext_curr_t& ZeroEngineBackend::getGraphDdiTable() const {
- return _instance->getGraphDdiTable();
+const std::shared_ptr<ZeroInitStructsHolder>& ZeroEngineBackend::getInitStruct() const {
+ return _initStruct;
}
void ZeroEngineBackend::updateInfo(const Config& config) {
diff --git a/src/plugins/intel_npu/src/backend/src/zero_device.cpp b/src/plugins/intel_npu/src/backend/src/zero_device.cpp
index 58bcd0eb7cc..6e16dde3b12 100644
--- a/src/plugins/intel_npu/src/backend/src/zero_device.cpp
+++ b/src/plugins/intel_npu/src/backend/src/zero_device.cpp
@@ -7,7 +7,6 @@
#include "intel_npu/common/itt.hpp"
#include "intel_npu/utils/zero/zero_api.hpp"
#include "intel_npu/utils/zero/zero_utils.hpp"
-#include "zero_executor.hpp"
#include "zero_host_tensor.hpp"
#include "zero_infer_request.hpp"
#include "zero_remote_tensor.hpp"
@@ -64,38 +63,6 @@ ZeroDevice::ZeroDevice(const std::shared_ptr<ZeroInitStructsHolder>& initStructs
device_gops[ov::element::i8] = gops;
device_gops[ov::element::f16] = 0.5f * gops;
}
-
- std::vector<ze_command_queue_group_properties_t> command_group_properties;
- uint32_t command_queue_group_count = 0;
- // Discover all command queue groups
- THROW_ON_FAIL_FOR_LEVELZERO(
- "zeDeviceGetCommandQueueGroupProperties",
- zeDeviceGetCommandQueueGroupProperties(_initStructs->getDevice(), &command_queue_group_count, nullptr));
-
- log.debug("ZeroDevice::ZeroDevice - resize command_queue_group_count");
- command_group_properties.resize(command_queue_group_count);
-
- for (auto& prop : command_group_properties) {
- prop.stype = ZE_STRUCTURE_TYPE_COMMAND_QUEUE_GROUP_PROPERTIES;
- prop.pNext = nullptr;
- }
-
- THROW_ON_FAIL_FOR_LEVELZERO("zeDeviceGetCommandQueueGroupProperties",
- zeDeviceGetCommandQueueGroupProperties(_initStructs->getDevice(),
- &command_queue_group_count,
- command_group_properties.data()));
-
- // Find the corresponding command queue group.
- log.debug("ZeroDevice::ZeroDevice - findGroupOrdinal");
- _group_ordinal = zeroUtils::findGroupOrdinal(command_group_properties, device_properties);
- log.debug("ZeroDevice::ZeroDevice - init completed");
-}
-
-std::shared_ptr<IExecutor> ZeroDevice::createExecutor(
- const std::shared_ptr<const NetworkDescription>& networkDescription,
- const Config& config) {
- OV_ITT_SCOPED_TASK(itt::domains::LevelZeroBackend, "Device::createExecutor");
- return std::make_shared<ZeroExecutor>(_initStructs, networkDescription, config, _group_ordinal);
}
std::string ZeroDevice::getName() const {
@@ -205,9 +172,8 @@ ov::device::Type ZeroDevice::getDeviceType() const {
std::shared_ptr<SyncInferRequest> ZeroDevice::createInferRequest(
const std::shared_ptr<const ICompiledModel>& compiledModel,
- const std::shared_ptr<IExecutor>& executor,
const Config& config) {
- return std::make_shared<ZeroInferRequest>(_initStructs, compiledModel, executor, config);
+ return std::make_shared<ZeroInferRequest>(_initStructs, compiledModel, config);
}
ov::SoPtr<ov::IRemoteTensor> ZeroDevice::createRemoteTensor(std::shared_ptr<ov::IRemoteContext> context,
diff --git a/src/plugins/intel_npu/src/backend/src/zero_executor.cpp b/src/plugins/intel_npu/src/backend/src/zero_executor.cpp
deleted file mode 100644
index 32da2b2e0e4..00000000000
--- a/src/plugins/intel_npu/src/backend/src/zero_executor.cpp
+++ /dev/null
@@ -1,187 +0,0 @@
-// Copyright (C) 2018-2024 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#include "zero_executor.hpp"
-
-#include <ze_api.h>
-
-#include <functional>
-#include <iostream>
-#include <sstream>
-#include <string>
-
-#include "intel_npu/common/itt.hpp"
-#include "intel_npu/config/common.hpp"
-#include "intel_npu/prefix.hpp"
-#include "intel_npu/utils/zero/zero_utils.hpp"
-#include "openvino/runtime/properties.hpp"
-#include "ze_command_queue_npu_ext.h"
-#include "zero_device.hpp"
-
-using namespace intel_npu;
-
-ZeroExecutor::ZeroExecutor(const std::shared_ptr<const ZeroInitStructsHolder>& initStructs,
- const std::shared_ptr<const NetworkDescription>& networkDescription,
- const Config& config,
- const uint32_t& group_ordinal)
- : _config(config),
- _logger("Graph", _config.get<LOG_LEVEL>()),
- _initStructs(initStructs),
- _networkDesc(networkDescription),
- _graph_ddi_table_ext(_initStructs->getGraphDdiTable()),
- _group_ordinal(group_ordinal),
- _command_queues{std::make_shared<CommandQueue>(_initStructs->getDevice(),
- _initStructs->getContext(),
- zeroUtils::toZeQueuePriority(_config.get<MODEL_PRIORITY>()),
- _initStructs->getCommandQueueDdiTable(),
- _config,
- group_ordinal)} {
- _logger.debug("ZeroExecutor::ZeroExecutor - create graph");
- OV_ITT_TASK_CHAIN(ZERO_EXECUTOR_GRAPH, itt::domains::LevelZeroBackend, "Executor::ZeroExecutor", "graphCreate");
-
- // _graph is a nullptr for CIP path, a new handle will be obtained from the driver based on the given
- // compiledNetwork _graph gets (reuses) graphHandle from the compiler for CID path
- if (_networkDesc->metadata.graphHandle == nullptr) {
- _logger.debug("create graph handle on executor");
- ze_graph_desc_t desc{ZE_STRUCTURE_TYPE_GRAPH_DESC_PROPERTIES,
- nullptr,
- ZE_GRAPH_FORMAT_NATIVE,
- _networkDesc->compiledNetwork.size(),
- _networkDesc->compiledNetwork.data(),
- nullptr};
- ze_result_t result =
- _graph_ddi_table_ext.pfnCreate(_initStructs->getContext(), _initStructs->getDevice(), &desc, &_graph);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnCreate", result, _graph_ddi_table_ext);
-
- } else {
- _logger.debug("reuse graph handle created from compiler");
- _graph = static_cast<ze_graph_handle_t>(_networkDesc->metadata.graphHandle);
- }
-
- OV_ITT_TASK_NEXT(ZERO_EXECUTOR_GRAPH, "pfnGetProperties");
- _logger.debug("performing pfnGetProperties");
- ze_graph_properties_t props{};
- props.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;
-
- ze_result_t result = _graph_ddi_table_ext.pfnGetProperties(_graph, &props);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetProperties", result, _graph_ddi_table_ext);
-
- auto targetDriverExtVersion = _graph_ddi_table_ext.version();
- if (targetDriverExtVersion <= ZE_GRAPH_EXT_VERSION_1_1) {
- OPENVINO_THROW("Incompatibility between the NPU plugin and driver! The driver version is too old, please "
- "update the driver version");
- }
-
- OV_ITT_TASK_NEXT(ZERO_EXECUTOR_GRAPH, "pfnGetArgumentProperties3");
- _logger.debug("performing pfnGetArgumentProperties3");
- for (uint32_t index = 0; index < props.numGraphArgs; ++index) {
- ze_graph_argument_properties_3_t arg3{};
- arg3.stype = ZE_STRUCTURE_TYPE_GRAPH_ARGUMENT_PROPERTIES;
- ze_result_t result = _graph_ddi_table_ext.pfnGetArgumentProperties3(_graph, index, &arg3);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetArgumentProperties3", result, _graph_ddi_table_ext);
-
- if (arg3.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT) {
- _input_descriptors.push_back(ArgumentDescriptor{arg3, index});
- } else {
- _output_descriptors.push_back(ArgumentDescriptor{arg3, index});
- }
- }
-
- if (_graph_ddi_table_ext.version() < ZE_GRAPH_EXT_VERSION_1_8) {
- initialize_graph_through_command_list();
- } else {
- ze_graph_properties_2_t properties = {};
- properties.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;
- _graph_ddi_table_ext.pfnGetProperties2(_graph, &properties);
-
- if (properties.initStageRequired & ZE_GRAPH_STAGE_INITIALIZE) {
- OV_ITT_TASK_NEXT(ZERO_EXECUTOR_GRAPH, "pfnGraphInitialize");
- _graph_ddi_table_ext.pfnGraphInitialize(_graph);
- }
-
- if (properties.initStageRequired & ZE_GRAPH_STAGE_COMMAND_LIST_INITIALIZE) {
- initialize_graph_through_command_list();
- }
- }
-
- if (config.has<WORKLOAD_TYPE>()) {
- setWorkloadType(config.get<WORKLOAD_TYPE>());
- }
-}
-
-void ZeroExecutor::initialize_graph_through_command_list() const {
- OV_ITT_TASK_CHAIN(ZERO_EXECUTOR_GRAPH,
- itt::domains::LevelZeroBackend,
- "Executor::ZeroExecutor",
- "initialize_graph_through_command_list");
-
- _logger.debug("ZeroExecutor::ZeroExecutor init start - create graph_command_list");
- OV_ITT_SCOPED_TASK(itt::domains::LevelZeroBackend, "Executor::ZeroExecutor");
- CommandList graph_command_list(_initStructs->getDevice(),
- _initStructs->getContext(),
- _graph_ddi_table_ext,
- _config,
- _group_ordinal);
- _logger.debug("ZeroExecutor::ZeroExecutor - create graph_command_queue");
- CommandQueue graph_command_queue(_initStructs->getDevice(),
- _initStructs->getContext(),
- ZE_COMMAND_QUEUE_PRIORITY_NORMAL,
- _initStructs->getCommandQueueDdiTable(),
- _config,
- _group_ordinal);
- _logger.debug("ZeroExecutor::ZeroExecutor - create fence");
- Fence fence(graph_command_queue, _config);
-
- OV_ITT_TASK_NEXT(ZERO_EXECUTOR_GRAPH, "appendGraphInitialize");
- _logger.debug("ZeroExecutor::ZeroExecutor - performing appendGraphInitialize");
- graph_command_list.appendGraphInitialize(_graph);
- _logger.debug("ZeroExecutor::ZeroExecutor - closing graph command list");
- graph_command_list.close();
-
- OV_ITT_TASK_NEXT(ZERO_EXECUTOR_GRAPH, "queue_execute");
- _logger.debug("ZeroExecutor::ZeroExecutor - performing executeCommandList");
- graph_command_queue.executeCommandList(graph_command_list, fence);
- _logger.debug("ZeroExecutor::ZeroExecutor - performing hostSynchronize");
- fence.hostSynchronize();
- _logger.debug("ZeroExecutor::ZeroExecutor - hostSynchronize completed");
-}
-
-void ZeroExecutor::setWorkloadType(const ov::WorkloadType workloadType) const {
- ze_command_queue_workload_type_t zeWorkloadType;
- switch (workloadType) {
- case ov::WorkloadType::DEFAULT:
- zeWorkloadType = ze_command_queue_workload_type_t::ZE_WORKLOAD_TYPE_DEFAULT;
- break;
- case ov::WorkloadType::EFFICIENT:
- zeWorkloadType = ze_command_queue_workload_type_t::ZE_WORKLOAD_TYPE_BACKGROUND;
- break;
- default:
- OPENVINO_THROW("Unknown value for WorkloadType!");
- }
-
- _command_queues->setWorkloadType(zeWorkloadType);
-}
-
-void ZeroExecutor::setArgumentValue(uint32_t argi_, const void* argv_) const {
- ze_result_t result = _graph_ddi_table_ext.pfnSetArgumentValue(_graph, argi_, argv_);
- if (ZE_RESULT_SUCCESS != result) {
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("zeGraphSetArgumentValue", result, _graph_ddi_table_ext);
- }
-}
-
-void ZeroExecutor::mutexLock() const {
- _mutex.lock();
-}
-
-void ZeroExecutor::mutexUnlock() const {
- _mutex.unlock();
-}
-
-ZeroExecutor::~ZeroExecutor() {
- _logger.debug("~ZeroExecutor() - pfnDestroy _graph ");
- auto result = _graph_ddi_table_ext.pfnDestroy(_graph);
- if (ZE_RESULT_SUCCESS != result) {
- _logger.error("_graph_ddi_table_ext.pfnDestroy failed %#X", uint64_t(result));
- }
-}
diff --git a/src/plugins/intel_npu/src/backend/src/zero_infer_request.cpp b/src/plugins/intel_npu/src/backend/src/zero_infer_request.cpp
index dd2629372dc..1c5ceecfac1 100644
--- a/src/plugins/intel_npu/src/backend/src/zero_infer_request.cpp
+++ b/src/plugins/intel_npu/src/backend/src/zero_infer_request.cpp
@@ -31,8 +31,7 @@ constexpr bool OUTPUT = false;
* @param ioDescriptor The OpenVINO API specific I/O descriptor which shall be compared.
* @param zeDescriptor The Level Zero specific structure used for comparison.
*/
-void check_level_zero_attributes_match(const IODescriptor& ioDescriptor,
- const ZeroExecutor::ArgumentDescriptor& zeDescriptor) {
+void check_level_zero_attributes_match(const IODescriptor& ioDescriptor, const ArgumentDescriptor& zeDescriptor) {
std::string zeDescriptorName = zeDescriptor.info.name;
if (isStateInputName(zeDescriptorName)) {
@@ -158,38 +157,35 @@ std::optional<size_t> ZeroInferRequest::get_batch_size(const NetworkMetadata& me
//------------------------------------------------------------------------------
ZeroInferRequest::ZeroInferRequest(const std::shared_ptr<ZeroInitStructsHolder>& initStructs,
const std::shared_ptr<const ICompiledModel>& compiledModel,
- const std::shared_ptr<const IExecutor>& executor,
const Config& config)
: SyncInferRequest(compiledModel, config),
_initStructs(initStructs),
- _executorPtr(executor),
- _executor(static_cast<const ZeroExecutor*>(_executorPtr.get())),
+ _graph(compiledModel->get_graph()),
_config(config),
_logger("ZeroInferRequest", config.get<LOG_LEVEL>()),
_levelZeroInputTensors(_metadata.inputs.size(), std::vector<std::shared_ptr<ov::ITensor>>(1, nullptr)),
_levelZeroOutputTensors(_metadata.outputs.size(), nullptr),
_inputTensorsData(_metadata.inputs.size(), std::vector<std::optional<TensorData>>(1, std::nullopt)),
_outputTensorsData(_metadata.outputs.size(), std::nullopt),
- _profilingPool(_executor->graph(), zeroProfiling::POOL_SIZE, _executor->getInitStructs()->getProfilingDdiTable()),
- _profilingQuery(0,
- _executor->getInitStructs()->getDevice(),
- _executor->getInitStructs()->getProfilingDdiTable()) {
+ _profilingPool(static_cast<ze_graph_handle_t>(_graph->get_handle()),
+ zeroProfiling::POOL_SIZE,
+ _initStructs->getProfilingDdiTable()),
+ _profilingQuery(0, _initStructs->getDevice(), _initStructs->getProfilingDdiTable()) {
_logger.debug("ZeroInferRequest::ZeroInferRequest - SyncInferRequest");
- const std::vector<ZeroExecutor::ArgumentDescriptor>& executorInputDescriptors = _executor->get_input_descriptors();
- const std::vector<ZeroExecutor::ArgumentDescriptor>& executorOutputDescriptors =
- _executor->get_output_descriptors();
+ const std::vector<ArgumentDescriptor>& executorInputDescriptors = _graph->get_input_descriptors();
+ const std::vector<ArgumentDescriptor>& executorOutputDescriptors = _graph->get_output_descriptors();
auto proftype = config.get<PROFILING_TYPE>();
if (proftype == ov::intel_npu::ProfilingType::INFER) {
_logger.debug("ZeroInferRequest::ZeroInferRequest - profiling type == ov::intel_npu::ProfilingType::INFER");
- _npuProfiling = std::make_shared<zeroProfiling::NpuInferProfiling>(_executor->getInitStructs()->getContext(),
- _executor->getInitStructs()->getDevice(),
+ _npuProfiling = std::make_shared<zeroProfiling::NpuInferProfiling>(_initStructs->getContext(),
+ _initStructs->getDevice(),
_config.get<LOG_LEVEL>());
}
_properties.stype = ZE_STRUCTURE_TYPE_DEVICE_PROPERTIES;
THROW_ON_FAIL_FOR_LEVELZERO("zeDeviceGetProperties",
- zeDeviceGetProperties(_executor->getInitStructs()->getDevice(), &_properties));
+ zeDeviceGetProperties(_initStructs->getDevice(), &_properties));
_outputAllocator = std::make_shared<const zeroMemory::HostMemAllocator>(_initStructs);
_inputAllocator =
@@ -278,17 +274,24 @@ void ZeroInferRequest::create_pipeline() {
_levelZeroOutputTensors.at(outputIndex)->get_byte_size()});
}
+ // Find the corresponding command queue group.
+ _logger.debug("ZeroDevice::ZeroDevice - findGroupOrdinal");
+ auto groupOrdinal = zeroUtils::findGroupOrdinal(_initStructs->getDevice(), _properties);
+ _logger.debug("ZeroDevice::ZeroDevice - init completed");
+
_logger.debug("ZeroInferRequest::create_pipeline - constructing pipeline");
- // Construct pipeline
+ // Construct pipeline
_pipeline = std::make_unique<Pipeline>(_config,
- _executorPtr,
+ _initStructs,
+ _graph,
_profilingPool,
_profilingQuery,
_npuProfiling,
_inputTensorsData,
_outputTensorsData,
- _numberOfCommandLists);
+ _numberOfCommandLists,
+ groupOrdinal);
_logger.debug("ZeroInferRequest::create_pipeline - SyncInferRequest completed");
}
@@ -338,8 +341,8 @@ void ZeroInferRequest::set_tensor_data(const std::shared_ptr<ov::ITensor> tensor
OV_ITT_TASK_NEXT(ZERO_SET_TENSOR, "updateCommandList");
_pipeline->updateCommandList(*tensorsData,
- isInput ? _executor->get_input_descriptors().at(index).idx
- : _executor->get_output_descriptors().at(index).idx);
+ isInput ? _graph->get_input_descriptors().at(index).idx
+ : _graph->get_output_descriptors().at(index).idx);
}
}
}
@@ -370,9 +373,9 @@ void ZeroInferRequest::set_remote_tensor_data(const std::shared_ptr<ZeroRemoteTe
_logger.debug("ZeroInferRequest::infer_async - update command list");
OV_ITT_TASK_NEXT(ZERO_SET_REMOTE_TENSOR, "updateCommandList");
- _pipeline->updateCommandList(*tensorsData,
- isInput ? _executor->get_input_descriptors().at(index).idx
- : _executor->get_output_descriptors().at(index).idx);
+ _pipeline->updateCommandList(
+ *tensorsData,
+ isInput ? _graph->get_input_descriptors().at(index).idx : _graph->get_output_descriptors().at(index).idx);
}
}
@@ -390,13 +393,17 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const
if (foundPort.is_input()) {
if (get_user_input(foundPort.idx)._ptr == tensor._ptr) {
// Got set_tensor with the same object - do nothing
+ _logger.debug("ZeroInferRequest::set_tensor - got the same tensor, do nothing");
return;
}
if (is_batched_input(foundPort.idx)) {
// resize vector size to 1 if set_tensor is called after set_tensors
get_input_tensors_data(foundPort.idx).resize(1);
+ get_input_tensors_data(foundPort.idx).shrink_to_fit();
get_level_zero_inputs(foundPort.idx).resize(1);
+ get_level_zero_inputs(foundPort.idx).shrink_to_fit();
get_user_inputs(foundPort.idx).resize(1);
+ get_user_inputs(foundPort.idx).shrink_to_fit();
}
get_user_input(foundPort.idx) = tensor;
@@ -485,7 +492,7 @@ void ZeroInferRequest::set_tensors(const ov::Output<const ov::Node>& port,
if (_pipelineIsCreated) {
OV_ITT_TASK_NEXT(SET_TENSORS, "updateCommandList");
_pipeline->updateCommandList(*get_input_tensor_data(foundPort.idx, i),
- _executor->get_input_descriptors().at(foundPort.idx).idx,
+ _graph->get_input_descriptors().at(foundPort.idx).idx,
i);
}
}
@@ -537,14 +544,16 @@ void ZeroInferRequest::infer_async() {
_logger.debug("InferRequest::infer_async started");
OV_ITT_TASK_CHAIN(ZERO_INFER, itt::domains::LevelZeroBackend, "infer_async", "start");
- _executor->mutexLock();
- if (!_pipelineIsCreated) {
- OV_ITT_TASK_NEXT(ZERO_INFER, "create_pipeline");
- create_pipeline();
+ {
+ std::lock_guard<std::mutex> lock(_graph->get_mutex());
- _pipelineIsCreated = true;
+ if (!_pipelineIsCreated) {
+ OV_ITT_TASK_NEXT(ZERO_INFER, "create_pipeline");
+ create_pipeline();
+
+ _pipelineIsCreated = true;
+ }
}
- _executor->mutexUnlock();
size_t inputIndex = 0;
for (const auto& userTensor : _userInputTensors) {
@@ -740,12 +749,9 @@ std::vector<ov::ProfilingInfo> ZeroInferRequest::get_profiling_info() const {
if (compilerType == ov::intel_npu::CompilerType::MLIR) {
// For plugin compiler retreive raw profiling data from backend and delegate
// processing to the compiler
- const auto& networkDesc = compiledModel.get_network_description();
- const auto& compiler = compiledModel.get_compiler();
- const auto& blob = networkDesc->compiledNetwork;
auto profData = get_raw_profiling_data();
_logger.debug("InferRequest::get_profiling_info complete with compiler->process_profiling_output().");
- return compiler->process_profiling_output(profData, blob, compilerConfig);
+ return _graph->process_profiling_output(profData, compilerConfig);
} else {
auto proftype = _config.get<PROFILING_TYPE>();
if (proftype == ov::intel_npu::ProfilingType::INFER) {
diff --git a/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp b/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp
index 009eee6541e..34eb71eaf11 100644
--- a/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp
+++ b/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp
@@ -11,25 +11,25 @@
#include "intel_npu/prefix.hpp"
#include "intel_npu/utils/logger/logger.hpp"
#include "intel_npu/utils/zero/zero_api.hpp"
-#include "zero_types.hpp"
+#include "intel_npu/utils/zero/zero_types.hpp"
namespace intel_npu {
Pipeline::Pipeline(const Config& config,
- const std::shared_ptr<const IExecutor>& executorPtr,
+ const std::shared_ptr<ZeroInitStructsHolder>& initStructs,
+ const std::shared_ptr<IGraph>& graph,
zeroProfiling::ProfilingPool& profiling_pool,
zeroProfiling::ProfilingQuery& profiling_query,
std::shared_ptr<zeroProfiling::NpuInferProfiling> npu_profiling,
const std::vector<std::vector<std::optional<TensorData>>>& inputTensorsData,
const std::vector<std::optional<TensorData>>& outputTensorsData,
- const size_t numberOfCommandLists)
+ size_t numberOfCommandLists,
+ uint32_t group_ordinal)
: _config(config),
- _executor(static_cast<const ZeroExecutor*>(executorPtr.get())),
- _command_queue(*_executor->getCommandQueue()),
- _event_pool{_executor->getInitStructs()->getDevice(),
- _executor->getInitStructs()->getContext(),
- numberOfCommandLists ? static_cast<uint32_t>(numberOfCommandLists) : 1,
- _config},
+ _command_queue(graph->get_command_queue()),
+ _event_pool{initStructs->getDevice(),
+ initStructs->getContext(),
+ numberOfCommandLists ? static_cast<uint32_t>(numberOfCommandLists) : 1},
_npu_profiling(std::move(npu_profiling)),
_logger("Pipeline", _config.get<LOG_LEVEL>()) {
OV_ITT_SCOPED_TASK(itt::domains::LevelZeroBackend, "Zero_infer_request::Pipeline::Pipeline");
@@ -45,38 +45,37 @@ Pipeline::Pipeline(const Config& config,
_logger.debug("Pipeline - emplace_back _event_pool and _command_queue");
for (size_t i = 0; i < numberOfCommandLists; i++) {
_command_lists.emplace_back(
- std::make_unique<CommandList>(_executor->getInitStructs()->getDevice(),
- _executor->getInitStructs()->getContext(),
- _executor->getInitStructs()->getGraphDdiTable(),
- _config,
- _executor->get_group_ordinal(),
- _executor->getInitStructs()->getMutableCommandListVersion() ? true : false));
- _events.emplace_back(std::make_unique<Event>(_event_pool.handle(), static_cast<uint32_t>(i), _config));
- _fences.emplace_back(std::make_unique<Fence>(_command_queue, _config));
+ std::make_unique<CommandList>(initStructs->getDevice(),
+ initStructs->getContext(),
+ initStructs->getGraphDdiTable(),
+ group_ordinal,
+ initStructs->getMutableCommandListVersion() ? true : false));
+ _events.emplace_back(std::make_unique<Event>(_event_pool.handle(), static_cast<uint32_t>(i)));
+ _fences.emplace_back(std::make_unique<Fence>(*_command_queue));
}
for (size_t i = 0; i < numberOfCommandLists; i++) {
size_t ioIndex = 0;
- for (const auto& desc : _executor->get_input_descriptors()) {
+ for (const auto& desc : graph->get_input_descriptors()) {
if (inputTensorsData.at(ioIndex).size() > 1) {
- _executor->setArgumentValue(desc.idx, inputTensorsData.at(ioIndex).at(i)->mem);
+ graph->set_argument_value(desc.idx, inputTensorsData.at(ioIndex).at(i)->mem);
++ioIndex;
continue;
}
- _executor->setArgumentValue(desc.idx,
- static_cast<unsigned char*>(inputTensorsData.at(ioIndex).at(0)->mem) +
- (i * inputTensorsData.at(ioIndex).at(0)->size) / numberOfCommandLists);
+ graph->set_argument_value(desc.idx,
+ static_cast<unsigned char*>(inputTensorsData.at(ioIndex).at(0)->mem) +
+ (i * inputTensorsData.at(ioIndex).at(0)->size) / numberOfCommandLists);
++ioIndex;
}
ioIndex = 0;
- for (const auto& desc : _executor->get_output_descriptors()) {
- _executor->setArgumentValue(desc.idx,
- static_cast<unsigned char*>(outputTensorsData.at(ioIndex)->mem) +
- (i * outputTensorsData.at(ioIndex)->size) / numberOfCommandLists);
+ for (const auto& desc : graph->get_output_descriptors()) {
+ graph->set_argument_value(desc.idx,
+ static_cast<unsigned char*>(outputTensorsData.at(ioIndex)->mem) +
+ (i * outputTensorsData.at(ioIndex)->size) / numberOfCommandLists);
++ioIndex;
}
@@ -86,7 +85,8 @@ Pipeline::Pipeline(const Config& config,
_command_lists.at(i)->appendNpuTimestamp(reinterpret_cast<uint64_t*>(_npu_profiling->npu_ts_infer_start));
}
- _command_lists.at(i)->appendGraphExecute(_executor->graph(), profiling_query.getHandle());
+ _command_lists.at(i)->appendGraphExecute(static_cast<ze_graph_handle_t>(graph->get_handle()),
+ profiling_query.getHandle());
/// append timestamp command if feature was activated
if (_npu_profiling != nullptr) {
@@ -108,11 +108,11 @@ void Pipeline::push() {
_logger.debug("Pipeline - push() started");
for (size_t i = 0; i < _command_lists.size(); ++i) {
- OV_ITT_TASK_CHAIN(ZERO_EXECUTOR_IP_PUSH, itt::domains::LevelZeroBackend, "Pipeline", "push");
+ OV_ITT_TASK_CHAIN(ZERO_PIPELINE_IP_PUSH, itt::domains::LevelZeroBackend, "Pipeline", "push");
if (sync_output_with_fences_) {
- _command_queue.executeCommandList(*_command_lists.at(i), *_fences.at(i));
+ _command_queue->executeCommandList(*_command_lists.at(i), *_fences.at(i));
} else {
- _command_queue.executeCommandList(*_command_lists.at(i));
+ _command_queue->executeCommandList(*_command_lists.at(i));
}
}
@@ -121,7 +121,7 @@ void Pipeline::push() {
void Pipeline::pull() {
_logger.debug("Pipeline - pull() started");
- OV_ITT_TASK_CHAIN(ZERO_EXECUTOR_IP_PULL, itt::domains::LevelZeroBackend, "Pipeline", "pull");
+ OV_ITT_TASK_CHAIN(ZERO_PIPELINE_IP_PULL, itt::domains::LevelZeroBackend, "Pipeline", "pull");
for (size_t i = 0; i < _command_lists.size(); ++i) {
if (sync_output_with_fences_) {
diff --git a/src/plugins/intel_npu/src/common/CMakeLists.txt b/src/plugins/intel_npu/src/common/CMakeLists.txt
index 2d1f5d9cbb3..1aa93cce1bc 100644
--- a/src/plugins/intel_npu/src/common/CMakeLists.txt
+++ b/src/plugins/intel_npu/src/common/CMakeLists.txt
@@ -20,7 +20,7 @@ target_link_libraries(${TARGET_NAME}
PUBLIC
openvino::npu_al
openvino::npu_logger_utils
- openvino::runtime::dev
+ openvino::npu_zero_utils
)
set_target_properties(${TARGET_NAME} PROPERTIES INTERPROCEDURAL_OPTIMIZATION_RELEASE ${ENABLE_LTO})
diff --git a/src/plugins/intel_npu/src/common/include/intel_npu/common/icompiled_model.hpp b/src/plugins/intel_npu/src/common/include/intel_npu/common/icompiled_model.hpp
index eb6a3de57e4..19023a1fca8 100644
--- a/src/plugins/intel_npu/src/common/include/intel_npu/common/icompiled_model.hpp
+++ b/src/plugins/intel_npu/src/common/include/intel_npu/common/icompiled_model.hpp
@@ -7,8 +7,8 @@
#include <memory>
#include <vector>
+#include "intel_npu/common/igraph.hpp"
#include "intel_npu/config/common.hpp"
-#include "intel_npu/icompiler.hpp"
#include "openvino/runtime/icompiled_model.hpp"
namespace intel_npu {
@@ -17,17 +17,10 @@ class ICompiledModel : public ov::ICompiledModel {
public:
using ov::ICompiledModel::ICompiledModel;
- virtual const std::shared_ptr<const NetworkDescription>& get_network_description() const = 0;
+ virtual const std::shared_ptr<IGraph>& get_graph() const = 0;
virtual const Config& get_config() const = 0;
- // Compiler is used for post-processing profiling data when using PERF_COUNT property
- virtual const ov::SoPtr<ICompiler>& get_compiler() const = 0;
-
- const NetworkMetadata& get_network_metadata() const {
- return get_network_description()->metadata;
- }
-
protected:
std::shared_ptr<const ICompiledModel> shared_from_this() const {
return std::dynamic_pointer_cast<const ICompiledModel>(ov::ICompiledModel::shared_from_this());
diff --git a/src/plugins/intel_npu/src/common/include/intel_npu/common/igraph.hpp b/src/plugins/intel_npu/src/common/include/intel_npu/common/igraph.hpp
new file mode 100644
index 00000000000..51c4a4cf26e
--- /dev/null
+++ b/src/plugins/intel_npu/src/common/include/intel_npu/common/igraph.hpp
@@ -0,0 +1,103 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <mutex>
+#include <vector>
+
+#include "intel_npu/network_metadata.hpp"
+#include "intel_npu/utils/zero/zero_utils.hpp"
+#include "intel_npu/utils/zero/zero_wrappers.hpp"
+#include "openvino/runtime/profiling_info.hpp"
+
+namespace intel_npu {
+
+class IGraph : public std::enable_shared_from_this<IGraph> {
+public:
+ IGraph(ze_graph_handle_t handle, NetworkMetadata metadata, std::optional<std::vector<uint8_t>> blob)
+ : _handle(handle),
+ _metadata(std::move(metadata)) {
+ if (blob.has_value()) {
+ _blob = std::move(*blob);
+ }
+ }
+
+ virtual void export_blob(std::ostream& stream) const = 0;
+
+ virtual std::vector<ov::ProfilingInfo> process_profiling_output(const std::vector<uint8_t>& profData,
+ const Config& config) const = 0;
+
+ virtual void set_argument_value(uint32_t argi, const void* argv) const = 0;
+
+ virtual void initialize(const Config& config) = 0;
+
+ virtual ~IGraph() = default;
+
+ const NetworkMetadata& get_metadata() const {
+ return _metadata;
+ }
+
+ ze_graph_handle_t get_handle() const {
+ return _handle;
+ }
+
+ void update_network_name(std::string_view name) {
+ _metadata.name = name;
+ }
+
+ inline const std::vector<ArgumentDescriptor>& get_input_descriptors() const {
+ return _input_descriptors;
+ }
+
+ inline const std::vector<ArgumentDescriptor>& get_output_descriptors() const {
+ return _output_descriptors;
+ }
+
+ inline const std::shared_ptr<CommandQueue>& get_command_queue() const {
+ return _command_queue;
+ }
+
+ void set_workload_type(const ov::WorkloadType workloadType) const {
+ if (_command_queue == nullptr) {
+ return;
+ }
+
+ ze_command_queue_workload_type_t zeWorkloadType;
+ switch (workloadType) {
+ case ov::WorkloadType::DEFAULT:
+ zeWorkloadType = ze_command_queue_workload_type_t::ZE_WORKLOAD_TYPE_DEFAULT;
+ break;
+ case ov::WorkloadType::EFFICIENT:
+ zeWorkloadType = ze_command_queue_workload_type_t::ZE_WORKLOAD_TYPE_BACKGROUND;
+ break;
+ default:
+ OPENVINO_THROW("Unknown value for WorkloadType!");
+ }
+
+ _command_queue->setWorkloadType(zeWorkloadType);
+ }
+
+ std::mutex& get_mutex() {
+ return _mutex;
+ }
+
+protected:
+ ze_graph_handle_t _handle = nullptr;
+ NetworkMetadata _metadata;
+
+ std::vector<ArgumentDescriptor> _input_descriptors;
+ std::vector<ArgumentDescriptor> _output_descriptors;
+
+ std::shared_ptr<CommandQueue> _command_queue;
+
+ // Used to protect zero pipeline creation in the graph. The pipeline should be created only once per graph when the
+ // first inference starts running
+ std::mutex _mutex;
+
+ std::vector<uint8_t> _blob;
+};
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/common/include/intel_npu/common/npu.hpp b/src/plugins/intel_npu/src/common/include/intel_npu/common/npu.hpp
index 8c1eb57fe34..b34f2deee6c 100644
--- a/src/plugins/intel_npu/src/common/include/intel_npu/common/npu.hpp
+++ b/src/plugins/intel_npu/src/common/include/intel_npu/common/npu.hpp
@@ -7,9 +7,9 @@
#include <cstdint>
#include "intel_npu/common/icompiled_model.hpp"
+#include "intel_npu/common/igraph.hpp"
#include "intel_npu/common/sync_infer_request.hpp"
#include "intel_npu/config/config.hpp"
-#include "intel_npu/icompiler.hpp"
#include "openvino/runtime/intel_npu/remote_properties.hpp"
#include "openvino/runtime/iremote_context.hpp"
#include "openvino/runtime/properties.hpp"
@@ -54,11 +54,14 @@ protected:
//------------------------------------------------------------------------------
-class IExecutor {
+class ICompilerAdapter {
public:
- virtual ~IExecutor() = default;
+ virtual std::shared_ptr<IGraph> compile(const std::shared_ptr<const ov::Model>& model,
+ const Config& config) const = 0;
+ virtual std::shared_ptr<IGraph> parse(std::vector<uint8_t> network, const Config& config) const = 0;
+ virtual ov::SupportedOpsMap query(const std::shared_ptr<const ov::Model>& model, const Config& config) const = 0;
- virtual void setWorkloadType(const ov::WorkloadType workloadType) const = 0;
+ virtual ~ICompilerAdapter() = default;
};
//------------------------------------------------------------------------------
@@ -67,10 +70,6 @@ class IDevice : public std::enable_shared_from_this<IDevice> {
public:
using Uuid = ov::device::UUID;
- virtual std::shared_ptr<IExecutor> createExecutor(
- const std::shared_ptr<const NetworkDescription>& networkDescription,
- const Config& config) = 0;
-
virtual std::string getName() const = 0;
virtual std::string getFullDeviceName() const = 0;
virtual Uuid getUuid() const;
@@ -85,7 +84,6 @@ public:
virtual std::shared_ptr<SyncInferRequest> createInferRequest(
const std::shared_ptr<const ICompiledModel>& compiledModel,
- const std::shared_ptr<IExecutor>& executor,
const Config& config) = 0;
virtual void updateInfo(const Config& config) = 0;
diff --git a/src/plugins/intel_npu/src/common/include/intel_npu/common/sync_infer_request.hpp b/src/plugins/intel_npu/src/common/include/intel_npu/common/sync_infer_request.hpp
index 99f9ce7cb0e..788ce87136a 100644
--- a/src/plugins/intel_npu/src/common/include/intel_npu/common/sync_infer_request.hpp
+++ b/src/plugins/intel_npu/src/common/include/intel_npu/common/sync_infer_request.hpp
@@ -5,8 +5,9 @@
#pragma once
#include "intel_npu/common/icompiled_model.hpp"
+#include "intel_npu/common/igraph.hpp"
#include "intel_npu/common/variable_state.hpp"
-#include "intel_npu/icompiler.hpp"
+#include "intel_npu/network_metadata.hpp"
#include "openvino/runtime/iinfer_request.hpp"
#include "openvino/runtime/iplugin.hpp"
diff --git a/src/plugins/intel_npu/src/common/src/sync_infer_request.cpp b/src/plugins/intel_npu/src/common/src/sync_infer_request.cpp
index 0ae0832fe29..0eeefccf439 100644
--- a/src/plugins/intel_npu/src/common/src/sync_infer_request.cpp
+++ b/src/plugins/intel_npu/src/common/src/sync_infer_request.cpp
@@ -21,7 +21,7 @@ namespace intel_npu {
SyncInferRequest::SyncInferRequest(const std::shared_ptr<const ICompiledModel>& compiledModel, const Config& config)
: _compiledModel(compiledModel),
- _metadata(compiledModel->get_network_metadata()),
+ _metadata(compiledModel->get_graph()->get_metadata()),
_logger("SyncInferRequest", config.get<LOG_LEVEL>()),
_userInputTensors(_metadata.inputs.size(), std::vector<ov::SoPtr<ov::ITensor>>(1, {nullptr})),
_userOutputTensors(_metadata.outputs.size(), {nullptr}) {
diff --git a/src/plugins/intel_npu/src/compiler/include/driver_compiler_adapter.hpp b/src/plugins/intel_npu/src/compiler/include/driver_compiler_adapter.hpp
deleted file mode 100644
index addd9ca5308..00000000000
--- a/src/plugins/intel_npu/src/compiler/include/driver_compiler_adapter.hpp
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (C) 2018-2024 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#pragma once
-
-#include <ze_graph_ext.h>
-
-#include "intel_npu/common/npu.hpp"
-#include "intel_npu/icompiler.hpp"
-#include "intel_npu/utils/logger/logger.hpp"
-
-namespace intel_npu {
-namespace driverCompilerAdapter {
-
-/**
- * @brief Adapter for Compiler in driver
- * @details Wrap compiler in driver calls and do preliminary actions (like opset conversion)
- */
-class LevelZeroCompilerAdapter final : public ICompiler {
-public:
- LevelZeroCompilerAdapter(std::shared_ptr<IEngineBackend> iEngineBackend);
-
- uint32_t getSupportedOpsetVersion() const override final;
-
- NetworkDescription compile(const std::shared_ptr<const ov::Model>& model,
- const Config& config) const override final;
-
- ov::SupportedOpsMap query(const std::shared_ptr<const ov::Model>& model, const Config& config) const override final;
-
- NetworkMetadata parse(const std::vector<uint8_t>& network, const Config& config) const override final;
-
- std::vector<ov::ProfilingInfo> process_profiling_output(const std::vector<uint8_t>& profData,
- const std::vector<uint8_t>& network,
- const Config& config) const override final;
-
- void release(std::shared_ptr<const NetworkDescription> networkDescription) override;
-
- CompiledNetwork getCompiledNetwork(const NetworkDescription& networkDescription) override;
-
-private:
- /**
- * @brief Separate externals calls to separate class
- */
- std::shared_ptr<ICompiler> apiAdapter;
- Logger _logger;
-};
-
-} // namespace driverCompilerAdapter
-} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler/include/zero_compiler_in_driver.hpp b/src/plugins/intel_npu/src/compiler/include/zero_compiler_in_driver.hpp
deleted file mode 100644
index 5641408dffc..00000000000
--- a/src/plugins/intel_npu/src/compiler/include/zero_compiler_in_driver.hpp
+++ /dev/null
@@ -1,201 +0,0 @@
-// Copyright (C) 2018-2024 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#include <ze_api.h>
-#include <ze_graph_ext.h>
-
-#include <type_traits>
-#include <utility>
-
-#include "intel_npu/icompiler.hpp"
-#include "intel_npu/utils/logger/logger.hpp"
-#include "intel_npu/utils/zero/zero_api.hpp"
-#include "zero_executor.hpp"
-
-namespace intel_npu {
-namespace driverCompilerAdapter {
-
-using SerializedIR = std::pair<size_t, std::shared_ptr<uint8_t>>;
-
-#define NotSupportQuery(T) (T == ZE_GRAPH_EXT_VERSION_1_2)
-
-// ext version == 1.3 && 1.4, support API (pfnQueryNetworkCreate, pfnQueryNetworkDestroy,
-// pfnQueryNetworkGetSupportedLayers)
-#define SupportAPIGraphQueryNetworkV1(T) (T == ZE_GRAPH_EXT_VERSION_1_3 || T == ZE_GRAPH_EXT_VERSION_1_4)
-
-// ext version >= 1.5, support API (pfnCreate2, pfnQueryNetworkCreate2, pfnQueryContextMemory)
-#define SupportAPIGraphQueryNetworkV2(T) ((!NotSupportQuery(T) && !SupportAPIGraphQueryNetworkV1(T)))
-
-// For ext version >= 1.5, pfnCreate2 api is avaible
-#define NotSupportGraph2(T) \
- (T == ZE_GRAPH_EXT_VERSION_1_2 || T == ZE_GRAPH_EXT_VERSION_1_3 || T == ZE_GRAPH_EXT_VERSION_1_4)
-
-// A bug inside the driver makes the "pfnGraphGetArgumentMetadata" call not safe for use prior to
-// "ze_graph_dditable_ext_1_6_t".
-// See: E#117498
-#define NotSupportArgumentMetadata(T) \
- (T == ZE_GRAPH_EXT_VERSION_1_2 || T == ZE_GRAPH_EXT_VERSION_1_3 || T == ZE_GRAPH_EXT_VERSION_1_4 || \
- T == ZE_GRAPH_EXT_VERSION_1_5)
-
-#define UseCopyForNativeBinary(T) \
- (T == ZE_GRAPH_EXT_VERSION_1_2 || T == ZE_GRAPH_EXT_VERSION_1_3 || T == ZE_GRAPH_EXT_VERSION_1_4 || \
- T == ZE_GRAPH_EXT_VERSION_1_5 || T == ZE_GRAPH_EXT_VERSION_1_6)
-
-/**
- * Adapter to use CiD through ZeroAPI
- */
-template <ze_graph_ext_version_t TableExtension>
-class LevelZeroCompilerInDriver final : public ICompiler {
-public:
- LevelZeroCompilerInDriver(ze_driver_handle_t driverHandle,
- ze_device_handle_t deviceHandle,
- ze_context_handle_t zeContext,
- ze_graph_dditable_ext_curr_t& graph_ddi_table_ext);
- LevelZeroCompilerInDriver(const LevelZeroCompilerInDriver&) = delete;
- LevelZeroCompilerInDriver& operator=(const LevelZeroCompilerInDriver&) = delete;
- ~LevelZeroCompilerInDriver() override;
-
- uint32_t getSupportedOpsetVersion() const override final;
-
- ov::SupportedOpsMap query(const std::shared_ptr<const ov::Model>& model, const Config& config) const override;
-
- NetworkDescription compile(const std::shared_ptr<const ov::Model>& model,
- const Config& config) const override final;
-
- ze_result_t seriazlideIRModelAndCreateGraph(const std::shared_ptr<const ov::Model>& model,
- const Config& config,
- ze_device_graph_properties_t deviceGraphProperties,
- ze_graph_handle_t& graphHandle) const;
-
- NetworkMetadata parse(const std::vector<uint8_t>& network, const Config& config) const override final;
-
- std::vector<ov::ProfilingInfo> process_profiling_output(const std::vector<uint8_t>& profData,
- const std::vector<uint8_t>& network,
- const Config& config) const override final {
- OPENVINO_THROW("Profiling post-processing is not implemented.");
- }
-
- template <ze_graph_ext_version_t T = TableExtension, std::enable_if_t<!NotSupportQuery(T), bool> = true>
- std::unordered_set<std::string> getQueryResultFromSupportedLayers(
- ze_result_t result,
- ze_graph_query_network_handle_t& hGraphQueryNetwork) const;
-
- /**
- * @brief Serialize input / output information to string format.
- * @details Format:
- * --inputs_precisions="0:<input1Precision> [1:<input2Precision>]"
- * --inputs_layouts="0:<input1Layout> [1:<input2Layout>]"
- * --outputs_precisions="0:<output1Precision>"
- * --outputs_layouts="0:<output1Layout>"
- *
- * For older compiler versions, the name of the inputs/outputs may be used instead of their indices.
- *
- * Since the layout information is no longer an important part of the metadata values when using the 2.0 OV
- * API, the layout fields shall be filled with default values in order to assure the backward compatibility
- * with the driver.
- */
- static std::string serializeIOInfo(const std::shared_ptr<const ov::Model>& model, const bool useIndices);
-
- void release(std::shared_ptr<const NetworkDescription> networkDescription) override;
-
- CompiledNetwork getCompiledNetwork(const NetworkDescription& networkDescription) override;
-
-private:
- NetworkMetadata getNetworkMeta(ze_graph_handle_t graphHandle) const;
-
- SerializedIR serializeIR(const std::shared_ptr<const ov::Model>& model,
- ze_graph_compiler_version_info_t compilerVersion) const;
- std::string serializeConfig(const Config& config, ze_graph_compiler_version_info_t& compilerVersion) const;
-
- template <ze_graph_ext_version_t T = TableExtension,
- typename std::enable_if_t<NotSupportArgumentMetadata(T), bool> = true>
- void getMetadata(ze_graph_dditable_ext_curr_t& graphDdiTableExt,
- ze_graph_handle_t graphHandle,
- uint32_t index,
- std::vector<IODescriptor>& inputs,
- std::vector<IODescriptor>& outputs) const;
-
- template <ze_graph_ext_version_t T = TableExtension,
- typename std::enable_if_t<!NotSupportArgumentMetadata(T), bool> = true>
- void getMetadata(ze_graph_dditable_ext_curr_t& graphDdiTableExt,
- ze_graph_handle_t graphHandle,
- uint32_t index,
- std::vector<IODescriptor>& inputs,
- std::vector<IODescriptor>& outputs) const;
-
- template <ze_graph_ext_version_t T = TableExtension,
- typename std::enable_if_t<UseCopyForNativeBinary(T), bool> = true>
- void getNativeBinary(ze_graph_dditable_ext_curr_t& graphDdiTableExt,
- ze_graph_handle_t graphHandle,
- std::vector<uint8_t>& blob,
- const uint8_t*& blobPtr,
- size_t& blobSize) const;
-
- template <ze_graph_ext_version_t T = TableExtension,
- typename std::enable_if_t<!UseCopyForNativeBinary(T), bool> = true>
- void getNativeBinary(ze_graph_dditable_ext_curr_t& graphDdiTableExt,
- ze_graph_handle_t graphHandle,
- std::vector<uint8_t>& /* unusedBlob */,
- const uint8_t*& blobPtr,
- size_t& blobSize) const;
-
- template <ze_graph_ext_version_t T = TableExtension,
- typename std::enable_if_t<SupportAPIGraphQueryNetworkV2(T), bool> = true>
- ze_result_t seriazlideIRModelAndQueryNetworkCreateV2(const std::shared_ptr<const ov::Model>& model,
- const Config& config,
- ze_device_graph_properties_t deviceGraphProperties,
- const ze_device_handle_t& _deviceHandle,
- ze_graph_query_network_handle_t& hGraphQueryNetwork) const;
-
- // ext version >= 1.5, support API (pfnCreate2, pfnQueryNetworkCreate2, pfnQueryContextMemory)
- template <ze_graph_ext_version_t T = TableExtension,
- typename std::enable_if_t<SupportAPIGraphQueryNetworkV2(T), bool> = true>
- std::unordered_set<std::string> queryImpl(const std::shared_ptr<const ov::Model>& model,
- const Config& config) const;
-
- template <ze_graph_ext_version_t T = TableExtension,
- typename std::enable_if_t<SupportAPIGraphQueryNetworkV1(T), bool> = true>
- ze_result_t seriazlideIRModelAndQueryNetworkCreateV1(const std::shared_ptr<const ov::Model>& model,
- const Config& config,
- ze_device_graph_properties_t deviceGraphProperties,
- const ze_device_handle_t& _deviceHandle,
- ze_graph_query_network_handle_t& hGraphQueryNetwork) const;
-
- // ext version == 1.3 && 1.4, support API (pfnQueryNetworkCreate, pfnQueryNetworkDestroy,
- // pfnQueryNetworkGetSupportedLayers)
- template <ze_graph_ext_version_t T = TableExtension,
- typename std::enable_if_t<SupportAPIGraphQueryNetworkV1(T), bool> = true>
- std::unordered_set<std::string> queryImpl(const std::shared_ptr<const ov::Model>& model,
- const Config& config) const;
-
- // For ext version < 1.3
- template <ze_graph_ext_version_t T = TableExtension, typename std::enable_if_t<NotSupportQuery(T), bool> = true>
- std::unordered_set<std::string> queryImpl(const std::shared_ptr<const ov::Model>& model,
- const Config& config) const;
-
- template <ze_graph_ext_version_t T = TableExtension, typename std::enable_if_t<NotSupportGraph2(T), bool> = true>
- ze_result_t createGraph(const ze_graph_format_t& format,
- const SerializedIR& serializedIR,
- const std::string& buildFlags,
- const uint32_t& flags,
- ze_graph_handle_t* graph) const;
-
- template <ze_graph_ext_version_t T = TableExtension, typename std::enable_if_t<!NotSupportGraph2(T), bool> = true>
- ze_result_t createGraph(const ze_graph_format_t& format,
- const SerializedIR& serializedIR,
- const std::string& buildFlags,
- const uint32_t& flags,
- ze_graph_handle_t* graph) const;
-
-private:
- ze_driver_handle_t _driverHandle = nullptr;
- ze_device_handle_t _deviceHandle = nullptr;
- ze_context_handle_t _context = nullptr;
-
- ze_graph_dditable_ext_curr_t& _graphDdiTableExt;
- Logger _logger;
-};
-
-} // namespace driverCompilerAdapter
-} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler/src/driver_compiler_adapter.cpp b/src/plugins/intel_npu/src/compiler/src/driver_compiler_adapter.cpp
deleted file mode 100644
index 0406b375609..00000000000
--- a/src/plugins/intel_npu/src/compiler/src/driver_compiler_adapter.cpp
+++ /dev/null
@@ -1,130 +0,0 @@
-// Copyright (C) 2018-2024 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#include "driver_compiler_adapter.hpp"
-
-#include "graph_transformations.hpp"
-#include "intel_npu/config/common.hpp"
-#include "intel_npu/utils/zero/zero_api.hpp"
-#include "intel_npu/utils/zero/zero_result.hpp"
-#include "ze_intel_npu_uuid.h"
-#include "zero_backend.hpp"
-#include "zero_compiler_in_driver.hpp"
-#include "zero_init.hpp"
-
-namespace intel_npu {
-namespace driverCompilerAdapter {
-
-LevelZeroCompilerAdapter::LevelZeroCompilerAdapter(std::shared_ptr<IEngineBackend> iEngineBackend)
- : _logger("LevelZeroCompilerAdapter", Logger::global().level()) {
- _logger.debug("initialize LevelZeroCompilerAdapter start");
-
- std::shared_ptr<ZeroEngineBackend> zeroBackend = nullptr;
- zeroBackend = std::dynamic_pointer_cast<ZeroEngineBackend>(iEngineBackend);
- if (!zeroBackend) {
- OPENVINO_THROW("LevelZeroCompilerAdapter init failed to cast zeroBackend, zeroBackend is a nullptr");
- }
-
- ze_context_handle_t zeContext = static_cast<ze_context_handle_t>(zeroBackend->getContext());
- ze_driver_handle_t driverHandle = static_cast<ze_driver_handle_t>(zeroBackend->getDriverHandle());
- ze_device_handle_t deviceHandle = static_cast<ze_device_handle_t>(zeroBackend->getDeviceHandle());
- ze_graph_dditable_ext_curr_t& graph_ddi_table_ext = zeroBackend->getGraphDdiTable();
-
- uint32_t graphExtVersion = graph_ddi_table_ext.version();
-
- if (driverHandle == nullptr) {
- OPENVINO_THROW("LevelZeroCompilerAdapter failed to get properties about zeDriver");
- }
-
- _logger.info("LevelZeroCompilerAdapter creating adapter using graphExtVersion");
-
- switch (graphExtVersion) {
- case ZE_GRAPH_EXT_VERSION_1_3:
- apiAdapter = std::make_shared<LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_3>>(driverHandle,
- deviceHandle,
- zeContext,
- graph_ddi_table_ext);
- break;
- case ZE_GRAPH_EXT_VERSION_1_4:
- apiAdapter = std::make_shared<LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_4>>(driverHandle,
- deviceHandle,
- zeContext,
- graph_ddi_table_ext);
- break;
- case ZE_GRAPH_EXT_VERSION_1_5:
- apiAdapter = std::make_shared<LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_5>>(driverHandle,
- deviceHandle,
- zeContext,
- graph_ddi_table_ext);
- break;
- case ZE_GRAPH_EXT_VERSION_1_6:
- apiAdapter = std::make_shared<LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_6>>(driverHandle,
- deviceHandle,
- zeContext,
- graph_ddi_table_ext);
- break;
- case ZE_GRAPH_EXT_VERSION_1_7:
- apiAdapter = std::make_shared<LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_7>>(driverHandle,
- deviceHandle,
- zeContext,
- graph_ddi_table_ext);
- break;
- case ZE_GRAPH_EXT_VERSION_1_8:
- apiAdapter = std::make_shared<LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_8>>(driverHandle,
- deviceHandle,
- zeContext,
- graph_ddi_table_ext);
- break;
- default:
- apiAdapter = std::make_shared<LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_2>>(driverHandle,
- deviceHandle,
- zeContext,
- graph_ddi_table_ext);
- break;
- }
-
- _logger.info("initialize LevelZeroCompilerAdapter complete, using graphExtVersion: %d.%d",
- ZE_MAJOR_VERSION(graphExtVersion),
- ZE_MINOR_VERSION(graphExtVersion));
-}
-
-uint32_t LevelZeroCompilerAdapter::getSupportedOpsetVersion() const {
- return apiAdapter->getSupportedOpsetVersion();
-}
-
-NetworkDescription LevelZeroCompilerAdapter::compile(const std::shared_ptr<const ov::Model>& model,
- const Config& config) const {
- _logger.debug("compile start");
- return apiAdapter->compile(model, config);
-}
-
-ov::SupportedOpsMap LevelZeroCompilerAdapter::query(const std::shared_ptr<const ov::Model>& model,
- const Config& config) const {
- _logger.debug("query start");
- return apiAdapter->query(model, config);
-}
-
-NetworkMetadata LevelZeroCompilerAdapter::parse(const std::vector<uint8_t>& network, const Config& config) const {
- _logger.debug("parse start");
- return apiAdapter->parse(network, config);
-}
-
-std::vector<ov::ProfilingInfo> LevelZeroCompilerAdapter::process_profiling_output(const std::vector<uint8_t>&,
- const std::vector<uint8_t>&,
- const Config&) const {
- OPENVINO_THROW("Profiling post-processing is not implemented.");
-}
-
-void LevelZeroCompilerAdapter::release(std::shared_ptr<const NetworkDescription> networkDescription) {
- _logger.info("release - using adapter to release networkDescription");
- apiAdapter->release(std::move(networkDescription));
-}
-
-CompiledNetwork LevelZeroCompilerAdapter::getCompiledNetwork(const NetworkDescription& networkDescription) {
- _logger.info("getCompiledNetwork - using adapter to perform getCompiledNetwork(networkDescription)");
- return apiAdapter->getCompiledNetwork(networkDescription);
-}
-
-} // namespace driverCompilerAdapter
-} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler/src/zero_compiler_in_driver.cpp b/src/plugins/intel_npu/src/compiler/src/zero_compiler_in_driver.cpp
deleted file mode 100644
index 8f7ac4198bb..00000000000
--- a/src/plugins/intel_npu/src/compiler/src/zero_compiler_in_driver.cpp
+++ /dev/null
@@ -1,1081 +0,0 @@
-// Copyright (C) 2018-2024 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#include "zero_compiler_in_driver.hpp"
-
-#include <regex>
-#include <string_view>
-
-#include "graph_transformations.hpp"
-#include "intel_npu/common/itt.hpp"
-#include "intel_npu/config/common.hpp"
-#include "intel_npu/config/compiler.hpp"
-#include "intel_npu/config/runtime.hpp"
-#include "intel_npu/prefix.hpp"
-#include "intel_npu/utils/zero/zero_result.hpp"
-#include "openvino/core/model.hpp"
-
-namespace {
-
-constexpr std::string_view INPUTS_PRECISIONS_KEY = "--inputs_precisions";
-constexpr std::string_view INPUTS_LAYOUTS_KEY = "--inputs_layouts";
-constexpr std::string_view OUTPUTS_PRECISIONS_KEY = "--outputs_precisions";
-constexpr std::string_view OUTPUTS_LAYOUTS_KEY = "--outputs_layouts";
-
-// <option key>="<option value>"
-constexpr std::string_view KEY_VALUE_SEPARATOR = "=";
-constexpr std::string_view VALUE_DELIMITER = "\""; // marks beginning and end of value
-
-// Format inside "<option value>"
-// <name1>:<value (precision / layout)> [<name2>:<value>]
-constexpr std::string_view NAME_VALUE_SEPARATOR = ":";
-constexpr std::string_view VALUES_SEPARATOR = " ";
-
-// Constants indicating the order indices needed to be applied as to perform conversions between legacy layout values
-const std::vector<size_t> NC_TO_CN_LAYOUT_DIMENSIONS_ORDER = {1, 0};
-const std::vector<size_t> NCHW_TO_NHWC_LAYOUT_DIMENSIONS_ORDER = {0, 2, 3, 1};
-const std::vector<size_t> NCDHW_TO_NDHWC_LAYOUT_DIMENSIONS_ORDER = {0, 2, 3, 4, 1};
-
-/**
- * @brief A standard copy function concerning memory segments. Additional checks on the given arguments are performed
- * before copying.
- * @details This is meant as a replacement for the legacy "ie_memcpy" function coming from the OpenVINO API.
- */
-void checkedMemcpy(void* destination, size_t destinationSize, void const* source, size_t numberOfBytes) {
- if (numberOfBytes == 0) {
- return;
- }
-
- OPENVINO_ASSERT(destination != nullptr, "Memcpy: received a null destination address");
- OPENVINO_ASSERT(source != nullptr, "Memcpy: received a null source address");
- OPENVINO_ASSERT(numberOfBytes <= destinationSize,
- "Memcpy: the source buffer does not fit inside the destination one");
- OPENVINO_ASSERT(numberOfBytes <= (destination > source ? ((uintptr_t)destination - (uintptr_t)source)
- : ((uintptr_t)source - (uintptr_t)destination)),
- "Memcpy: the offset between the two buffers does not allow a safe execution of the operation");
-
- memcpy(destination, source, numberOfBytes);
-}
-
-ov::element::Type_t toOVElementType(const ze_graph_argument_precision_t zeElementType) {
- switch (zeElementType) {
- case ZE_GRAPH_ARGUMENT_PRECISION_UNKNOWN:
- return ov::element::Type_t::undefined;
- case ZE_GRAPH_ARGUMENT_PRECISION_DYNAMIC:
- return ov::element::Type_t::dynamic;
- case ZE_GRAPH_ARGUMENT_PRECISION_BOOLEAN:
- return ov::element::Type_t::boolean;
- case ZE_GRAPH_ARGUMENT_PRECISION_BF16:
- return ov::element::Type_t::bf16;
- case ZE_GRAPH_ARGUMENT_PRECISION_FP16:
- return ov::element::Type_t::f16;
- case ZE_GRAPH_ARGUMENT_PRECISION_FP32:
- return ov::element::Type_t::f32;
- case ZE_GRAPH_ARGUMENT_PRECISION_FP64:
- return ov::element::Type_t::f64;
- case ZE_GRAPH_ARGUMENT_PRECISION_INT4:
- return ov::element::Type_t::i4;
- case ZE_GRAPH_ARGUMENT_PRECISION_INT8:
- return ov::element::Type_t::i8;
- case ZE_GRAPH_ARGUMENT_PRECISION_INT16:
- return ov::element::Type_t::i16;
- case ZE_GRAPH_ARGUMENT_PRECISION_INT32:
- return ov::element::Type_t::i32;
- case ZE_GRAPH_ARGUMENT_PRECISION_INT64:
- return ov::element::Type_t::i64;
- case ZE_GRAPH_ARGUMENT_PRECISION_BIN:
- return ov::element::Type_t::u1;
- case ZE_GRAPH_ARGUMENT_PRECISION_UINT4:
- return ov::element::Type_t::u4;
- case ZE_GRAPH_ARGUMENT_PRECISION_UINT8:
- return ov::element::Type_t::u8;
- case ZE_GRAPH_ARGUMENT_PRECISION_UINT16:
- return ov::element::Type_t::u16;
- case ZE_GRAPH_ARGUMENT_PRECISION_UINT32:
- return ov::element::Type_t::u32;
- case ZE_GRAPH_ARGUMENT_PRECISION_UINT64:
- return ov::element::Type_t::u64;
- default:
- return ov::element::Type_t::undefined;
- }
-}
-
-/**
- * @brief For driver backward compatibility reasons, the given value shall be converted to a string corresponding to the
- * adequate legacy precision.
- */
-std::string ovPrecisionToLegacyPrecisionString(const ov::element::Type& precision) {
- switch (precision) {
- case ov::element::Type_t::undefined:
- return "UNSPECIFIED";
- case ov::element::Type_t::f16:
- return "FP16";
- case ov::element::Type_t::f32:
- return "FP32";
- case ov::element::Type_t::f64:
- return "FP64";
- case ov::element::Type_t::bf16:
- return "BF16";
- case ov::element::Type_t::i4:
- return "I4";
- case ov::element::Type_t::i8:
- return "I8";
- case ov::element::Type_t::i16:
- return "I16";
- case ov::element::Type_t::i32:
- return "I32";
- case ov::element::Type_t::i64:
- return "I64";
- case ov::element::Type_t::u4:
- return "U4";
- case ov::element::Type_t::u8:
- return "U8";
- case ov::element::Type_t::u16:
- return "U16";
- case ov::element::Type_t::u32:
- return "U32";
- case ov::element::Type_t::u64:
- return "U64";
- case ov::element::Type_t::u1:
- return "BIN";
- case ov::element::Type_t::boolean:
- return "BOOL";
- case ov::element::Type_t::dynamic:
- return "DYNAMIC";
- default:
- OPENVINO_THROW("Incorrect precision: ", precision);
- }
-}
-
-/**
- * @brief Gives the string representation of the default legacy layout value corresponding to the given rank.
- * @details This is done in order to assure the backward compatibility with the driver. Giving a layout different from
- * the default one may lead either to error or to accuracy failures since unwanted transposition layers may be
- * introduced.
- */
-std::string rankToLegacyLayoutString(const size_t rank) {
- switch (rank) {
- case 0:
- return "**SCALAR**";
- case 1:
- return "C";
- case 2:
- return "NC";
- case 3:
- return "CHW";
- case 4:
- return "NCHW";
- case 5:
- return "NCDHW";
- default:
- return "BLOCKED";
- }
-}
-
-} // namespace
-
-namespace intel_npu {
-namespace driverCompilerAdapter {
-
-template <ze_graph_ext_version_t TableExtension>
-LevelZeroCompilerInDriver<TableExtension>::LevelZeroCompilerInDriver(ze_driver_handle_t driverHandle,
- ze_device_handle_t deviceHandle,
- ze_context_handle_t zeContext,
- ze_graph_dditable_ext_curr_t& graph_ddi_table_ext)
- : _driverHandle(driverHandle),
- _deviceHandle(deviceHandle),
- _context(zeContext),
- _graphDdiTableExt(graph_ddi_table_ext),
- _logger("LevelZeroCompilerInDriver", Logger::global().level()) {}
-
-template <ze_graph_ext_version_t TableExtension>
-LevelZeroCompilerInDriver<TableExtension>::~LevelZeroCompilerInDriver() {
- _logger.debug("LevelZeroCompilerInDriver obj destroyed");
-}
-
-/**
- * @brief Place xml + weights in sequential memory
- * @details Format of the memory:
- */
-template <ze_graph_ext_version_t TableExtension>
-SerializedIR LevelZeroCompilerInDriver<TableExtension>::serializeIR(
- const std::shared_ptr<const ov::Model>& model,
- ze_graph_compiler_version_info_t compilerVersion) const {
- IRSerializer irSerializer(model, getSupportedOpsetVersion());
-
- // Contract between adapter and compiler in driver
- const uint32_t maxNumberOfElements = 10;
- const uint64_t maxSizeOfXML = std::numeric_limits<uint64_t>::max() / 3;
- const uint64_t maxSizeOfWeights = maxSizeOfXML * 2;
-
- const uint32_t numberOfInputData = 2;
- const uint64_t xmlSize = static_cast<uint64_t>(irSerializer.getXmlSize());
- const uint64_t weightsSize = static_cast<uint64_t>(irSerializer.getWeightsSize());
-
- OPENVINO_ASSERT(numberOfInputData < maxNumberOfElements);
- if (xmlSize >= maxSizeOfXML) {
- OPENVINO_THROW("LevelZeroCompilerInDriver: Xml file is too big to process. xmlSize: ",
- xmlSize,
- " >= maxSizeOfXML: ",
- maxSizeOfXML);
- }
- if (weightsSize >= maxSizeOfWeights) {
- OPENVINO_THROW("LevelZeroCompilerInDriver: Bin file is too big to process. xmlSize: ",
- weightsSize,
- " >= maxSizeOfWeights: ",
- maxSizeOfWeights);
- }
-
- const uint64_t sizeOfSerializedIR = sizeof(compilerVersion) + sizeof(numberOfInputData) + sizeof(xmlSize) +
- xmlSize + sizeof(weightsSize) + weightsSize;
-
- // use array to avoid vector's memory zeroing overhead
- std::shared_ptr<uint8_t> buffer(new uint8_t[sizeOfSerializedIR], std::default_delete<uint8_t[]>());
- uint8_t* serializedIR = buffer.get();
-
- uint64_t offset = 0;
- checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &compilerVersion, sizeof(compilerVersion));
- offset += sizeof(compilerVersion);
-
- checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &numberOfInputData, sizeof(numberOfInputData));
- offset += sizeof(numberOfInputData);
- checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &xmlSize, sizeof(xmlSize));
- offset += sizeof(xmlSize);
- // xml data is filled in serializeModel()
- uint64_t xmlOffset = offset;
- offset += xmlSize;
- checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &weightsSize, sizeof(weightsSize));
- offset += sizeof(weightsSize);
- // weights data is filled in serializeModel()
- uint64_t weightsOffset = offset;
- offset += weightsSize;
-
- irSerializer.serializeModelToBuffer(serializedIR + xmlOffset, serializedIR + weightsOffset);
-
- OPENVINO_ASSERT(offset == sizeOfSerializedIR);
-
- return std::make_pair(sizeOfSerializedIR, buffer);
-}
-
-template <ze_graph_ext_version_t TableExtension>
-std::string LevelZeroCompilerInDriver<TableExtension>::serializeIOInfo(const std::shared_ptr<const ov::Model>& model,
- const bool useIndices) {
- const ov::ParameterVector& parameters = model->get_parameters();
- const ov::ResultVector& results = model->get_results();
-
- std::stringstream inputsPrecisionSS;
- std::stringstream inputsLayoutSS;
- std::stringstream outputsPrecisionSS;
- std::stringstream outputsLayoutSS;
-
- inputsPrecisionSS << INPUTS_PRECISIONS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;
- inputsLayoutSS << INPUTS_LAYOUTS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;
- const auto getRankOrThrow = [](const ov::PartialShape& shape) -> size_t {
- if (shape.rank().is_dynamic()) {
- OPENVINO_THROW("Dynamic rank is not supported for NPU plugin");
- }
- return shape.rank().get_length();
- };
-
- if (!parameters.empty()) {
- size_t parameterIndex = 0;
-
- for (const std::shared_ptr<ov::op::v0::Parameter>& parameter : parameters) {
- const auto precision = parameter->get_element_type();
- const auto rank = getRankOrThrow(parameter->get_partial_shape());
-
- if (parameterIndex != 0) {
- inputsPrecisionSS << VALUES_SEPARATOR;
- inputsLayoutSS << VALUES_SEPARATOR;
- }
-
- if (useIndices) {
- inputsPrecisionSS << parameterIndex;
- inputsLayoutSS << parameterIndex;
- } else {
- const std::string& name = parameter->get_friendly_name();
-
- inputsPrecisionSS << name;
- // Ticket: E-88902
- inputsLayoutSS << name;
- }
-
- inputsPrecisionSS << NAME_VALUE_SEPARATOR << ovPrecisionToLegacyPrecisionString(precision);
- inputsLayoutSS << NAME_VALUE_SEPARATOR << rankToLegacyLayoutString(rank);
-
- ++parameterIndex;
- }
- }
-
- inputsPrecisionSS << VALUE_DELIMITER;
- inputsLayoutSS << VALUE_DELIMITER;
-
- outputsPrecisionSS << OUTPUTS_PRECISIONS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;
- outputsLayoutSS << OUTPUTS_LAYOUTS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;
-
- size_t resultIndex = 0;
- for (const std::shared_ptr<ov::op::v0::Result>& result : results) {
- const auto precision = result->get_element_type();
- const auto rank = getRankOrThrow(result->get_output_partial_shape(0));
-
- if (resultIndex != 0) {
- outputsPrecisionSS << VALUES_SEPARATOR;
- outputsLayoutSS << VALUES_SEPARATOR;
- }
-
- if (useIndices) {
- outputsPrecisionSS << resultIndex;
- outputsLayoutSS << resultIndex;
- } else {
- const std::string& name = result->get_input_node_ptr(0)->get_friendly_name();
-
- outputsPrecisionSS << name;
- outputsLayoutSS << name;
- }
-
- outputsPrecisionSS << NAME_VALUE_SEPARATOR << ovPrecisionToLegacyPrecisionString(precision);
- outputsLayoutSS << NAME_VALUE_SEPARATOR << rankToLegacyLayoutString(rank);
-
- ++resultIndex;
- }
-
- outputsPrecisionSS << VALUE_DELIMITER;
- outputsLayoutSS << VALUE_DELIMITER;
-
- // One line without spaces to avoid parsing as config option inside CID
- return inputsPrecisionSS.str() + VALUES_SEPARATOR.data() + inputsLayoutSS.str() + VALUES_SEPARATOR.data() +
- outputsPrecisionSS.str() + VALUES_SEPARATOR.data() + outputsLayoutSS.str();
-}
-
-template <ze_graph_ext_version_t TableExtension>
-void LevelZeroCompilerInDriver<TableExtension>::release(std::shared_ptr<const NetworkDescription> networkDescription) {
- _logger.debug("performing release networkDescription");
- if (networkDescription->metadata.graphHandle != nullptr) {
- _logger.debug("release - graphHandle is not nullptr");
- ze_graph_handle_t graphHandle = static_cast<ze_graph_handle_t>(networkDescription->metadata.graphHandle);
- _logger.debug("release - pfnDestroy graphHandle");
- auto result = _graphDdiTableExt.pfnDestroy(graphHandle);
-
- if (ZE_RESULT_SUCCESS != result) {
- _logger.error("failed to release graph handle. L0 pfnDestroy result: %s, code %#X",
- ze_result_to_string(result).c_str(),
- uint64_t(result));
- }
- }
- _logger.debug("release completed");
-}
-
-template <ze_graph_ext_version_t TableExtension>
-template <ze_graph_ext_version_t T, std::enable_if_t<UseCopyForNativeBinary(T), bool>>
-void LevelZeroCompilerInDriver<TableExtension>::getNativeBinary(ze_graph_dditable_ext_curr_t& graphDdiTableExt,
- ze_graph_handle_t graphHandle,
- std::vector<uint8_t>& blob,
- const uint8_t*& blobPtr,
- size_t& blobSize) const {
- // Get blob size first
- auto result = _graphDdiTableExt.pfnGetNativeBinary(graphHandle, &blobSize, nullptr);
- blob.resize(blobSize);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetNativeBinary get blob size, Failed to compile network.",
- result,
- _graphDdiTableExt);
-
- // Get blob data
- result = _graphDdiTableExt.pfnGetNativeBinary(graphHandle, &blobSize, blob.data());
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetNativeBinary get blob data, Failed to compile network.",
- result,
- _graphDdiTableExt);
-
- blobPtr = blob.data();
-}
-
-template <ze_graph_ext_version_t TableExtension>
-template <ze_graph_ext_version_t T, std::enable_if_t<!UseCopyForNativeBinary(T), bool>>
-void LevelZeroCompilerInDriver<TableExtension>::getNativeBinary(ze_graph_dditable_ext_curr_t& graphDdiTableExt,
- ze_graph_handle_t graphHandle,
- std::vector<uint8_t>& /* unusedBlob */,
- const uint8_t*& blobPtr,
- size_t& blobSize) const {
- // Get blob ptr and size
- auto result = _graphDdiTableExt.pfnGetNativeBinary2(graphHandle, &blobSize, &blobPtr);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetNativeBinary get blob size, Failed to compile network.",
- result,
- _graphDdiTableExt);
-}
-
-template <ze_graph_ext_version_t TableExtension>
-CompiledNetwork LevelZeroCompilerInDriver<TableExtension>::getCompiledNetwork(
- const NetworkDescription& networkDescription) {
- if (networkDescription.metadata.graphHandle != nullptr && networkDescription.compiledNetwork.size() == 0) {
- _logger.info("LevelZeroCompilerInDriver getCompiledNetwork get blob from graphHandle");
- ze_graph_handle_t graphHandle = static_cast<ze_graph_handle_t>(networkDescription.metadata.graphHandle);
-
- const uint8_t* blobPtr = nullptr;
- size_t blobSize = -1;
- std::vector<uint8_t> blob;
-
- getNativeBinary(_graphDdiTableExt, graphHandle, blob, blobPtr, blobSize);
-
- _logger.info("LevelZeroCompilerInDriver getCompiledNetwork returning blob");
- return CompiledNetwork(blobPtr, blobSize, std::move(blob));
- }
- _logger.info("return the blob from network description");
- return CompiledNetwork(networkDescription.compiledNetwork.data(),
- networkDescription.compiledNetwork.size(),
- networkDescription.compiledNetwork);
-}
-
-template <ze_graph_ext_version_t TableExtension>
-std::string LevelZeroCompilerInDriver<TableExtension>::serializeConfig(
- const Config& config,
- ze_graph_compiler_version_info_t& compilerVersion) const {
- std::string content = config.toString();
- _logger.debug("Original content of config: %s", content.c_str());
-
- // Remove optimization-level and performance-hint-override for old driver which not support them
- if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 7)) {
- std::string valueOfParams = config.get<COMPILATION_MODE_PARAMS>();
- std::string keyOfOptL("optimization-level");
- std::string keyOfPerfHO("performance-hint-override");
- if (valueOfParams != "" && (valueOfParams.find(keyOfOptL) != std::string::npos ||
- valueOfParams.find(keyOfPerfHO) != std::string::npos)) {
- // Remove unsupported options from value
- std::ostringstream optLevelStr;
- optLevelStr << keyOfOptL << KEY_VALUE_SEPARATOR << "\\d+";
- std::ostringstream perfHintStr;
- perfHintStr << keyOfPerfHO << KEY_VALUE_SEPARATOR << "\\S+";
- _logger.warning("%s property is not suppored by this compiler version. Removing from parameters",
- keyOfOptL.c_str());
- valueOfParams = std::regex_replace(valueOfParams, std::regex(optLevelStr.str()), "");
- _logger.warning("%s property is not suppored by this compiler version. Removing from parameters",
- keyOfPerfHO.c_str());
- valueOfParams = std::regex_replace(valueOfParams, std::regex(perfHintStr.str()), "");
-
- // Trim space
- valueOfParams = std::regex_replace(valueOfParams, std::regex(R"(^\s+|\s+$)"), "");
-
- // Replace the value in content with new value
- std::ostringstream compilationParamsStr;
- compilationParamsStr << ov::intel_npu::compilation_mode_params.name() << KEY_VALUE_SEPARATOR
- << VALUE_DELIMITER << ".*" << VALUE_DELIMITER;
- if (valueOfParams == "") {
- _logger.warning("Clear empty NPU_COMPILATION_MODE_PARAMS. Removing from parameters");
- content = std::regex_replace(content, std::regex(compilationParamsStr.str()), "");
- } else {
- std::ostringstream newValue;
- newValue << ov::intel_npu::compilation_mode_params.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER
- << valueOfParams << VALUE_DELIMITER;
- _logger.warning("Replace value of NPU_COMPILATION_MODE_PARAMS with new value %s",
- newValue.str().c_str());
- content = std::regex_replace(content, std::regex(compilationParamsStr.str()), newValue.str().c_str());
- }
- }
- }
-
- // As a consequence of complying to the conventions established in the 2.0 OV API, the set of values corresponding
- // to the "model priority" key has been modified
- // cpu_pinning property is not supported in compilers < v5.2 - need to remove it
- if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 2)) {
- const auto& getTargetRegex = [](const ov::hint::Priority& priorityValue) -> std::regex {
- std::ostringstream result;
- result << ov::hint::model_priority.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << priorityValue
- << VALUE_DELIMITER;
- return std::regex(result.str());
- };
- const auto& getStringReplacement = [](const ov::intel_npu::LegacyPriority& priorityValue) -> std::string {
- std::ostringstream result;
- result << ov::intel_npu::legacy_model_priority.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER
- << priorityValue << VALUE_DELIMITER;
- return result.str();
- };
-
- // E.g. (valid as of writing this): MODEL_PRIORITY="MEDIUM" -> MODEL_PRIORITY="MODEL_PRIORITY_MED"
- content = std::regex_replace(content,
- getTargetRegex(ov::hint::Priority::LOW),
- getStringReplacement(ov::intel_npu::LegacyPriority::LOW));
- content = std::regex_replace(content,
- getTargetRegex(ov::hint::Priority::MEDIUM),
- getStringReplacement(ov::intel_npu::LegacyPriority::MEDIUM));
- content = std::regex_replace(content,
- getTargetRegex(ov::hint::Priority::HIGH),
- getStringReplacement(ov::intel_npu::LegacyPriority::HIGH));
-
- // Removing cpu_pinning from the command string
- std::ostringstream pinningstr;
- pinningstr << ov::hint::enable_cpu_pinning.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+"
- << VALUE_DELIMITER;
- _logger.warning(
- "ENABLE_CPU_PINNING property is not suppored by this compiler version. Removing from parameters");
- content = std::regex_replace(content, std::regex(pinningstr.str()), "");
- }
-
- /// Stepping and max_tiles are not supported in versions < 5.3 - need to remove it
- if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 3)) {
- std::ostringstream stepstr;
- stepstr << ov::intel_npu::stepping.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\d+"
- << VALUE_DELIMITER;
- std::ostringstream maxtilestr;
- maxtilestr << ov::intel_npu::max_tiles.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\d+"
- << VALUE_DELIMITER;
- _logger.warning("NPU_STEPPING property is not suppored by this compiler version. Removing from parameters");
- content = std::regex_replace(content, std::regex(stepstr.str()), "");
- _logger.warning("NPU_MAX_TILES property is not suppored by this compiler version. Removing from parameters");
- content = std::regex_replace(content, std::regex(maxtilestr.str()), "");
- }
-
- /// Removing INFERENCE_PRECISION_HINT for older compilers
- if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 4)) {
- std::ostringstream precstr;
- precstr << ov::hint::inference_precision.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+"
- << VALUE_DELIMITER;
- _logger.warning(
- "INFERENCE_PRECISION_HINT property is not suppored by this compiler version. Removing from parameters");
- content = std::regex_replace(content, std::regex(precstr.str()), "");
- }
-
- /// Replacing NPU_TILES (for all versions) with NPU_DPU_GROUPS for backwards compatibility
- if (std::regex_search(content, std::regex(ov::intel_npu::tiles.name()))) {
- _logger.warning("NPU_TILES property is not suppored by this compiler version. Swaping it to "
- "NPU_DPU_GROUPS (obsolete)");
- content = std::regex_replace(content, std::regex(ov::intel_npu::tiles.name()), "NPU_DPU_GROUPS");
- }
-
- // Batch mode property is not supported in versions < 5.5 - need to remove it
- if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 5)) {
- std::ostringstream batchstr;
- batchstr << ov::intel_npu::batch_mode.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+"
- << VALUE_DELIMITER;
-
- _logger.warning("NPU_BATCH_MODE property is not suppored by this compiler version. Removing from parameters");
- content = std::regex_replace(content, std::regex(batchstr.str()), "");
- }
-
- // EXECUTION_MODE_HINT is not supported in versions < 5.6 - need to remove it
- if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 6)) {
- std::ostringstream batchstr;
- batchstr << ov::hint::execution_mode.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+"
- << VALUE_DELIMITER;
- _logger.warning(
- "EXECUTION_MODE_HINT property is not suppored by this compiler version. Removing from parameters");
- content = std::regex_replace(content, std::regex(batchstr.str()), "");
- }
-
- // Remove the properties that are not used by the compiler
- // WorkloadType is used only by compiled model
- std::ostringstream workloadtypestr;
- workloadtypestr << ov::workload_type.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+" << VALUE_DELIMITER;
- content = std::regex_replace(content, std::regex(workloadtypestr.str()), "");
- // Remove turbo property as it is not used by compiler
- std::ostringstream turbostring;
- turbostring << ov::intel_npu::turbo.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+" << VALUE_DELIMITER;
- content = std::regex_replace(content, std::regex(turbostring.str()), "");
- // Remove Bypass UMD Caching propery
- std::ostringstream umdcachestring;
- umdcachestring << ov::intel_npu::bypass_umd_caching.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+"
- << VALUE_DELIMITER;
- content = std::regex_replace(content, std::regex(umdcachestring.str()), "");
-
- // FINAL step to convert prefixes of remaining params, to ensure backwards compatibility
- // From 5.0.0, driver compiler start to use NPU_ prefix, the old version uses VPU_ prefix
- if (compilerVersion.major < 5) {
- std::regex reg("NPU_");
- content = std::regex_replace(content, reg, "VPU_");
- // From 4.0.0, driver compiler start to use VPU_ prefix, the old version uses VPUX_ prefix
- if (compilerVersion.major < 4) {
- // Replace VPU_ with VPUX_ for old driver compiler
- std::regex reg("VPU_");
- content = std::regex_replace(content, reg, "VPUX_");
- }
- }
-
- return "--config " + content;
-}
-
-// Parse the result string of query from foramt <name_0><name_1><name_2> to unordered_set of string
-static std::unordered_set<std::string> parseQueryResult(std::vector<char>& data) {
- std::string dataString(data.begin(), data.end());
- std::unordered_set<std::string> result;
- size_t i = 0, start = 0;
- while (i < dataString.length()) {
- if (dataString[i] == '<') {
- start = ++i;
- } else if (dataString[i] == '>') {
- std::string temp(dataString.begin() + start, dataString.begin() + i);
- result.insert(temp);
- i++;
- } else {
- i++;
- }
- }
- return result;
-}
-
-// For ext version < 1.3, query is unsupported, return empty result and add debug log here
-template <ze_graph_ext_version_t TableExtension>
-template <ze_graph_ext_version_t T, std::enable_if_t<NotSupportQuery(T), bool>>
-std::unordered_set<std::string> LevelZeroCompilerInDriver<TableExtension>::queryImpl(
- const std::shared_ptr<const ov::Model>& /*model*/,
- const Config&) const {
- _logger.info("queryImpl - Driver version is less than 1.3, queryNetwork is unsupported.");
- return std::unordered_set<std::string>();
-}
-
-// For ext version == 1.3 && == 1.4
-template <ze_graph_ext_version_t TableExtension>
-template <ze_graph_ext_version_t T, std::enable_if_t<SupportAPIGraphQueryNetworkV1(T), bool>>
-ze_result_t LevelZeroCompilerInDriver<TableExtension>::seriazlideIRModelAndQueryNetworkCreateV1(
- const std::shared_ptr<const ov::Model>& model,
- const Config& config,
- ze_device_graph_properties_t deviceGraphProperties,
- const ze_device_handle_t& _deviceHandle,
- ze_graph_query_network_handle_t& hGraphQueryNetwork) const {
- ze_graph_compiler_version_info_t& compilerVersion = deviceGraphProperties.compilerVersion;
-
- auto serializedIR = serializeIR(model, compilerVersion);
-
- std::string buildFlags;
- buildFlags += serializeConfig(config, compilerVersion);
- _logger.debug("queryImpl build flags : %s", buildFlags.c_str());
-
- ze_graph_desc_t desc = {ZE_STRUCTURE_TYPE_GRAPH_DESC_PROPERTIES,
- nullptr,
- ZE_GRAPH_FORMAT_NGRAPH_LITE,
- serializedIR.first,
- serializedIR.second.get(),
- buildFlags.c_str()};
-
- // Create querynetwork handle
- ze_result_t result = _graphDdiTableExt.pfnQueryNetworkCreate(_context, _deviceHandle, &desc, &hGraphQueryNetwork);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("seriazlideIRModelAndQueryNetworkCreateV1", result, _graphDdiTableExt);
-
- return result;
-}
-
-// For ext version == 1.3 && == 1.4, query is supported, calling querynetwork api in _graphDdiTableExt
-template <ze_graph_ext_version_t TableExtension>
-template <ze_graph_ext_version_t T, std::enable_if_t<SupportAPIGraphQueryNetworkV1(T), bool>>
-std::unordered_set<std::string> LevelZeroCompilerInDriver<TableExtension>::queryImpl(
- const std::shared_ptr<const ov::Model>& model,
- const Config& config) const {
- _logger.info("queryImpl - Calling queryNetwork of 1.3 version.");
-
- ze_device_graph_properties_t deviceGraphProperties{};
- auto result = _graphDdiTableExt.pfnDeviceGetGraphProperties(_deviceHandle, &deviceGraphProperties);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnDeviceGetGraphProperties", result, _graphDdiTableExt);
-
- ze_graph_query_network_handle_t hGraphQueryNetwork = nullptr;
-
- result = seriazlideIRModelAndQueryNetworkCreateV1(model,
- config,
- deviceGraphProperties,
- _deviceHandle,
- hGraphQueryNetwork);
-
- return getQueryResultFromSupportedLayers(result, hGraphQueryNetwork);
-}
-
-// For ext version >= 1.5
-template <ze_graph_ext_version_t TableExtension>
-template <ze_graph_ext_version_t T, std::enable_if_t<SupportAPIGraphQueryNetworkV2(T), bool>>
-ze_result_t LevelZeroCompilerInDriver<TableExtension>::seriazlideIRModelAndQueryNetworkCreateV2(
- const std::shared_ptr<const ov::Model>& model,
- const Config& config,
- ze_device_graph_properties_t deviceGraphProperties,
- const ze_device_handle_t& _deviceHandle,
- ze_graph_query_network_handle_t& hGraphQueryNetwork) const {
- ze_graph_compiler_version_info_t& compilerVersion = deviceGraphProperties.compilerVersion;
-
- auto serializedIR = serializeIR(model, compilerVersion);
-
- std::string buildFlags;
- buildFlags += serializeConfig(config, compilerVersion);
- _logger.debug("queryImpl build flags : %s", buildFlags.c_str());
-
- ze_graph_desc_2_t desc = {ZE_STRUCTURE_TYPE_GRAPH_DESC_PROPERTIES,
- nullptr,
- ZE_GRAPH_FORMAT_NGRAPH_LITE,
- serializedIR.first,
- serializedIR.second.get(),
- buildFlags.c_str(),
- ZE_GRAPH_FLAG_NONE};
-
- // Create querynetwork handle
- _logger.debug("seriazlideIRModelAndQueryNetworkCreateV2 - performing pfnQueryNetworkCreate2");
- ze_result_t result = _graphDdiTableExt.pfnQueryNetworkCreate2(_context, _deviceHandle, &desc, &hGraphQueryNetwork);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("seriazlideIRModelAndQueryNetworkCreateV2", result, _graphDdiTableExt);
-
- return result;
-}
-
-// For ext version >= 1.5
-template <ze_graph_ext_version_t TableExtension>
-template <ze_graph_ext_version_t T, std::enable_if_t<SupportAPIGraphQueryNetworkV2(T), bool>>
-std::unordered_set<std::string> LevelZeroCompilerInDriver<TableExtension>::queryImpl(
- const std::shared_ptr<const ov::Model>& model,
- const Config& config) const {
- _logger.debug("queryImpl - Calling queryNetwork of 1.5 version.");
-
- ze_device_graph_properties_t deviceGraphProperties{};
- auto result = _graphDdiTableExt.pfnDeviceGetGraphProperties(_deviceHandle, &deviceGraphProperties);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnDeviceGetGraphProperties", result, _graphDdiTableExt);
-
- ze_graph_query_network_handle_t hGraphQueryNetwork = nullptr;
-
- result = seriazlideIRModelAndQueryNetworkCreateV2(model,
- config,
- deviceGraphProperties,
- _deviceHandle,
- hGraphQueryNetwork);
-
- return getQueryResultFromSupportedLayers(result, hGraphQueryNetwork);
-}
-
-template <ze_graph_ext_version_t TableExtension>
-template <ze_graph_ext_version_t T, std::enable_if_t<!NotSupportQuery(T), bool>>
-std::unordered_set<std::string> LevelZeroCompilerInDriver<TableExtension>::getQueryResultFromSupportedLayers(
- ze_result_t result,
- ze_graph_query_network_handle_t& hGraphQueryNetwork) const {
- // Get the size of query result
- size_t size = 0;
- result = _graphDdiTableExt.pfnQueryNetworkGetSupportedLayers(hGraphQueryNetwork, &size, nullptr);
- if (ZE_RESULT_SUCCESS != result) {
- _graphDdiTableExt.pfnQueryNetworkDestroy(hGraphQueryNetwork);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnQueryNetworkGetSupportedLayers get size of query result",
- result,
- _graphDdiTableExt);
- }
-
- // Get the result data of query
- std::vector<char> supportedLayers(size);
- result = _graphDdiTableExt.pfnQueryNetworkGetSupportedLayers(hGraphQueryNetwork, &size, supportedLayers.data());
- if (ZE_RESULT_SUCCESS != result) {
- _graphDdiTableExt.pfnQueryNetworkDestroy(hGraphQueryNetwork);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnQueryNetworkGetSupportedLayers get result data of query",
- result,
- _graphDdiTableExt);
- }
-
- result = _graphDdiTableExt.pfnQueryNetworkDestroy(hGraphQueryNetwork);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnQueryNetworkDestroy", result, _graphDdiTableExt);
-
- return parseQueryResult(supportedLayers);
-}
-
-template <ze_graph_ext_version_t TableExtension>
-ov::SupportedOpsMap LevelZeroCompilerInDriver<TableExtension>::query(const std::shared_ptr<const ov::Model>& model,
- const Config& config) const {
- _logger.debug("query start");
-
- ov::SupportedOpsMap result;
- const std::string deviceName = "NPU";
-
- try {
- const auto supportedLayers = queryImpl(model, config);
- for (auto&& layerName : supportedLayers) {
- result.emplace(layerName, deviceName);
- }
- _logger.info("For given model, there are %d supported layers", supportedLayers.size());
- } catch (std::exception& e) {
- OPENVINO_THROW("Fail in calling querynetwork : ", e.what());
- }
-
- _logger.debug("query end");
- return result;
-}
-
-// For ext version <1.5, calling pfnCreate api in _graphDdiTableExt
-template <ze_graph_ext_version_t TableExtension>
-template <ze_graph_ext_version_t T, std::enable_if_t<NotSupportGraph2(T), bool>>
-ze_result_t LevelZeroCompilerInDriver<TableExtension>::createGraph(const ze_graph_format_t& format,
- const SerializedIR& serializedIR,
- const std::string& buildFlags,
- const uint32_t& /*flags*/,
- ze_graph_handle_t* graph) const {
- ze_graph_desc_t desc = {ZE_STRUCTURE_TYPE_GRAPH_DESC_PROPERTIES,
- nullptr,
- format,
- serializedIR.first,
- serializedIR.second.get(),
- buildFlags.c_str()};
-
- _logger.debug("createGraph - performing pfnCreate");
- // Create querynetwork handle
- auto result = _graphDdiTableExt.pfnCreate(_context, _deviceHandle, &desc, graph);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnCreate", result, _graphDdiTableExt);
-
- return result;
-}
-
-// For ext version >= 1.5, calling pfnCreate2 api in _graphDdiTableExt
-template <ze_graph_ext_version_t TableExtension>
-template <ze_graph_ext_version_t T, std::enable_if_t<!NotSupportGraph2(T), bool>>
-ze_result_t LevelZeroCompilerInDriver<TableExtension>::createGraph(const ze_graph_format_t& format,
- const SerializedIR& serializedIR,
- const std::string& buildFlags,
- const uint32_t& flags,
- ze_graph_handle_t* graph) const {
- ze_graph_desc_2_t desc = {ZE_STRUCTURE_TYPE_GRAPH_DESC_PROPERTIES,
- nullptr,
- format,
- serializedIR.first,
- serializedIR.second.get(),
- buildFlags.c_str(),
- flags};
-
- _logger.debug("createGraph - performing pfnCreate2");
- // Create querynetwork handle
- auto result = _graphDdiTableExt.pfnCreate2(_context, _deviceHandle, &desc, graph);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnCreate2", result, _graphDdiTableExt);
-
- return result;
-}
-template <ze_graph_ext_version_t TableExtension>
-ze_result_t LevelZeroCompilerInDriver<TableExtension>::seriazlideIRModelAndCreateGraph(
- const std::shared_ptr<const ov::Model>& model,
- const Config& config,
- ze_device_graph_properties_t deviceGraphProperties,
- ze_graph_handle_t& graphHandle) const {
- const ze_graph_compiler_version_info_t& compilerVersion = deviceGraphProperties.compilerVersion;
- auto serializedIR = serializeIR(model, compilerVersion);
-
- ze_graph_format_t format = ZE_GRAPH_FORMAT_NGRAPH_LITE;
-
- std::string buildFlags;
- const bool useIndices = !((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 9));
-
- buildFlags += serializeIOInfo(model, useIndices);
- buildFlags += " ";
- buildFlags += serializeConfig(config, const_cast<ze_graph_compiler_version_info_t&>(compilerVersion));
-
- _logger.debug("compileIR Build flags : %s", buildFlags.c_str());
-
- // If UMD Caching is requested to be bypassed or if OV cache is enabled, disable driver caching
- uint32_t flags = ZE_GRAPH_FLAG_NONE;
- const auto set_cache_dir = config.get<CACHE_DIR>();
- if (!set_cache_dir.empty() || config.get<BYPASS_UMD_CACHING>()) {
- flags = flags | ZE_GRAPH_FLAG_DISABLE_CACHING;
- }
-
- _logger.info("compileIR Using extension version: %s", typeid(TableExtension).name());
- ze_result_t result = createGraph(format, serializedIR, buildFlags, flags, &graphHandle);
-
- return result;
-}
-
-template <ze_graph_ext_version_t TableExtension>
-NetworkDescription LevelZeroCompilerInDriver<TableExtension>::compile(const std::shared_ptr<const ov::Model>& model,
- const Config& config) const {
- _logger.debug("compile start");
-
- ze_device_graph_properties_t deviceGraphProperties{};
- auto result = _graphDdiTableExt.pfnDeviceGetGraphProperties(_deviceHandle, &deviceGraphProperties);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnDeviceGetGraphProperties, Failed to compile network.",
- result,
- _graphDdiTableExt);
-
- // Graph handle should be used only in scope of compile / parse functions.
- ze_graph_handle_t graphHandle;
-
- result = seriazlideIRModelAndCreateGraph(model, config, deviceGraphProperties, graphHandle);
-
- auto networkMeta = getNetworkMeta(graphHandle);
- networkMeta.name = model->get_friendly_name();
-
- _logger.debug("compile end");
-
- auto networkDescription = NetworkDescription(std::move(networkMeta));
- return networkDescription;
-}
-
-template <ze_graph_ext_version_t TableExtension>
-NetworkMetadata LevelZeroCompilerInDriver<TableExtension>::parse(const std::vector<uint8_t>& network,
- const Config& config) const {
- OV_ITT_TASK_CHAIN(PARSE_BLOB, itt::domains::NPUPlugin, "LevelZeroCompilerInDriver::parse", "desc");
- ze_graph_handle_t graphHandle;
-
- if (!network.empty()) {
- _logger.debug("Import network case");
- ze_graph_format_t format = ZE_GRAPH_FORMAT_NATIVE;
- ze_graph_desc_t desc{ZE_STRUCTURE_TYPE_GRAPH_DESC_PROPERTIES,
- nullptr,
- format,
- network.size(),
- network.data(),
- nullptr};
-
- auto result = _graphDdiTableExt.pfnCreate(_context, _deviceHandle, &desc, &graphHandle);
- OV_ITT_TASK_NEXT(PARSE_BLOB, "_graphDdiTableExt");
-
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnCreate", result, _graphDdiTableExt);
-
- } else {
- OPENVINO_THROW("Empty blob");
- }
-
- OV_ITT_TASK_NEXT(PARSE_BLOB, "getNetworkMeta");
- const auto networkMeta = getNetworkMeta(graphHandle);
- OV_ITT_TASK_NEXT(PARSE_BLOB, "NetworkDescription");
-
- _logger.debug("parse end");
- return networkMeta;
-}
-
-template <ze_graph_ext_version_t TableExtension>
-uint32_t LevelZeroCompilerInDriver<TableExtension>::getSupportedOpsetVersion() const {
- _logger.debug("getSupportedOpsetVersion start");
-
- ze_device_graph_properties_t graphProperties;
-
- auto result = _graphDdiTableExt.pfnDeviceGetGraphProperties(_deviceHandle, &graphProperties);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnDeviceGetGraphProperties", result, _graphDdiTableExt);
-
- const auto maxOpsetVersion = graphProperties.maxOVOpsetVersionSupported;
- _logger.info("getSupportedOpsetVersion Max supported version of opset in CiD: %d", maxOpsetVersion);
- _logger.debug("getSupportedOpset end");
- return maxOpsetVersion;
-}
-
-/**
- * @brief Extracts the I/O metadata from Level Zero specific structures and converts them into OpenVINO specific ones.
- *
- * @param arg The main Level Zero structure from which most metadata will be extracted.
- * @param metadata The secondary Level Zero structure from which metadata will be extracted. More specifically, the
- * argument is used for populating "shapeFromIRModel". Not providing this argument will lead to an empty value for the
- * referenced attribute.
- * @returns A descriptor object containing the metadata converted in OpenVINO specific structures.
- */
-static IODescriptor getIODescriptor(const ze_graph_argument_properties_3_t& arg,
- const std::optional<ze_graph_argument_metadata_t>& metadata) {
- ov::element::Type_t precision = toOVElementType(arg.devicePrecision);
- ov::Shape shapeFromCompiler, shapeFromIRModel;
- std::unordered_set<std::string> outputTensorNames;
-
- for (uint32_t id = 0; id < arg.associated_tensor_names_count; id++) {
- outputTensorNames.insert(arg.associated_tensor_names[id]);
- }
- for (uint32_t id = 0; id < arg.dims_count; id++) {
- shapeFromCompiler.push_back(arg.dims[id]);
- }
- if (metadata.has_value()) {
- for (uint32_t id = 0; id < metadata->shape_size; id++) {
- shapeFromIRModel.push_back(metadata->shape[id]);
- }
- }
-
- // Flags will be used instead of indices for informing the type of the current entry
- std::string nameFromCompiler = arg.name;
- bool isStateInput = false;
- bool isStateOutput = false;
- bool isShapeTensor = false;
- if (isStateInputName(nameFromCompiler)) {
- nameFromCompiler = nameFromCompiler.substr(READVALUE_PREFIX.length());
- isStateInput = true;
- } else if (isStateOutputName(nameFromCompiler)) {
- nameFromCompiler = nameFromCompiler.substr(ASSIGN_PREFIX.length());
- isStateOutput = true;
- } else if (isShapeTensorName(nameFromCompiler)) {
- nameFromCompiler = nameFromCompiler.substr(SHAPE_TENSOR_PREFIX.length());
- isShapeTensor = true;
- }
-
- return {std::move(nameFromCompiler),
- precision,
- std::move(shapeFromCompiler),
- isStateInput,
- isStateOutput,
- isShapeTensor,
- std::nullopt,
- arg.debug_friendly_name,
- std::move(outputTensorNames),
- metadata.has_value() ? std::optional(shapeFromIRModel) : std::nullopt};
-}
-
-template <ze_graph_ext_version_t TableExtension>
-template <ze_graph_ext_version_t T, std::enable_if_t<NotSupportArgumentMetadata(T), bool>>
-void LevelZeroCompilerInDriver<TableExtension>::getMetadata(ze_graph_dditable_ext_curr_t& graphDdiTableExt,
- ze_graph_handle_t graphHandle,
- uint32_t index,
- std::vector<IODescriptor>& inputs,
- std::vector<IODescriptor>& outputs) const {
- ze_graph_argument_properties_3_t arg;
- auto result = graphDdiTableExt.pfnGetArgumentProperties3(graphHandle, index, &arg);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetArgumentProperties3", result, _graphDdiTableExt);
-
- switch (arg.type) {
- case ZE_GRAPH_ARGUMENT_TYPE_INPUT: {
- inputs.push_back(getIODescriptor(arg, std::nullopt));
- } break;
- case ZE_GRAPH_ARGUMENT_TYPE_OUTPUT: {
- outputs.push_back(getIODescriptor(arg, std::nullopt));
- } break;
- default: {
- OPENVINO_THROW("Invalid ze_graph_argument_type_t found in ze_graph_argument_properties_3_t object: ", arg.type);
- }
- }
-}
-
-template <ze_graph_ext_version_t TableExtension>
-template <ze_graph_ext_version_t T, std::enable_if_t<!NotSupportArgumentMetadata(T), bool>>
-void LevelZeroCompilerInDriver<TableExtension>::getMetadata(ze_graph_dditable_ext_curr_t& graphDdiTableExt,
- ze_graph_handle_t graphHandle,
- uint32_t index,
- std::vector<IODescriptor>& inputs,
- std::vector<IODescriptor>& outputs) const {
- ze_graph_argument_properties_3_t arg;
- auto result = graphDdiTableExt.pfnGetArgumentProperties3(graphHandle, index, &arg);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetArgumentProperties3", result, _graphDdiTableExt);
-
- std::optional<ze_graph_argument_metadata_t> optionalMetadata = std::nullopt;
-
- if (!isStateInputName(arg.name) && !isStateOutputName(arg.name) && !isShapeTensorName(arg.name)) {
- ze_graph_argument_metadata_t metadata;
- result = graphDdiTableExt.pfnGraphGetArgumentMetadata(graphHandle, index, &metadata);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGraphGetArgumentMetadata", result, _graphDdiTableExt);
-
- optionalMetadata = std::optional(metadata);
- }
-
- switch (arg.type) {
- case ZE_GRAPH_ARGUMENT_TYPE_INPUT: {
- inputs.push_back(getIODescriptor(arg, optionalMetadata));
- } break;
- case ZE_GRAPH_ARGUMENT_TYPE_OUTPUT: {
- outputs.push_back(getIODescriptor(arg, optionalMetadata));
- } break;
- default: {
- OPENVINO_THROW("Invalid ze_graph_argument_type_t found in ze_graph_argument_properties_3_t object: ", arg.type);
- }
- }
-}
-
-template <ze_graph_ext_version_t TableExtension>
-NetworkMetadata LevelZeroCompilerInDriver<TableExtension>::getNetworkMeta(ze_graph_handle_t graphHandle) const {
- ze_graph_properties_t graphProperties{};
-
- auto result = _graphDdiTableExt.pfnGetProperties(graphHandle, &graphProperties);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetProperties", result, _graphDdiTableExt);
-
- NetworkMetadata meta;
-
- for (uint32_t index = 0; index < graphProperties.numGraphArgs; ++index) {
- getMetadata(_graphDdiTableExt, graphHandle, index, meta.inputs, meta.outputs);
- }
- // TODO: support this information in CiD [track: E#33479]
- meta.numStreams = 1;
- meta.bindRelatedDescriptors();
- // Store the graph handle as a void pointer, return the same graphHandle to backend for ZeroExecutor
- meta.graphHandle = static_cast<void*>(graphHandle);
-
- return meta;
-}
-
-template class LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_2>;
-template class LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_3>;
-template class LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_4>;
-template class LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_5>;
-template class LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_6>;
-template class LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_7>;
-template class LevelZeroCompilerInDriver<ZE_GRAPH_EXT_VERSION_1_8>;
-
-} // namespace driverCompilerAdapter
-} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler/CMakeLists.txt b/src/plugins/intel_npu/src/compiler_adapter/CMakeLists.txt
similarity index 85%
rename from src/plugins/intel_npu/src/compiler/CMakeLists.txt
rename to src/plugins/intel_npu/src/compiler_adapter/CMakeLists.txt
index 5c81e00945b..9f265b7f6d5 100644
--- a/src/plugins/intel_npu/src/compiler/CMakeLists.txt
+++ b/src/plugins/intel_npu/src/compiler_adapter/CMakeLists.txt
@@ -22,14 +22,9 @@ target_include_directories(${TARGET_NAME}
)
target_link_libraries(${TARGET_NAME}
- PUBLIC
+ PRIVATE
openvino::npu_al
openvino::npu_common
- PRIVATE
- openvino_npu_zero_result_parser
- openvino_npu_level_zero_backend
- openvino::runtime
- openvino::runtime::dev
ze_loader
)
diff --git a/src/plugins/intel_npu/src/compiler/include/custom_stream_buffer.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/custom_stream_buffer.hpp
similarity index 95%
rename from src/plugins/intel_npu/src/compiler/include/custom_stream_buffer.hpp
rename to src/plugins/intel_npu/src/compiler_adapter/include/custom_stream_buffer.hpp
index 419bada60dc..a1e8974682b 100644
--- a/src/plugins/intel_npu/src/compiler/include/custom_stream_buffer.hpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/custom_stream_buffer.hpp
@@ -7,7 +7,7 @@
#include <algorithm>
#include <streambuf>
-namespace intel_npu::driverCompilerAdapter {
+namespace intel_npu::driver_compiler_utils {
/**
* @brief Counter stream buffer, just counts the written bytes.
@@ -79,4 +79,4 @@ private:
OutputIt writeIt;
};
-} // namespace intel_npu::driverCompilerAdapter
+} // namespace intel_npu::driver_compiler_utils
diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/driver_compiler_adapter.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/driver_compiler_adapter.hpp
new file mode 100644
index 00000000000..dc000b99d74
--- /dev/null
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/driver_compiler_adapter.hpp
@@ -0,0 +1,64 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Compiler Interface
+
+#pragma once
+
+#include <ze_api.h>
+#include <ze_graph_ext.h>
+
+#include <type_traits>
+#include <utility>
+
+#include "intel_npu/common/npu.hpp"
+#include "intel_npu/config/config.hpp"
+#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/zero/zero_init.hpp"
+#include "ze_graph_ext_wrappers_interface.hpp"
+
+namespace intel_npu {
+
+class DriverCompilerAdapter final : public ICompilerAdapter {
+public:
+ DriverCompilerAdapter(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct);
+
+ std::shared_ptr<IGraph> compile(const std::shared_ptr<const ov::Model>& model, const Config& config) const override;
+
+ std::shared_ptr<IGraph> parse(std::vector<uint8_t> network, const Config& config) const override;
+
+ ov::SupportedOpsMap query(const std::shared_ptr<const ov::Model>& model, const Config& config) const override;
+
+private:
+ /**
+ * @brief Serialize input / output information to string format.
+ * @details Format:
+ * --inputs_precisions="0:<input1Precision> [1:<input2Precision>]"
+ * --inputs_layouts="0:<input1Layout> [1:<input2Layout>]"
+ * --outputs_precisions="0:<output1Precision>"
+ * --outputs_layouts="0:<output1Layout>"
+ *
+ * For older compiler versions, the name of the inputs/outputs may be used instead of their indices.
+ *
+ * Since the layout information is no longer an important part of the metadata values when using the 2.0 OV
+ * API, the layout fields shall be filled with default values in order to assure the backward compatibility
+ * with the driver.
+ */
+ std::string serializeIOInfo(const std::shared_ptr<const ov::Model>& model, const bool useIndices) const;
+
+ SerializedIR serializeIR(const std::shared_ptr<const ov::Model>& model,
+ ze_graph_compiler_version_info_t compilerVersion,
+ const uint32_t supportedOpsetVersion) const;
+
+ std::string serializeConfig(const Config& config, ze_graph_compiler_version_info_t compilerVersion) const;
+
+ std::shared_ptr<ZeroInitStructsHolder> _zeroInitStruct;
+ std::shared_ptr<ZeGraphExtWrappersInterface> _zeGraphExt;
+
+ ze_device_graph_properties_t _deviceGraphProperties = {};
+
+ Logger _logger;
+};
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/driver_graph.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/driver_graph.hpp
new file mode 100644
index 00000000000..f7ea940cf9a
--- /dev/null
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/driver_graph.hpp
@@ -0,0 +1,50 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Compiler Interface
+
+#pragma once
+
+#include <ze_graph_ext.h>
+
+#include "intel_npu/common/igraph.hpp"
+#include "intel_npu/utils/zero/zero_init.hpp"
+#include "ze_graph_ext_wrappers_interface.hpp"
+
+namespace intel_npu {
+
+class DriverGraph final : public IGraph {
+public:
+ DriverGraph(const std::shared_ptr<ZeGraphExtWrappersInterface>& zeGraphExt,
+ const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,
+ ze_graph_handle_t graphHandle,
+ NetworkMetadata metadata,
+ const Config& config,
+ std::optional<std::vector<uint8_t>> blob);
+
+ void export_blob(std::ostream& stream) const override;
+
+ std::vector<ov::ProfilingInfo> process_profiling_output(const std::vector<uint8_t>& profData,
+ const Config& config) const override;
+
+ void set_argument_value(uint32_t argi, const void* argv) const override;
+
+ void initialize(const Config& config) override;
+
+ ~DriverGraph() override;
+
+private:
+ bool release_blob(const Config& config);
+
+ std::shared_ptr<ZeGraphExtWrappersInterface> _zeGraphExt;
+ std::shared_ptr<ZeroInitStructsHolder> _zeroInitStruct;
+
+ Logger _logger;
+
+ // In the case of the import path, the blob is released after graph initialization so it can not be any longer
+ // exported
+ bool _blobIsReleased = false;
+};
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler/include/graph_transformations.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/ir_serializer.hpp
similarity index 93%
rename from src/plugins/intel_npu/src/compiler/include/graph_transformations.hpp
rename to src/plugins/intel_npu/src/compiler_adapter/include/ir_serializer.hpp
index 7c6ae33c629..300d2b2b71a 100644
--- a/src/plugins/intel_npu/src/compiler/include/graph_transformations.hpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/ir_serializer.hpp
@@ -15,7 +15,7 @@
* @brief Contain all required transformation on OpenVINO model in case for external compiler usage and
* providing forward compatibility (OV model with opset N+M, external compiler with opset N)
*/
-namespace intel_npu::driverCompilerAdapter {
+namespace intel_npu::driver_compiler_utils {
class IRSerializer {
public:
@@ -52,4 +52,4 @@ private:
size_t _weightsSize = 0;
};
-} // namespace intel_npu::driverCompilerAdapter
+} // namespace intel_npu::driver_compiler_utils
diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/plugin_compiler_adapter.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/plugin_compiler_adapter.hpp
new file mode 100644
index 00000000000..eab8a19627c
--- /dev/null
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/plugin_compiler_adapter.hpp
@@ -0,0 +1,37 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Compiler Interface
+
+#pragma once
+
+#include "intel_npu/common/npu.hpp"
+#include "intel_npu/icompiler.hpp"
+#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/zero/zero_init.hpp"
+#include "openvino/runtime/so_ptr.hpp"
+#include "ze_graph_ext_wrappers_interface.hpp"
+
+namespace intel_npu {
+
+class PluginCompilerAdapter final : public ICompilerAdapter {
+public:
+ PluginCompilerAdapter(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct);
+
+ std::shared_ptr<IGraph> compile(const std::shared_ptr<const ov::Model>& model, const Config& config) const override;
+
+ std::shared_ptr<IGraph> parse(std::vector<uint8_t> network, const Config& config) const override;
+
+ ov::SupportedOpsMap query(const std::shared_ptr<const ov::Model>& model, const Config& config) const override;
+
+private:
+ std::shared_ptr<ZeroInitStructsHolder> _zeroInitStruct;
+
+ std::shared_ptr<ZeGraphExtWrappersInterface> _zeGraphExt;
+ ov::SoPtr<ICompiler> _compiler;
+
+ Logger _logger;
+};
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/plugin_graph.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/plugin_graph.hpp
new file mode 100644
index 00000000000..1028112368e
--- /dev/null
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/plugin_graph.hpp
@@ -0,0 +1,49 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Compiler Interface
+
+#pragma once
+
+#include <ze_graph_ext.h>
+
+#include "intel_npu/common/igraph.hpp"
+#include "intel_npu/icompiler.hpp"
+#include "intel_npu/utils/zero/zero_init.hpp"
+#include "openvino/runtime/so_ptr.hpp"
+#include "ze_graph_ext_wrappers_interface.hpp"
+
+namespace intel_npu {
+
+class PluginGraph final : public IGraph {
+public:
+ PluginGraph(const std::shared_ptr<ZeGraphExtWrappersInterface>& zeGraphExt,
+ const ov::SoPtr<ICompiler>& compiler,
+ const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,
+ ze_graph_handle_t graphHandle,
+ NetworkMetadata metadata,
+ std::vector<uint8_t> blob,
+ const Config& config);
+
+ void export_blob(std::ostream& stream) const override;
+
+ std::vector<ov::ProfilingInfo> process_profiling_output(const std::vector<uint8_t>& profData,
+ const Config& config) const override;
+
+ void set_argument_value(uint32_t argi, const void* argv) const override;
+
+ void initialize(const Config& config) override;
+
+ ~PluginGraph() override;
+
+private:
+ std::shared_ptr<ZeGraphExtWrappersInterface> _zeGraphExt;
+ std::shared_ptr<ZeroInitStructsHolder> _zeroInitStruct;
+
+ const ov::SoPtr<ICompiler> _compiler;
+
+ Logger _logger;
+};
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers.hpp
new file mode 100644
index 00000000000..1bc58b153a4
--- /dev/null
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers.hpp
@@ -0,0 +1,159 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <ze_api.h>
+#include <ze_graph_ext.h>
+
+#include <type_traits>
+#include <utility>
+
+#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/zero/zero_init.hpp"
+#include "intel_npu/utils/zero/zero_types.hpp"
+#include "ze_graph_ext_wrappers_interface.hpp"
+
+namespace intel_npu {
+
+#define NotSupportQuery(T) (T == ZE_GRAPH_EXT_VERSION_1_2)
+
+// ext version == 1.3 && 1.4, support API (pfnQueryNetworkCreate, pfnQueryNetworkDestroy,
+// pfnQueryNetworkGetSupportedLayers)
+#define SupportAPIGraphQueryNetworkV1(T) (T == ZE_GRAPH_EXT_VERSION_1_3 || T == ZE_GRAPH_EXT_VERSION_1_4)
+
+// ext version >= 1.5, support API (pfnCreate2, pfnQueryNetworkCreate2, pfnQueryContextMemory)
+#define SupportAPIGraphQueryNetworkV2(T) ((!NotSupportQuery(T) && !SupportAPIGraphQueryNetworkV1(T)))
+
+// For ext version >= 1.5, pfnCreate2 api is avaible
+#define NotSupportGraph2(T) \
+ (T == ZE_GRAPH_EXT_VERSION_1_2 || T == ZE_GRAPH_EXT_VERSION_1_3 || T == ZE_GRAPH_EXT_VERSION_1_4)
+
+// A bug inside the driver makes the "pfnGraphGetArgumentMetadata" call not safe for use prior to
+// "ze_graph_dditable_ext_1_6_t".
+// See: E#117498
+#define NotSupportArgumentMetadata(T) \
+ (T == ZE_GRAPH_EXT_VERSION_1_2 || T == ZE_GRAPH_EXT_VERSION_1_3 || T == ZE_GRAPH_EXT_VERSION_1_4 || \
+ T == ZE_GRAPH_EXT_VERSION_1_5)
+
+#define UseCopyForNativeBinary(T) \
+ (T == ZE_GRAPH_EXT_VERSION_1_2 || T == ZE_GRAPH_EXT_VERSION_1_3 || T == ZE_GRAPH_EXT_VERSION_1_4 || \
+ T == ZE_GRAPH_EXT_VERSION_1_5 || T == ZE_GRAPH_EXT_VERSION_1_6)
+
+/**
+ * Adapter to use CiD through ZeroAPI
+ */
+template <ze_graph_ext_version_t TableExtension>
+class ZeGraphExtWrappers final : public ZeGraphExtWrappersInterface {
+public:
+ ZeGraphExtWrappers(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct);
+ ZeGraphExtWrappers(const ZeGraphExtWrappers&) = delete;
+ ZeGraphExtWrappers& operator=(const ZeGraphExtWrappers&) = delete;
+ ~ZeGraphExtWrappers();
+
+ std::unordered_set<std::string> queryGraph(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags) const override;
+ ze_graph_handle_t getGraphHandle(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags,
+ const uint32_t& flags) const override;
+
+ ze_graph_handle_t getGraphHandle(const std::vector<uint8_t>& network) const override;
+
+ NetworkMetadata getNetworkMeta(ze_graph_handle_t graphHandle) const override;
+
+ _ze_result_t destroyGraph(ze_graph_handle_t graphHandle) override;
+
+ void getGraphBinary(ze_graph_handle_t graphHandle,
+ std::vector<uint8_t>& blob,
+ const uint8_t*& blobPtr,
+ size_t& blobSize) const override;
+
+ void setGraphArgumentValue(ze_graph_handle_t graphHandle, uint32_t argi_, const void* argv) const override;
+
+ void initializeGraph(ze_graph_handle_t graphHandle, const Config& config) const override;
+
+private:
+ template <ze_graph_ext_version_t T = TableExtension, std::enable_if_t<!NotSupportQuery(T), bool> = true>
+ std::unordered_set<std::string> getQueryResultFromSupportedLayers(
+ ze_result_t result,
+ ze_graph_query_network_handle_t& hGraphQueryNetwork) const;
+
+ template <ze_graph_ext_version_t T = TableExtension,
+ typename std::enable_if_t<NotSupportArgumentMetadata(T), bool> = true>
+ void getMetadata(ze_graph_handle_t graphHandle,
+ uint32_t index,
+ std::vector<IODescriptor>& inputs,
+ std::vector<IODescriptor>& outputs) const;
+
+ template <ze_graph_ext_version_t T = TableExtension,
+ typename std::enable_if_t<!NotSupportArgumentMetadata(T), bool> = true>
+ void getMetadata(ze_graph_handle_t graphHandle,
+ uint32_t index,
+ std::vector<IODescriptor>& inputs,
+ std::vector<IODescriptor>& outputs) const;
+
+ template <ze_graph_ext_version_t T = TableExtension,
+ typename std::enable_if_t<UseCopyForNativeBinary(T), bool> = true>
+ void getNativeBinary(ze_graph_handle_t graphHandle,
+ std::vector<uint8_t>& blob,
+ const uint8_t*& blobPtr,
+ size_t& blobSize) const;
+
+ template <ze_graph_ext_version_t T = TableExtension,
+ typename std::enable_if_t<!UseCopyForNativeBinary(T), bool> = true>
+ void getNativeBinary(ze_graph_handle_t graphHandle,
+ std::vector<uint8_t>& /* unusedBlob */,
+ const uint8_t*& blobPtr,
+ size_t& blobSize) const;
+
+ template <ze_graph_ext_version_t T = TableExtension,
+ typename std::enable_if_t<SupportAPIGraphQueryNetworkV2(T), bool> = true>
+ ze_result_t queryNetworkCreateV2(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags,
+ ze_graph_query_network_handle_t& hGraphQueryNetwork) const;
+
+ // ext version >= 1.5, support API (pfnCreate2, pfnQueryNetworkCreate2, pfnQueryContextMemory)
+ template <ze_graph_ext_version_t T = TableExtension,
+ typename std::enable_if_t<SupportAPIGraphQueryNetworkV2(T), bool> = true>
+ std::unordered_set<std::string> queryImpl(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags) const;
+
+ template <ze_graph_ext_version_t T = TableExtension,
+ typename std::enable_if_t<SupportAPIGraphQueryNetworkV1(T), bool> = true>
+ ze_result_t queryNetworkCreateV1(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags,
+ ze_graph_query_network_handle_t& hGraphQueryNetwork) const;
+
+ // ext version == 1.3 && 1.4, support API (pfnQueryNetworkCreate, pfnQueryNetworkDestroy,
+ // pfnQueryNetworkGetSupportedLayers)
+ template <ze_graph_ext_version_t T = TableExtension,
+ typename std::enable_if_t<SupportAPIGraphQueryNetworkV1(T), bool> = true>
+ std::unordered_set<std::string> queryImpl(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags) const;
+
+ // For ext version < 1.3
+ template <ze_graph_ext_version_t T = TableExtension, typename std::enable_if_t<NotSupportQuery(T), bool> = true>
+ std::unordered_set<std::string> queryImpl(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags) const;
+
+ template <ze_graph_ext_version_t T = TableExtension, typename std::enable_if_t<NotSupportGraph2(T), bool> = true>
+ void createGraph(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags,
+ const uint32_t& flags,
+ ze_graph_handle_t* graph) const;
+
+ template <ze_graph_ext_version_t T = TableExtension, typename std::enable_if_t<!NotSupportGraph2(T), bool> = true>
+ void createGraph(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags,
+ const uint32_t& flags,
+ ze_graph_handle_t* graph) const;
+
+ void initialize_graph_through_command_list(ze_graph_handle_t graphHandle, const Config& config) const;
+
+ std::shared_ptr<ZeroInitStructsHolder> _zeroInitStruct;
+
+ Logger _logger;
+};
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers_interface.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers_interface.hpp
new file mode 100644
index 00000000000..ac44f9853e1
--- /dev/null
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers_interface.hpp
@@ -0,0 +1,42 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <ze_graph_ext.h>
+
+#include "intel_npu/network_metadata.hpp"
+
+namespace intel_npu {
+
+using SerializedIR = std::pair<size_t, std::shared_ptr<uint8_t>>;
+
+class ZeGraphExtWrappersInterface {
+public:
+ virtual std::unordered_set<std::string> queryGraph(SerializedIR serializedIR,
+ const std::string& buildFlags) const = 0;
+
+ virtual ze_graph_handle_t getGraphHandle(SerializedIR serializedIR,
+ const std::string& buildFlags,
+ const uint32_t& flags) const = 0;
+
+ virtual ze_graph_handle_t getGraphHandle(const std::vector<uint8_t>& network) const = 0;
+
+ virtual NetworkMetadata getNetworkMeta(ze_graph_handle_t graphHandle) const = 0;
+
+ virtual _ze_result_t destroyGraph(ze_graph_handle_t graphHandle) = 0;
+
+ virtual void getGraphBinary(ze_graph_handle_t graphHandle,
+ std::vector<uint8_t>& blob,
+ const uint8_t*& blobPtr,
+ size_t& blobSize) const = 0;
+
+ virtual void setGraphArgumentValue(ze_graph_handle_t graphHandle, uint32_t argi_, const void* argv) const = 0;
+
+ virtual void initializeGraph(ze_graph_handle_t graphHandle, const Config& config) const = 0;
+
+ virtual ~ZeGraphExtWrappersInterface() = default;
+};
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/driver_compiler_adapter.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/driver_compiler_adapter.cpp
new file mode 100644
index 00000000000..b4da8a2bcc3
--- /dev/null
+++ b/src/plugins/intel_npu/src/compiler_adapter/src/driver_compiler_adapter.cpp
@@ -0,0 +1,606 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "driver_compiler_adapter.hpp"
+
+#include <ze_graph_ext.h>
+
+#include <regex>
+#include <string_view>
+
+#include "driver_graph.hpp"
+#include "intel_npu/common/itt.hpp"
+#include "intel_npu/config/common.hpp"
+#include "intel_npu/config/compiler.hpp"
+#include "intel_npu/config/runtime.hpp"
+#include "intel_npu/prefix.hpp"
+#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/zero/zero_api.hpp"
+#include "intel_npu/utils/zero/zero_result.hpp"
+#include "intel_npu/utils/zero/zero_utils.hpp"
+#include "ir_serializer.hpp"
+#include "openvino/core/model.hpp"
+#include "ze_graph_ext_wrappers.hpp"
+
+namespace {
+
+constexpr std::string_view INPUTS_PRECISIONS_KEY = "--inputs_precisions";
+constexpr std::string_view INPUTS_LAYOUTS_KEY = "--inputs_layouts";
+constexpr std::string_view OUTPUTS_PRECISIONS_KEY = "--outputs_precisions";
+constexpr std::string_view OUTPUTS_LAYOUTS_KEY = "--outputs_layouts";
+
+// <option key>="<option value>"
+constexpr std::string_view KEY_VALUE_SEPARATOR = "=";
+constexpr std::string_view VALUE_DELIMITER = "\""; // marks beginning and end of value
+
+// Format inside "<option value>"
+// <name1>:<value (precision / layout)> [<name2>:<value>]
+constexpr std::string_view NAME_VALUE_SEPARATOR = ":";
+constexpr std::string_view VALUES_SEPARATOR = " ";
+
+// Constants indicating the order indices needed to be applied as to perform conversions between legacy layout values
+const std::vector<size_t> NC_TO_CN_LAYOUT_DIMENSIONS_ORDER = {1, 0};
+const std::vector<size_t> NCHW_TO_NHWC_LAYOUT_DIMENSIONS_ORDER = {0, 2, 3, 1};
+const std::vector<size_t> NCDHW_TO_NDHWC_LAYOUT_DIMENSIONS_ORDER = {0, 2, 3, 4, 1};
+
+/**
+ * @brief A standard copy function concerning memory segments. Additional checks on the given arguments are performed
+ * before copying.
+ * @details This is meant as a replacement for the legacy "ie_memcpy" function coming from the OpenVINO API.
+ */
+void checkedMemcpy(void* destination, size_t destinationSize, void const* source, size_t numberOfBytes) {
+ if (numberOfBytes == 0) {
+ return;
+ }
+
+ OPENVINO_ASSERT(destination != nullptr, "Memcpy: received a null destination address");
+ OPENVINO_ASSERT(source != nullptr, "Memcpy: received a null source address");
+ OPENVINO_ASSERT(numberOfBytes <= destinationSize,
+ "Memcpy: the source buffer does not fit inside the destination one");
+ OPENVINO_ASSERT(numberOfBytes <= (destination > source ? ((uintptr_t)destination - (uintptr_t)source)
+ : ((uintptr_t)source - (uintptr_t)destination)),
+ "Memcpy: the offset between the two buffers does not allow a safe execution of the operation");
+
+ memcpy(destination, source, numberOfBytes);
+}
+
+/**
+ * @brief For driver backward compatibility reasons, the given value shall be converted to a string corresponding to the
+ * adequate legacy precision.
+ */
+std::string ovPrecisionToLegacyPrecisionString(const ov::element::Type& precision) {
+ switch (precision) {
+ case ov::element::Type_t::undefined:
+ return "UNSPECIFIED";
+ case ov::element::Type_t::f16:
+ return "FP16";
+ case ov::element::Type_t::f32:
+ return "FP32";
+ case ov::element::Type_t::f64:
+ return "FP64";
+ case ov::element::Type_t::bf16:
+ return "BF16";
+ case ov::element::Type_t::i4:
+ return "I4";
+ case ov::element::Type_t::i8:
+ return "I8";
+ case ov::element::Type_t::i16:
+ return "I16";
+ case ov::element::Type_t::i32:
+ return "I32";
+ case ov::element::Type_t::i64:
+ return "I64";
+ case ov::element::Type_t::u4:
+ return "U4";
+ case ov::element::Type_t::u8:
+ return "U8";
+ case ov::element::Type_t::u16:
+ return "U16";
+ case ov::element::Type_t::u32:
+ return "U32";
+ case ov::element::Type_t::u64:
+ return "U64";
+ case ov::element::Type_t::u1:
+ return "BIN";
+ case ov::element::Type_t::boolean:
+ return "BOOL";
+ case ov::element::Type_t::dynamic:
+ return "DYNAMIC";
+ default:
+ OPENVINO_THROW("Incorrect precision: ", precision);
+ }
+}
+
+/**
+ * @brief Gives the string representation of the default legacy layout value corresponding to the given rank.
+ * @details This is done in order to assure the backward compatibility with the driver. Giving a layout different from
+ * the default one may lead either to error or to accuracy failures since unwanted transposition layers may be
+ * introduced.
+ */
+std::string rankToLegacyLayoutString(const size_t rank) {
+ switch (rank) {
+ case 0:
+ return "**SCALAR**";
+ case 1:
+ return "C";
+ case 2:
+ return "NC";
+ case 3:
+ return "CHW";
+ case 4:
+ return "NCHW";
+ case 5:
+ return "NCDHW";
+ default:
+ return "BLOCKED";
+ }
+}
+
+} // namespace
+
+namespace intel_npu {
+
+DriverCompilerAdapter::DriverCompilerAdapter(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct)
+ : _zeroInitStruct(zeroInitStruct),
+ _logger("DriverCompilerAdapter", Logger::global().level()) {
+ _logger.debug("initialize DriverCompilerAdapter start");
+
+ uint32_t graphExtVersion = _zeroInitStruct->getGraphDdiTable().version();
+
+ _deviceGraphProperties.stype = ZE_STRUCTURE_TYPE_DEVICE_GRAPH_PROPERTIES;
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnDeviceGetGraphProperties(_zeroInitStruct->getDevice(),
+ &_deviceGraphProperties);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnDeviceGetGraphProperties", result, _zeroInitStruct->getGraphDdiTable());
+
+ _logger.info("DriverCompilerAdapter creating adapter using graphExtVersion");
+
+ switch (graphExtVersion) {
+ case ZE_GRAPH_EXT_VERSION_1_3:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_3>>(_zeroInitStruct);
+ break;
+ case ZE_GRAPH_EXT_VERSION_1_4:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_4>>(_zeroInitStruct);
+ break;
+ case ZE_GRAPH_EXT_VERSION_1_5:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_5>>(_zeroInitStruct);
+ break;
+ case ZE_GRAPH_EXT_VERSION_1_6:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_6>>(_zeroInitStruct);
+ break;
+ case ZE_GRAPH_EXT_VERSION_1_7:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_7>>(_zeroInitStruct);
+ break;
+ case ZE_GRAPH_EXT_VERSION_1_8:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_8>>(_zeroInitStruct);
+ break;
+ default:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_2>>(_zeroInitStruct);
+ break;
+ }
+
+ _logger.info("initialize DriverCompilerAdapter complete, using graphExtVersion: %d.%d",
+ ZE_MAJOR_VERSION(graphExtVersion),
+ ZE_MINOR_VERSION(graphExtVersion));
+}
+
+std::shared_ptr<IGraph> DriverCompilerAdapter::compile(const std::shared_ptr<const ov::Model>& model,
+ const Config& config) const {
+ OV_ITT_TASK_CHAIN(COMPILE_BLOB, itt::domains::NPUPlugin, "DriverCompilerAdapter", "compile");
+
+ const ze_graph_compiler_version_info_t& compilerVersion = _deviceGraphProperties.compilerVersion;
+ const auto maxOpsetVersion = _deviceGraphProperties.maxOVOpsetVersionSupported;
+ _logger.info("getSupportedOpsetVersion Max supported version of opset in CiD: %d", maxOpsetVersion);
+
+ _logger.debug("serialize IR");
+ auto serializedIR = serializeIR(model, compilerVersion, maxOpsetVersion);
+
+ std::string buildFlags;
+ const bool useIndices = !((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 9));
+
+ _logger.debug("build flags");
+ buildFlags += serializeIOInfo(model, useIndices);
+ buildFlags += " ";
+ buildFlags += serializeConfig(config, compilerVersion);
+
+ _logger.debug("compileIR Build flags : %s", buildFlags.c_str());
+
+ // If UMD Caching is requested to be bypassed or if OV cache is enabled, disable driver caching
+ uint32_t flags = ZE_GRAPH_FLAG_NONE;
+ const auto set_cache_dir = config.get<CACHE_DIR>();
+ if (!set_cache_dir.empty() || config.get<BYPASS_UMD_CACHING>()) {
+ flags = flags | ZE_GRAPH_FLAG_DISABLE_CACHING;
+ }
+
+ _logger.debug("compile start");
+ ze_graph_handle_t graphHandle = _zeGraphExt->getGraphHandle(std::move(serializedIR), buildFlags, flags);
+ _logger.debug("compile end");
+
+ OV_ITT_TASK_NEXT(COMPILE_BLOB, "getNetworkMeta");
+ auto networkMeta = _zeGraphExt->getNetworkMeta(graphHandle);
+ networkMeta.name = model->get_friendly_name();
+
+ return std::make_shared<DriverGraph>(_zeGraphExt,
+ _zeroInitStruct,
+ graphHandle,
+ std::move(networkMeta),
+ config,
+ std::nullopt);
+}
+
+std::shared_ptr<IGraph> DriverCompilerAdapter::parse(std::vector<uint8_t> network, const Config& config) const {
+ OV_ITT_TASK_CHAIN(PARSE_BLOB, itt::domains::NPUPlugin, "DriverCompilerAdapter", "parse");
+
+ _logger.debug("parse start");
+ ze_graph_handle_t graphHandle = _zeGraphExt->getGraphHandle(network);
+ _logger.debug("parse end");
+
+ OV_ITT_TASK_NEXT(PARSE_BLOB, "getNetworkMeta");
+ auto networkMeta = _zeGraphExt->getNetworkMeta(graphHandle);
+
+ return std::make_shared<DriverGraph>(_zeGraphExt,
+ _zeroInitStruct,
+ graphHandle,
+ std::move(networkMeta),
+ config,
+ std::optional<std::vector<uint8_t>>(std::move(network)));
+}
+
+ov::SupportedOpsMap DriverCompilerAdapter::query(const std::shared_ptr<const ov::Model>& model,
+ const Config& config) const {
+ OV_ITT_TASK_CHAIN(query_BLOB, itt::domains::NPUPlugin, "DriverCompilerAdapter", "query");
+
+ const ze_graph_compiler_version_info_t& compilerVersion = _deviceGraphProperties.compilerVersion;
+ const auto maxOpsetVersion = _deviceGraphProperties.maxOVOpsetVersionSupported;
+ _logger.info("getSupportedOpsetVersion Max supported version of opset in CiD: %d", maxOpsetVersion);
+
+ _logger.debug("serialize IR");
+ auto serializedIR = serializeIR(model, compilerVersion, maxOpsetVersion);
+
+ std::string buildFlags;
+ buildFlags += serializeConfig(config, compilerVersion);
+ _logger.debug("queryImpl build flags : %s", buildFlags.c_str());
+
+ ov::SupportedOpsMap result;
+ const std::string deviceName = "NPU";
+
+ try {
+ const auto supportedLayers = _zeGraphExt->queryGraph(std::move(serializedIR), buildFlags);
+ for (auto&& layerName : supportedLayers) {
+ result.emplace(layerName, deviceName);
+ }
+ _logger.info("For given model, there are %d supported layers", supportedLayers.size());
+ } catch (std::exception& e) {
+ OPENVINO_THROW("Fail in calling querynetwork : ", e.what());
+ }
+
+ _logger.debug("query end");
+ return result;
+}
+
+/**
+ * @brief Place xml + weights in sequential memory
+ * @details Format of the memory:
+ */
+SerializedIR DriverCompilerAdapter::serializeIR(const std::shared_ptr<const ov::Model>& model,
+ ze_graph_compiler_version_info_t compilerVersion,
+ const uint32_t supportedOpsetVersion) const {
+ driver_compiler_utils::IRSerializer irSerializer(model, supportedOpsetVersion);
+
+ // Contract between adapter and compiler in driver
+ const uint32_t maxNumberOfElements = 10;
+ const uint64_t maxSizeOfXML = std::numeric_limits<uint64_t>::max() / 3;
+ const uint64_t maxSizeOfWeights = maxSizeOfXML * 2;
+
+ const uint32_t numberOfInputData = 2;
+ const uint64_t xmlSize = static_cast<uint64_t>(irSerializer.getXmlSize());
+ const uint64_t weightsSize = static_cast<uint64_t>(irSerializer.getWeightsSize());
+
+ OPENVINO_ASSERT(numberOfInputData < maxNumberOfElements);
+ if (xmlSize >= maxSizeOfXML) {
+ OPENVINO_THROW("Xml file is too big to process. xmlSize: ", xmlSize, " >= maxSizeOfXML: ", maxSizeOfXML);
+ }
+ if (weightsSize >= maxSizeOfWeights) {
+ OPENVINO_THROW("Bin file is too big to process. xmlSize: ",
+ weightsSize,
+ " >= maxSizeOfWeights: ",
+ maxSizeOfWeights);
+ }
+
+ const uint64_t sizeOfSerializedIR = sizeof(compilerVersion) + sizeof(numberOfInputData) + sizeof(xmlSize) +
+ xmlSize + sizeof(weightsSize) + weightsSize;
+
+ // use array to avoid vector's memory zeroing overhead
+ std::shared_ptr<uint8_t> buffer(new uint8_t[sizeOfSerializedIR], std::default_delete<uint8_t[]>());
+ uint8_t* serializedIR = buffer.get();
+
+ uint64_t offset = 0;
+ checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &compilerVersion, sizeof(compilerVersion));
+ offset += sizeof(compilerVersion);
+
+ checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &numberOfInputData, sizeof(numberOfInputData));
+ offset += sizeof(numberOfInputData);
+ checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &xmlSize, sizeof(xmlSize));
+ offset += sizeof(xmlSize);
+ // xml data is filled in serializeModel()
+ uint64_t xmlOffset = offset;
+ offset += xmlSize;
+ checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &weightsSize, sizeof(weightsSize));
+ offset += sizeof(weightsSize);
+ // weights data is filled in serializeModel()
+ uint64_t weightsOffset = offset;
+ offset += weightsSize;
+
+ irSerializer.serializeModelToBuffer(serializedIR + xmlOffset, serializedIR + weightsOffset);
+
+ OPENVINO_ASSERT(offset == sizeOfSerializedIR);
+
+ return std::make_pair(sizeOfSerializedIR, buffer);
+}
+
+std::string DriverCompilerAdapter::serializeIOInfo(const std::shared_ptr<const ov::Model>& model,
+ const bool useIndices) const {
+ const ov::ParameterVector& parameters = model->get_parameters();
+ const ov::ResultVector& results = model->get_results();
+
+ std::stringstream inputsPrecisionSS;
+ std::stringstream inputsLayoutSS;
+ std::stringstream outputsPrecisionSS;
+ std::stringstream outputsLayoutSS;
+
+ inputsPrecisionSS << INPUTS_PRECISIONS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;
+ inputsLayoutSS << INPUTS_LAYOUTS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;
+ const auto getRankOrThrow = [](const ov::PartialShape& shape) -> size_t {
+ if (shape.rank().is_dynamic()) {
+ OPENVINO_THROW("Dynamic rank is not supported for NPU plugin");
+ }
+ return shape.rank().get_length();
+ };
+
+ if (!parameters.empty()) {
+ size_t parameterIndex = 0;
+
+ for (const std::shared_ptr<ov::op::v0::Parameter>& parameter : parameters) {
+ const auto precision = parameter->get_element_type();
+ const auto rank = getRankOrThrow(parameter->get_partial_shape());
+
+ if (parameterIndex != 0) {
+ inputsPrecisionSS << VALUES_SEPARATOR;
+ inputsLayoutSS << VALUES_SEPARATOR;
+ }
+
+ if (useIndices) {
+ inputsPrecisionSS << parameterIndex;
+ inputsLayoutSS << parameterIndex;
+ } else {
+ const std::string& name = parameter->get_friendly_name();
+
+ inputsPrecisionSS << name;
+ // Ticket: E-88902
+ inputsLayoutSS << name;
+ }
+
+ inputsPrecisionSS << NAME_VALUE_SEPARATOR << ovPrecisionToLegacyPrecisionString(precision);
+ inputsLayoutSS << NAME_VALUE_SEPARATOR << rankToLegacyLayoutString(rank);
+
+ ++parameterIndex;
+ }
+ }
+
+ inputsPrecisionSS << VALUE_DELIMITER;
+ inputsLayoutSS << VALUE_DELIMITER;
+
+ outputsPrecisionSS << OUTPUTS_PRECISIONS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;
+ outputsLayoutSS << OUTPUTS_LAYOUTS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;
+
+ size_t resultIndex = 0;
+ for (const std::shared_ptr<ov::op::v0::Result>& result : results) {
+ const auto precision = result->get_element_type();
+ const auto rank = getRankOrThrow(result->get_output_partial_shape(0));
+
+ if (resultIndex != 0) {
+ outputsPrecisionSS << VALUES_SEPARATOR;
+ outputsLayoutSS << VALUES_SEPARATOR;
+ }
+
+ if (useIndices) {
+ outputsPrecisionSS << resultIndex;
+ outputsLayoutSS << resultIndex;
+ } else {
+ const std::string& name = result->get_input_node_ptr(0)->get_friendly_name();
+
+ outputsPrecisionSS << name;
+ outputsLayoutSS << name;
+ }
+
+ outputsPrecisionSS << NAME_VALUE_SEPARATOR << ovPrecisionToLegacyPrecisionString(precision);
+ outputsLayoutSS << NAME_VALUE_SEPARATOR << rankToLegacyLayoutString(rank);
+
+ ++resultIndex;
+ }
+
+ outputsPrecisionSS << VALUE_DELIMITER;
+ outputsLayoutSS << VALUE_DELIMITER;
+
+ // One line without spaces to avoid parsing as config option inside CID
+ return inputsPrecisionSS.str() + VALUES_SEPARATOR.data() + inputsLayoutSS.str() + VALUES_SEPARATOR.data() +
+ outputsPrecisionSS.str() + VALUES_SEPARATOR.data() + outputsLayoutSS.str();
+}
+
+std::string DriverCompilerAdapter::serializeConfig(const Config& config,
+ ze_graph_compiler_version_info_t compilerVersion) const {
+ Logger logger("serializeConfig", Logger::global().level());
+
+ std::string content = config.toString();
+
+ logger.debug("Original content of config: %s", content.c_str());
+
+ // Remove optimization-level and performance-hint-override for old driver which not support them
+ if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 7)) {
+ std::string valueOfParams = config.get<COMPILATION_MODE_PARAMS>();
+ std::string keyOfOptL("optimization-level");
+ std::string keyOfPerfHO("performance-hint-override");
+ if (valueOfParams != "" && (valueOfParams.find(keyOfOptL) != std::string::npos ||
+ valueOfParams.find(keyOfPerfHO) != std::string::npos)) {
+ // Remove unsupported options from value
+ std::ostringstream optLevelStr;
+ optLevelStr << keyOfOptL << KEY_VALUE_SEPARATOR << "\\d+";
+ std::ostringstream perfHintStr;
+ perfHintStr << keyOfPerfHO << KEY_VALUE_SEPARATOR << "\\S+";
+ logger.warning("%s property is not suppored by this compiler version. Removing from parameters",
+ keyOfOptL.c_str());
+ valueOfParams = std::regex_replace(valueOfParams, std::regex(optLevelStr.str()), "");
+ logger.warning("%s property is not suppored by this compiler version. Removing from parameters",
+ keyOfPerfHO.c_str());
+ valueOfParams = std::regex_replace(valueOfParams, std::regex(perfHintStr.str()), "");
+
+ // Trim space
+ valueOfParams = std::regex_replace(valueOfParams, std::regex(R"(^\s+|\s+$)"), "");
+
+ // Replace the value in content with new value
+ std::ostringstream compilationParamsStr;
+ compilationParamsStr << ov::intel_npu::compilation_mode_params.name() << KEY_VALUE_SEPARATOR
+ << VALUE_DELIMITER << ".*" << VALUE_DELIMITER;
+ if (valueOfParams == "") {
+ logger.warning("Clear empty NPU_COMPILATION_MODE_PARAMS. Removing from parameters");
+ content = std::regex_replace(content, std::regex(compilationParamsStr.str()), "");
+ } else {
+ std::ostringstream newValue;
+ newValue << ov::intel_npu::compilation_mode_params.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER
+ << valueOfParams << VALUE_DELIMITER;
+ logger.warning("Replace value of NPU_COMPILATION_MODE_PARAMS with new value %s",
+ newValue.str().c_str());
+ content = std::regex_replace(content, std::regex(compilationParamsStr.str()), newValue.str().c_str());
+ }
+ }
+ }
+
+ // As a consequence of complying to the conventions established in the 2.0 OV API, the set of values corresponding
+ // to the "model priority" key has been modified cpu_pinning property is not supported in compilers < v5.2 - need to
+ // remove it
+ if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 2)) {
+ const auto& getTargetRegex = [](const ov::hint::Priority& priorityValue) -> std::regex {
+ std::ostringstream result;
+ result << ov::hint::model_priority.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << priorityValue
+ << VALUE_DELIMITER;
+ return std::regex(result.str());
+ };
+ const auto& getStringReplacement = [](const ov::intel_npu::LegacyPriority& priorityValue) -> std::string {
+ std::ostringstream result;
+ result << ov::intel_npu::legacy_model_priority.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER
+ << priorityValue << VALUE_DELIMITER;
+ return result.str();
+ };
+
+ // E.g. (valid as of writing this): MODEL_PRIORITY="MEDIUM" -> MODEL_PRIORITY="MODEL_PRIORITY_MED"
+ content = std::regex_replace(content,
+ getTargetRegex(ov::hint::Priority::LOW),
+ getStringReplacement(ov::intel_npu::LegacyPriority::LOW));
+ content = std::regex_replace(content,
+ getTargetRegex(ov::hint::Priority::MEDIUM),
+ getStringReplacement(ov::intel_npu::LegacyPriority::MEDIUM));
+ content = std::regex_replace(content,
+ getTargetRegex(ov::hint::Priority::HIGH),
+ getStringReplacement(ov::intel_npu::LegacyPriority::HIGH));
+
+ // Removing cpu_pinning from the command string
+ std::ostringstream pinningstr;
+ pinningstr << ov::hint::enable_cpu_pinning.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+"
+ << VALUE_DELIMITER;
+ logger.warning(
+ "ENABLE_CPU_PINNING property is not suppored by this compiler version. Removing from parameters");
+ content = std::regex_replace(content, std::regex(pinningstr.str()), "");
+ }
+
+ /// Stepping and max_tiles are not supported in versions < 5.3 - need to remove it
+ if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 3)) {
+ std::ostringstream stepstr;
+ stepstr << ov::intel_npu::stepping.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\d+"
+ << VALUE_DELIMITER;
+ std::ostringstream maxtilestr;
+ maxtilestr << ov::intel_npu::max_tiles.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\d+"
+ << VALUE_DELIMITER;
+ logger.warning("NPU_STEPPING property is not suppored by this compiler version. Removing from parameters");
+ content = std::regex_replace(content, std::regex(stepstr.str()), "");
+ logger.warning("NPU_MAX_TILES property is not suppored by this compiler version. Removing from parameters");
+ content = std::regex_replace(content, std::regex(maxtilestr.str()), "");
+ }
+
+ /// Removing INFERENCE_PRECISION_HINT for older compilers
+ if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 4)) {
+ std::ostringstream precstr;
+ precstr << ov::hint::inference_precision.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+"
+ << VALUE_DELIMITER;
+ logger.warning(
+ "INFERENCE_PRECISION_HINT property is not suppored by this compiler version. Removing from parameters");
+ content = std::regex_replace(content, std::regex(precstr.str()), "");
+ }
+
+ /// Replacing NPU_TILES (for all versions) with NPU_DPU_GROUPS for backwards compatibility
+ if (std::regex_search(content, std::regex(ov::intel_npu::tiles.name()))) {
+ logger.warning("NPU_TILES property is not suppored by this compiler version. Swaping it to "
+ "NPU_DPU_GROUPS (obsolete)");
+ content = std::regex_replace(content, std::regex(ov::intel_npu::tiles.name()), "NPU_DPU_GROUPS");
+ }
+
+ // Batch mode property is not supported in versions < 5.5 - need to remove it
+ if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 5)) {
+ std::ostringstream batchstr;
+ batchstr << ov::intel_npu::batch_mode.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+"
+ << VALUE_DELIMITER;
+
+ logger.warning("NPU_BATCH_MODE property is not suppored by this compiler version. Removing from parameters");
+ content = std::regex_replace(content, std::regex(batchstr.str()), "");
+ }
+
+ // EXECUTION_MODE_HINT is not supported in versions < 5.6 - need to remove it
+ if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 6)) {
+ std::ostringstream batchstr;
+ batchstr << ov::hint::execution_mode.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+"
+ << VALUE_DELIMITER;
+ logger.warning(
+ "EXECUTION_MODE_HINT property is not suppored by this compiler version. Removing from parameters");
+ content = std::regex_replace(content, std::regex(batchstr.str()), "");
+ }
+
+ // NPU_DEFER_WEIGHTS_LOAD is not supported in versions < 6.2 - need to remove it
+ if ((compilerVersion.major < 6) || (compilerVersion.major == 6 && compilerVersion.minor < 2)) {
+ std::ostringstream batchstr;
+ batchstr << ov::intel_npu::defer_weights_load.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+"
+ << VALUE_DELIMITER;
+ logger.warning(
+ "NPU_DEFER_WEIGHTS_LOAD property is not suppored by this compiler version. Removing from parameters");
+ content = std::regex_replace(content, std::regex(batchstr.str()), "");
+ }
+
+ // Remove the properties that are not used by the compiler WorkloadType is used only by compiled model
+ std::ostringstream workloadtypestr;
+ workloadtypestr << ov::workload_type.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+" << VALUE_DELIMITER;
+ content = std::regex_replace(content, std::regex(workloadtypestr.str()), "");
+ // Remove turbo property as it is not used by compiler
+ std::ostringstream turbostring;
+ turbostring << ov::intel_npu::turbo.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+" << VALUE_DELIMITER;
+ content = std::regex_replace(content, std::regex(turbostring.str()), "");
+ // Remove Bypass UMD Caching propery
+ std::ostringstream umdcachestring;
+ umdcachestring << ov::intel_npu::bypass_umd_caching.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+"
+ << VALUE_DELIMITER;
+ content = std::regex_replace(content, std::regex(umdcachestring.str()), "");
+
+ // FINAL step to convert prefixes of remaining params, to ensure backwards compatibility
+ // From 5.0.0, driver compiler start to use NPU_ prefix, the old version uses VPU_ prefix
+ if (compilerVersion.major < 5) {
+ std::regex reg("NPU_");
+ content = std::regex_replace(content, reg, "VPU_");
+ // From 4.0.0, driver compiler start to use VPU_ prefix, the old version uses VPUX_ prefix
+ if (compilerVersion.major < 4) {
+ // Replace VPU_ with VPUX_ for old driver compiler
+ std::regex reg("VPU_");
+ content = std::regex_replace(content, reg, "VPUX_");
+ }
+ }
+
+ return "--config " + content;
+}
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/driver_graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/driver_graph.cpp
new file mode 100644
index 00000000000..c0b15292662
--- /dev/null
+++ b/src/plugins/intel_npu/src/compiler_adapter/src/driver_graph.cpp
@@ -0,0 +1,164 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "driver_graph.hpp"
+
+#include "intel_npu/config/common.hpp"
+#include "intel_npu/config/runtime.hpp"
+
+namespace intel_npu {
+
+DriverGraph::DriverGraph(const std::shared_ptr<ZeGraphExtWrappersInterface>& zeGraphExt,
+ const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,
+ ze_graph_handle_t graphHandle,
+ NetworkMetadata metadata,
+ const Config& config,
+ std::optional<std::vector<uint8_t>> blob)
+ : IGraph(graphHandle, std::move(metadata), std::move(blob)),
+ _zeGraphExt(zeGraphExt),
+ _zeroInitStruct(zeroInitStruct),
+ _logger("DriverGraph", config.get<LOG_LEVEL>()) {
+ if (_zeGraphExt == nullptr) {
+ OPENVINO_THROW("Zero compiler adapter wasn't initialized");
+ }
+
+ if (!config.get<CREATE_EXECUTOR>() || config.get<DEFER_WEIGHTS_LOAD>()) {
+ _logger.info("Graph initialize is deferred from the \"Graph\" constructor");
+ return;
+ }
+
+ initialize(config);
+}
+
+void DriverGraph::export_blob(std::ostream& stream) const {
+ const uint8_t* blobPtr = nullptr;
+ size_t blobSize = -1;
+ std::vector<uint8_t> blob;
+
+ if (_blobIsReleased) {
+ OPENVINO_THROW("Model was imported (not compiled) by the plugin. Model export is forbidden in this case!");
+ }
+
+ _zeGraphExt->getGraphBinary(_handle, blob, blobPtr, blobSize);
+
+ stream.write(reinterpret_cast<const char*>(blobPtr), blobSize);
+
+ if (!stream) {
+ _logger.error("Write blob to stream failed. Blob is broken!");
+ return;
+ }
+
+ if (_logger.level() >= ov::log::Level::INFO) {
+ std::uint32_t result = 1171117u;
+ for (const uint8_t* it = blobPtr; it != blobPtr + blobSize; ++it) {
+ result = ((result << 7) + result) + static_cast<uint32_t>(*it);
+ }
+
+ std::stringstream str;
+ str << "Blob size: " << blobSize << ", hash: " << std::hex << result;
+ _logger.info(str.str().c_str());
+ }
+ _logger.info("Write blob to stream successfully.");
+}
+
+std::vector<ov::ProfilingInfo> DriverGraph::process_profiling_output(const std::vector<uint8_t>& profData,
+ const Config& config) const {
+ OPENVINO_THROW("Profiling post-processing is not supported.");
+}
+
+void DriverGraph::set_argument_value(uint32_t argi, const void* argv) const {
+ _zeGraphExt->setGraphArgumentValue(_handle, argi, argv);
+}
+
+void DriverGraph::initialize(const Config& config) {
+ _logger.debug("Graph initialize start");
+
+ _logger.debug("performing pfnGetProperties");
+ ze_graph_properties_t props{};
+ props.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetProperties(_handle, &props);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetProperties", result, _zeroInitStruct->getGraphDdiTable());
+
+ _logger.debug("performing pfnGetArgumentProperties3");
+ for (uint32_t index = 0; index < props.numGraphArgs; ++index) {
+ ze_graph_argument_properties_3_t arg3{};
+ arg3.stype = ZE_STRUCTURE_TYPE_GRAPH_ARGUMENT_PROPERTIES;
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetArgumentProperties3(_handle, index, &arg3);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetArgumentProperties3", result, _zeroInitStruct->getGraphDdiTable());
+
+ if (arg3.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT) {
+ _input_descriptors.push_back(ArgumentDescriptor{arg3, index});
+ } else {
+ _output_descriptors.push_back(ArgumentDescriptor{arg3, index});
+ }
+ }
+
+ _input_descriptors.shrink_to_fit();
+ _output_descriptors.shrink_to_fit();
+
+ ze_device_properties_t deviceProperties = {};
+ deviceProperties.stype = ZE_STRUCTURE_TYPE_DEVICE_PROPERTIES;
+ THROW_ON_FAIL_FOR_LEVELZERO("zeDeviceGetProperties",
+ zeDeviceGetProperties(_zeroInitStruct->getDevice(), &deviceProperties));
+ auto groupOrdinal = zeroUtils::findGroupOrdinal(_zeroInitStruct->getDevice(), deviceProperties);
+
+ bool turbo = false;
+ if (config.has<TURBO>()) {
+ turbo = config.get<TURBO>();
+ }
+
+ _command_queue = std::make_shared<CommandQueue>(_zeroInitStruct->getDevice(),
+ _zeroInitStruct->getContext(),
+ zeroUtils::toZeQueuePriority(config.get<MODEL_PRIORITY>()),
+ _zeroInitStruct->getCommandQueueDdiTable(),
+ turbo,
+ groupOrdinal);
+
+ if (config.has<WORKLOAD_TYPE>()) {
+ set_workload_type(config.get<WORKLOAD_TYPE>());
+ }
+
+ _zeGraphExt->initializeGraph(_handle, config);
+
+ _logger.debug("Graph initialize finish");
+
+ // We are allowed to release the original blob because weights were loaded in NPU memory during
+ // _zeGraphExt->initializeGraph(). The driver will not access the original blob from this moment on, so we are
+ // releasing it here to avoid unnecessary memory usage.
+ _blobIsReleased = release_blob(config);
+}
+
+bool DriverGraph::release_blob(const Config& config) {
+ if (_blob.empty() || _zeroInitStruct->getGraphDdiTable().version() < ZE_GRAPH_EXT_VERSION_1_8 ||
+ config.get<PERF_COUNT>()) {
+ return false;
+ }
+
+ ze_graph_properties_2_t properties = {};
+ properties.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;
+ _zeroInitStruct->getGraphDdiTable().pfnGetProperties2(_handle, &properties);
+
+ if (~properties.initStageRequired & ZE_GRAPH_STAGE_INITIALIZE) {
+ return false;
+ }
+
+ _blob.clear();
+ _blob.shrink_to_fit();
+
+ _logger.debug("Blob is released");
+
+ return true;
+};
+
+DriverGraph::~DriverGraph() {
+ if (_handle != nullptr) {
+ auto result = _zeGraphExt->destroyGraph(_handle);
+
+ if (ZE_RESULT_SUCCESS == result) {
+ _handle = nullptr;
+ }
+ }
+}
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler/src/graph_transformations.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/ir_serializer.cpp
similarity index 94%
rename from src/plugins/intel_npu/src/compiler/src/graph_transformations.cpp
rename to src/plugins/intel_npu/src/compiler_adapter/src/ir_serializer.cpp
index 72596731914..ab28a1aa281 100644
--- a/src/plugins/intel_npu/src/compiler/src/graph_transformations.cpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/src/ir_serializer.cpp
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
//
-#include "graph_transformations.hpp"
+#include "ir_serializer.hpp"
#include <cstdint>
#include <istream>
@@ -12,10 +12,10 @@
#include "openvino/pass/serialize.hpp"
#include "transformations/op_conversions/convert_interpolate11_downgrade.hpp"
-namespace intel_npu::driverCompilerAdapter {
+namespace intel_npu::driver_compiler_utils {
IRSerializer::IRSerializer(const std::shared_ptr<const ov::Model>& origModel, const uint32_t supportedOpset)
- : _logger("DriverCompilerAdapter::IRSerializer", Logger::global().level()),
+ : _logger("IRSerializer", Logger::global().level()),
_supportedOpset(supportedOpset) {
// There is no const variant of run_passes so use const_cast here
// as model serialization does not mutate the model
@@ -101,4 +101,4 @@ void IRSerializer::serializeModelToBuffer(uint8_t* xml, uint8_t* weights) {
_logger.debug("serializeModelToBuffer end");
}
-} // namespace intel_npu::driverCompilerAdapter
+} // namespace intel_npu::driver_compiler_utils
diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cpp
new file mode 100644
index 00000000000..73dd3817e24
--- /dev/null
+++ b/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cpp
@@ -0,0 +1,160 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "plugin_compiler_adapter.hpp"
+
+#include <ze_graph_ext.h>
+
+#include <memory>
+#include <string>
+
+#include "intel_npu/common/device_helpers.hpp"
+#include "intel_npu/common/itt.hpp"
+#include "intel_npu/config/compiler.hpp"
+#include "intel_npu/npu_private_properties.hpp"
+#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/zero/zero_api.hpp"
+#include "intel_npu/utils/zero/zero_result.hpp"
+#include "openvino/util/file_util.hpp"
+#include "openvino/util/shared_object.hpp"
+#include "plugin_graph.hpp"
+#include "ze_graph_ext_wrappers.hpp"
+
+namespace {
+std::shared_ptr<void> loadLibrary(const std::string& libpath) {
+#if defined(OPENVINO_ENABLE_UNICODE_PATH_SUPPORT) && defined(_WIN32)
+ return ov::util::load_shared_object(ov::util::string_to_wstring(libpath).c_str());
+#else
+ return ov::util::load_shared_object(libpath.c_str());
+#endif
+}
+
+std::shared_ptr<intel_npu::ICompiler> getCompiler(std::shared_ptr<void> so) {
+ static constexpr auto CreateFuncName = "CreateNPUCompiler";
+ auto symbol = ov::util::get_symbol(so, CreateFuncName);
+
+ using CreateFuncT = void (*)(std::shared_ptr<intel_npu::ICompiler>&);
+ const auto createFunc = reinterpret_cast<CreateFuncT>(symbol);
+
+ std::shared_ptr<intel_npu::ICompiler> compilerPtr;
+ createFunc(compilerPtr);
+ return compilerPtr;
+}
+
+ov::SoPtr<intel_npu::ICompiler> loadCompiler(const std::string& libpath) {
+ auto compilerSO = loadLibrary(libpath);
+ auto compiler = getCompiler(compilerSO);
+
+ return ov::SoPtr<intel_npu::ICompiler>(compiler, compilerSO);
+}
+} // namespace
+
+namespace intel_npu {
+
+PluginCompilerAdapter::PluginCompilerAdapter(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct)
+ : _zeroInitStruct(zeroInitStruct),
+ _logger("PluginCompilerAdapter", Logger::global().level()) {
+ _logger.debug("initialize PluginCompilerAdapter start");
+
+ _logger.info("MLIR compiler will be used.");
+ std::string baseName = "npu_mlir_compiler";
+ auto libPath = ov::util::make_plugin_library_name(ov::util::get_ov_lib_path(), baseName + OV_BUILD_POSTFIX);
+ _compiler = loadCompiler(libPath);
+
+ if (_zeroInitStruct == nullptr) {
+ return;
+ }
+
+ uint32_t graphExtVersion = _zeroInitStruct->getGraphDdiTable().version();
+
+ _logger.info("PluginCompilerAdapter creating adapter using graphExtVersion");
+
+ switch (graphExtVersion) {
+ case ZE_GRAPH_EXT_VERSION_1_3:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_3>>(_zeroInitStruct);
+ break;
+ case ZE_GRAPH_EXT_VERSION_1_4:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_4>>(_zeroInitStruct);
+ break;
+ case ZE_GRAPH_EXT_VERSION_1_5:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_5>>(_zeroInitStruct);
+ break;
+ case ZE_GRAPH_EXT_VERSION_1_6:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_6>>(_zeroInitStruct);
+ break;
+ case ZE_GRAPH_EXT_VERSION_1_7:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_7>>(_zeroInitStruct);
+ break;
+ case ZE_GRAPH_EXT_VERSION_1_8:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_8>>(_zeroInitStruct);
+ break;
+ default:
+ _zeGraphExt = std::make_shared<ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_2>>(_zeroInitStruct);
+ break;
+ }
+
+ _logger.info("initialize PluginCompilerAdapter complete, using graphExtVersion: %d.%d",
+ ZE_MAJOR_VERSION(graphExtVersion),
+ ZE_MINOR_VERSION(graphExtVersion));
+}
+
+std::shared_ptr<IGraph> PluginCompilerAdapter::compile(const std::shared_ptr<const ov::Model>& model,
+ const Config& config) const {
+ OV_ITT_TASK_CHAIN(COMPILE_BLOB, itt::domains::NPUPlugin, "PluginCompilerAdapter", "compile");
+
+ _logger.debug("compile start");
+ auto networkDesc = _compiler->compile(model, config);
+ _logger.debug("compile end");
+
+ ze_graph_handle_t graphHandle = nullptr;
+
+ if (_zeGraphExt) {
+ // Depending on the config, we may get an error when trying to get the graph handle from the compiled network
+ try {
+ graphHandle = _zeGraphExt->getGraphHandle(networkDesc.compiledNetwork);
+ } catch (...) {
+ _logger.info("Failed to obtain the level zero graph handle. Inference requests for this model are not "
+ "allowed. Only exports are available");
+ }
+ }
+
+ return std::make_shared<PluginGraph>(_zeGraphExt,
+ _compiler,
+ _zeroInitStruct,
+ graphHandle,
+ std::move(networkDesc.metadata),
+ std::move(networkDesc.compiledNetwork),
+ config);
+}
+
+std::shared_ptr<IGraph> PluginCompilerAdapter::parse(std::vector<uint8_t> network, const Config& config) const {
+ OV_ITT_TASK_CHAIN(PARSE_BLOB, itt::domains::NPUPlugin, "PluginCompilerAdapter", "parse");
+
+ _logger.debug("parse start");
+ auto networkMeta = _compiler->parse(network, config);
+ _logger.debug("parse end");
+
+ ze_graph_handle_t graphHandle = nullptr;
+
+ if (_zeGraphExt) {
+ graphHandle = _zeGraphExt->getGraphHandle(network);
+ }
+
+ return std::make_shared<PluginGraph>(_zeGraphExt,
+ _compiler,
+ _zeroInitStruct,
+ graphHandle,
+ std::move(networkMeta),
+ std::move(network),
+ config);
+}
+
+ov::SupportedOpsMap PluginCompilerAdapter::query(const std::shared_ptr<const ov::Model>& model,
+ const Config& config) const {
+ OV_ITT_TASK_CHAIN(QUERY_BLOB, itt::domains::NPUPlugin, "PluginCompilerAdapter", "query");
+
+ return _compiler->query(model, config);
+}
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/plugin_graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/plugin_graph.cpp
new file mode 100644
index 00000000000..aaeb51108e5
--- /dev/null
+++ b/src/plugins/intel_npu/src/compiler_adapter/src/plugin_graph.cpp
@@ -0,0 +1,132 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "plugin_graph.hpp"
+
+#include "intel_npu/config/common.hpp"
+#include "intel_npu/config/runtime.hpp"
+
+namespace intel_npu {
+
+PluginGraph::PluginGraph(const std::shared_ptr<ZeGraphExtWrappersInterface>& zeGraphExt,
+ const ov::SoPtr<ICompiler>& compiler,
+ const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,
+ ze_graph_handle_t graphHandle,
+ NetworkMetadata metadata,
+ std::vector<uint8_t> blob,
+ const Config& config)
+ : IGraph(graphHandle, std::move(metadata), std::optional<std::vector<uint8_t>>(std::move(blob))),
+ _zeGraphExt(zeGraphExt),
+ _zeroInitStruct(zeroInitStruct),
+ _compiler(compiler),
+ _logger("PluginGraph", config.get<LOG_LEVEL>()) {
+ if (!config.get<CREATE_EXECUTOR>() || config.get<DEFER_WEIGHTS_LOAD>()) {
+ _logger.info("Graph initialize is deferred from the \"Graph\" constructor");
+ return;
+ }
+
+ initialize(config);
+}
+
+void PluginGraph::export_blob(std::ostream& stream) const {
+ stream.write(reinterpret_cast<const char*>(_blob.data()), _blob.size());
+
+ if (!stream) {
+ _logger.error("Write blob to stream failed. Blob is broken!");
+ return;
+ }
+
+ if (_logger.level() >= ov::log::Level::INFO) {
+ std::uint32_t result = 1171117u;
+ for (const uint8_t* it = _blob.data(); it != _blob.data() + _blob.size(); ++it) {
+ result = ((result << 7) + result) + static_cast<uint32_t>(*it);
+ }
+
+ std::stringstream str;
+ str << "Blob size: " << _blob.size() << ", hash: " << std::hex << result;
+ _logger.info(str.str().c_str());
+ }
+ _logger.info("Write blob to stream successfully.");
+}
+
+std::vector<ov::ProfilingInfo> PluginGraph::process_profiling_output(const std::vector<uint8_t>& profData,
+ const Config& config) const {
+ return _compiler->process_profiling_output(profData, _blob, config);
+}
+
+void PluginGraph::set_argument_value(uint32_t argi, const void* argv) const {
+ if (_zeGraphExt == nullptr) {
+ OPENVINO_THROW("Zero compiler adapter wasn't initialized");
+ }
+ _zeGraphExt->setGraphArgumentValue(_handle, argi, argv);
+}
+
+void PluginGraph::initialize(const Config& config) {
+ if (_zeGraphExt == nullptr || _handle == nullptr) {
+ return;
+ }
+
+ _logger.debug("Graph initialize start");
+
+ _logger.debug("performing pfnGetProperties");
+ ze_graph_properties_t props{};
+ props.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetProperties(_handle, &props);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetProperties", result, _zeroInitStruct->getGraphDdiTable());
+
+ _logger.debug("performing pfnGetArgumentProperties3");
+ for (uint32_t index = 0; index < props.numGraphArgs; ++index) {
+ ze_graph_argument_properties_3_t arg3{};
+ arg3.stype = ZE_STRUCTURE_TYPE_GRAPH_ARGUMENT_PROPERTIES;
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetArgumentProperties3(_handle, index, &arg3);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetArgumentProperties3", result, _zeroInitStruct->getGraphDdiTable());
+
+ if (arg3.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT) {
+ _input_descriptors.push_back(ArgumentDescriptor{arg3, index});
+ } else {
+ _output_descriptors.push_back(ArgumentDescriptor{arg3, index});
+ }
+ }
+
+ _input_descriptors.shrink_to_fit();
+ _output_descriptors.shrink_to_fit();
+
+ ze_device_properties_t deviceProperties = {};
+ deviceProperties.stype = ZE_STRUCTURE_TYPE_DEVICE_PROPERTIES;
+ THROW_ON_FAIL_FOR_LEVELZERO("zeDeviceGetProperties",
+ zeDeviceGetProperties(_zeroInitStruct->getDevice(), &deviceProperties));
+ auto groupOrdinal = zeroUtils::findGroupOrdinal(_zeroInitStruct->getDevice(), deviceProperties);
+
+ bool turbo = false;
+ if (config.has<TURBO>()) {
+ turbo = config.get<TURBO>();
+ }
+
+ _command_queue = std::make_shared<CommandQueue>(_zeroInitStruct->getDevice(),
+ _zeroInitStruct->getContext(),
+ zeroUtils::toZeQueuePriority(config.get<MODEL_PRIORITY>()),
+ _zeroInitStruct->getCommandQueueDdiTable(),
+ turbo,
+ groupOrdinal);
+
+ if (config.has<WORKLOAD_TYPE>()) {
+ set_workload_type(config.get<WORKLOAD_TYPE>());
+ }
+
+ _zeGraphExt->initializeGraph(_handle, config);
+
+ _logger.debug("Graph initialize finish");
+}
+
+PluginGraph::~PluginGraph() {
+ if (_handle != nullptr) {
+ auto result = _zeGraphExt->destroyGraph(_handle);
+
+ if (ZE_RESULT_SUCCESS == result) {
+ _handle = nullptr;
+ }
+ }
+}
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/compiler/src/precomp.hpp b/src/plugins/intel_npu/src/compiler_adapter/src/precomp.hpp
similarity index 100%
rename from src/plugins/intel_npu/src/compiler/src/precomp.hpp
rename to src/plugins/intel_npu/src/compiler_adapter/src/precomp.hpp
diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/ze_graph_ext_wrappers.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/ze_graph_ext_wrappers.cpp
new file mode 100644
index 00000000000..c094838cc22
--- /dev/null
+++ b/src/plugins/intel_npu/src/compiler_adapter/src/ze_graph_ext_wrappers.cpp
@@ -0,0 +1,568 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "ze_graph_ext_wrappers.hpp"
+
+#include <regex>
+#include <string_view>
+
+#include "intel_npu/config/runtime.hpp"
+#include "intel_npu/prefix.hpp"
+#include "intel_npu/utils/zero/zero_api.hpp"
+#include "intel_npu/utils/zero/zero_result.hpp"
+#include "intel_npu/utils/zero/zero_wrappers.hpp"
+#include "openvino/core/model.hpp"
+
+namespace {
+
+ov::element::Type_t toOVElementType(const ze_graph_argument_precision_t zeElementType) {
+ switch (zeElementType) {
+ case ZE_GRAPH_ARGUMENT_PRECISION_UNKNOWN:
+ return ov::element::Type_t::undefined;
+ case ZE_GRAPH_ARGUMENT_PRECISION_DYNAMIC:
+ return ov::element::Type_t::dynamic;
+ case ZE_GRAPH_ARGUMENT_PRECISION_BOOLEAN:
+ return ov::element::Type_t::boolean;
+ case ZE_GRAPH_ARGUMENT_PRECISION_BF16:
+ return ov::element::Type_t::bf16;
+ case ZE_GRAPH_ARGUMENT_PRECISION_FP16:
+ return ov::element::Type_t::f16;
+ case ZE_GRAPH_ARGUMENT_PRECISION_FP32:
+ return ov::element::Type_t::f32;
+ case ZE_GRAPH_ARGUMENT_PRECISION_FP64:
+ return ov::element::Type_t::f64;
+ case ZE_GRAPH_ARGUMENT_PRECISION_INT4:
+ return ov::element::Type_t::i4;
+ case ZE_GRAPH_ARGUMENT_PRECISION_INT8:
+ return ov::element::Type_t::i8;
+ case ZE_GRAPH_ARGUMENT_PRECISION_INT16:
+ return ov::element::Type_t::i16;
+ case ZE_GRAPH_ARGUMENT_PRECISION_INT32:
+ return ov::element::Type_t::i32;
+ case ZE_GRAPH_ARGUMENT_PRECISION_INT64:
+ return ov::element::Type_t::i64;
+ case ZE_GRAPH_ARGUMENT_PRECISION_BIN:
+ return ov::element::Type_t::u1;
+ case ZE_GRAPH_ARGUMENT_PRECISION_UINT4:
+ return ov::element::Type_t::u4;
+ case ZE_GRAPH_ARGUMENT_PRECISION_UINT8:
+ return ov::element::Type_t::u8;
+ case ZE_GRAPH_ARGUMENT_PRECISION_UINT16:
+ return ov::element::Type_t::u16;
+ case ZE_GRAPH_ARGUMENT_PRECISION_UINT32:
+ return ov::element::Type_t::u32;
+ case ZE_GRAPH_ARGUMENT_PRECISION_UINT64:
+ return ov::element::Type_t::u64;
+ default:
+ return ov::element::Type_t::undefined;
+ }
+}
+
+} // namespace
+
+namespace intel_npu {
+
+template <ze_graph_ext_version_t TableExtension>
+ZeGraphExtWrappers<TableExtension>::ZeGraphExtWrappers(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct)
+ : _zeroInitStruct(zeroInitStruct),
+ _logger("ZeGraphExtWrappers", Logger::global().level()) {}
+
+template <ze_graph_ext_version_t TableExtension>
+ZeGraphExtWrappers<TableExtension>::~ZeGraphExtWrappers() {
+ _logger.debug("ZeGraphExtWrappers obj destroyed");
+}
+
+template <ze_graph_ext_version_t TableExtension>
+_ze_result_t ZeGraphExtWrappers<TableExtension>::destroyGraph(ze_graph_handle_t graphHandle) {
+ _logger.debug("destroyGraph - pfnDestroy graphHandle");
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnDestroy(graphHandle);
+
+ if (ZE_RESULT_SUCCESS != result) {
+ _logger.error("failed to destroy graph handle. L0 pfnDestroy result: %s, code %#X",
+ ze_result_to_string(result).c_str(),
+ uint64_t(result));
+ }
+
+ return result;
+}
+
+template <ze_graph_ext_version_t TableExtension>
+template <ze_graph_ext_version_t T, std::enable_if_t<UseCopyForNativeBinary(T), bool>>
+void ZeGraphExtWrappers<TableExtension>::getNativeBinary(ze_graph_handle_t graphHandle,
+ std::vector<uint8_t>& blob,
+ const uint8_t*& blobPtr,
+ size_t& blobSize) const {
+ // Get blob size first
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetNativeBinary(graphHandle, &blobSize, nullptr);
+ blob.resize(blobSize);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetNativeBinary get blob size, Failed to compile network.",
+ result,
+ _zeroInitStruct->getGraphDdiTable());
+
+ // Get blob data
+ result = _zeroInitStruct->getGraphDdiTable().pfnGetNativeBinary(graphHandle, &blobSize, blob.data());
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetNativeBinary get blob data, Failed to compile network.",
+ result,
+ _zeroInitStruct->getGraphDdiTable());
+
+ blobPtr = blob.data();
+}
+
+template <ze_graph_ext_version_t TableExtension>
+template <ze_graph_ext_version_t T, std::enable_if_t<!UseCopyForNativeBinary(T), bool>>
+void ZeGraphExtWrappers<TableExtension>::getNativeBinary(ze_graph_handle_t graphHandle,
+ std::vector<uint8_t>& /* unusedBlob */,
+ const uint8_t*& blobPtr,
+ size_t& blobSize) const {
+ // Get blob ptr and size
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetNativeBinary2(graphHandle, &blobSize, &blobPtr);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetNativeBinary get blob size, Failed to compile network.",
+ result,
+ _zeroInitStruct->getGraphDdiTable());
+}
+
+template <ze_graph_ext_version_t TableExtension>
+void ZeGraphExtWrappers<TableExtension>::getGraphBinary(ze_graph_handle_t graphHandle,
+ std::vector<uint8_t>& blob,
+ const uint8_t*& blobPtr,
+ size_t& blobSize) const {
+ if (graphHandle == nullptr) {
+ OPENVINO_THROW("Graph handle is null");
+ }
+
+ _logger.info("ZeGraphExtWrappers getGraphBinary get blob from graphHandle");
+
+ getNativeBinary(graphHandle, blob, blobPtr, blobSize);
+}
+
+template <ze_graph_ext_version_t TableExtension>
+void ZeGraphExtWrappers<TableExtension>::setGraphArgumentValue(ze_graph_handle_t graphHandle,
+ uint32_t argi,
+ const void* argv) const {
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnSetArgumentValue(graphHandle, argi, argv);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("zeGraphSetArgumentValue", result, _zeroInitStruct->getGraphDdiTable());
+}
+
+template <ze_graph_ext_version_t TableExtension>
+void ZeGraphExtWrappers<TableExtension>::initializeGraph(ze_graph_handle_t graphHandle, const Config& config) const {
+ if (_zeroInitStruct->getGraphDdiTable().version() < ZE_GRAPH_EXT_VERSION_1_8) {
+ initialize_graph_through_command_list(graphHandle, config);
+ } else {
+ ze_graph_properties_2_t properties = {};
+ properties.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;
+ _zeroInitStruct->getGraphDdiTable().pfnGetProperties2(graphHandle, &properties);
+
+ if (properties.initStageRequired & ZE_GRAPH_STAGE_INITIALIZE) {
+ _zeroInitStruct->getGraphDdiTable().pfnGraphInitialize(graphHandle);
+ }
+
+ if (properties.initStageRequired & ZE_GRAPH_STAGE_COMMAND_LIST_INITIALIZE) {
+ initialize_graph_through_command_list(graphHandle, config);
+ }
+ }
+}
+
+template <ze_graph_ext_version_t TableExtension>
+void ZeGraphExtWrappers<TableExtension>::initialize_graph_through_command_list(ze_graph_handle_t graphHandle,
+ const Config& config) const {
+ ze_device_properties_t deviceProperties = {};
+ deviceProperties.stype = ZE_STRUCTURE_TYPE_DEVICE_PROPERTIES;
+ THROW_ON_FAIL_FOR_LEVELZERO("zeDeviceGetProperties",
+ zeDeviceGetProperties(_zeroInitStruct->getDevice(), &deviceProperties));
+ auto groupOrdinal = zeroUtils::findGroupOrdinal(_zeroInitStruct->getDevice(), deviceProperties);
+
+ _logger.debug("ZeGraphExtWrappers::initialize_graph_through_command_list init start - create graph_command_list");
+ CommandList graph_command_list(_zeroInitStruct->getDevice(),
+ _zeroInitStruct->getContext(),
+ _zeroInitStruct->getGraphDdiTable(),
+ groupOrdinal);
+ _logger.debug("ZeGraphExtWrappers::initialize_graph_through_command_list - create graph_command_queue");
+ CommandQueue graph_command_queue(_zeroInitStruct->getDevice(),
+ _zeroInitStruct->getContext(),
+ ZE_COMMAND_QUEUE_PRIORITY_NORMAL,
+ _zeroInitStruct->getCommandQueueDdiTable(),
+ false,
+ groupOrdinal);
+ _logger.debug("ZeGraphExtWrappers::initialize_graph_through_command_list - create fence");
+ Fence fence(graph_command_queue);
+
+ _logger.debug("ZeGraphExtWrappers::initialize_graph_through_command_list - performing appendGraphInitialize");
+ graph_command_list.appendGraphInitialize(graphHandle);
+ _logger.debug("ZeGraphExtWrappers::initialize_graph_through_command_list - closing graph command list");
+ graph_command_list.close();
+
+ _logger.debug("ZeGraphExtWrappers::initialize_graph_through_command_list - performing executeCommandList");
+ graph_command_queue.executeCommandList(graph_command_list, fence);
+ _logger.debug("ZeGraphExtWrappers::initialize_graph_through_command_list - performing hostSynchronize");
+ fence.hostSynchronize();
+ _logger.debug("ZeGraphExtWrappers::initialize_graph_through_command_list - hostSynchronize completed");
+}
+
+// Parse the result string of query from foramt <name_0><name_1><name_2> to unordered_set of string
+static std::unordered_set<std::string> parseQueryResult(std::vector<char>& data) {
+ std::string dataString(data.begin(), data.end());
+ std::unordered_set<std::string> result;
+ size_t i = 0, start = 0;
+ while (i < dataString.length()) {
+ if (dataString[i] == '<') {
+ start = ++i;
+ } else if (dataString[i] == '>') {
+ std::string temp(dataString.begin() + start, dataString.begin() + i);
+ result.insert(temp);
+ i++;
+ } else {
+ i++;
+ }
+ }
+ return result;
+}
+
+// For ext version < 1.3, query is unsupported, return empty result and add debug log here
+template <ze_graph_ext_version_t TableExtension>
+template <ze_graph_ext_version_t T, std::enable_if_t<NotSupportQuery(T), bool>>
+std::unordered_set<std::string> ZeGraphExtWrappers<TableExtension>::queryImpl(
+ std::pair<size_t, std::shared_ptr<uint8_t>>,
+ const std::string&) const {
+ _logger.info("queryImpl - Driver version is less than 1.3, queryNetwork is unsupported.");
+ return std::unordered_set<std::string>();
+}
+
+// For ext version == 1.3 && == 1.4
+template <ze_graph_ext_version_t TableExtension>
+template <ze_graph_ext_version_t T, std::enable_if_t<SupportAPIGraphQueryNetworkV1(T), bool>>
+ze_result_t ZeGraphExtWrappers<TableExtension>::queryNetworkCreateV1(
+ std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags,
+ ze_graph_query_network_handle_t& hGraphQueryNetwork) const {
+ ze_graph_desc_t desc = {ZE_STRUCTURE_TYPE_GRAPH_DESC_PROPERTIES,
+ nullptr,
+ ZE_GRAPH_FORMAT_NGRAPH_LITE,
+ serializedIR.first,
+ serializedIR.second.get(),
+ buildFlags.c_str()};
+
+ // Create querynetwork handle
+ ze_result_t result = _zeroInitStruct->getGraphDdiTable().pfnQueryNetworkCreate(_zeroInitStruct->getContext(),
+ _zeroInitStruct->getDevice(),
+ &desc,
+ &hGraphQueryNetwork);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("queryNetworkCreateV1", result, _zeroInitStruct->getGraphDdiTable());
+
+ return result;
+}
+
+// For ext version == 1.3 && == 1.4, query is supported, calling querynetwork api in _zeroInitStruct->getGraphDdiTable()
+template <ze_graph_ext_version_t TableExtension>
+template <ze_graph_ext_version_t T, std::enable_if_t<SupportAPIGraphQueryNetworkV1(T), bool>>
+std::unordered_set<std::string> ZeGraphExtWrappers<TableExtension>::queryImpl(
+ std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags) const {
+ _logger.info("queryImpl - Calling queryNetwork of 1.3 version.");
+
+ ze_graph_query_network_handle_t hGraphQueryNetwork = nullptr;
+
+ auto result = queryNetworkCreateV1(std::move(serializedIR), buildFlags, hGraphQueryNetwork);
+
+ return getQueryResultFromSupportedLayers(result, hGraphQueryNetwork);
+}
+
+// For ext version >= 1.5
+template <ze_graph_ext_version_t TableExtension>
+template <ze_graph_ext_version_t T, std::enable_if_t<SupportAPIGraphQueryNetworkV2(T), bool>>
+ze_result_t ZeGraphExtWrappers<TableExtension>::queryNetworkCreateV2(
+ std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags,
+ ze_graph_query_network_handle_t& hGraphQueryNetwork) const {
+ ze_graph_desc_2_t desc = {ZE_STRUCTURE_TYPE_GRAPH_DESC_PROPERTIES,
+ nullptr,
+ ZE_GRAPH_FORMAT_NGRAPH_LITE,
+ serializedIR.first,
+ serializedIR.second.get(),
+ buildFlags.c_str(),
+ ZE_GRAPH_FLAG_NONE};
+
+ // Create querynetwork handle
+ _logger.debug("queryNetworkCreateV2 - performing pfnQueryNetworkCreate2");
+ ze_result_t result = _zeroInitStruct->getGraphDdiTable().pfnQueryNetworkCreate2(_zeroInitStruct->getContext(),
+ _zeroInitStruct->getDevice(),
+ &desc,
+ &hGraphQueryNetwork);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("queryNetworkCreateV2", result, _zeroInitStruct->getGraphDdiTable());
+
+ return result;
+}
+
+// For ext version >= 1.5
+template <ze_graph_ext_version_t TableExtension>
+template <ze_graph_ext_version_t T, std::enable_if_t<SupportAPIGraphQueryNetworkV2(T), bool>>
+std::unordered_set<std::string> ZeGraphExtWrappers<TableExtension>::queryImpl(
+ std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags) const {
+ _logger.debug("queryImpl - Calling queryNetwork of 1.5 version.");
+
+ ze_graph_query_network_handle_t hGraphQueryNetwork = nullptr;
+
+ auto result = queryNetworkCreateV2(std::move(serializedIR), buildFlags, hGraphQueryNetwork);
+
+ return getQueryResultFromSupportedLayers(result, hGraphQueryNetwork);
+}
+
+template <ze_graph_ext_version_t TableExtension>
+template <ze_graph_ext_version_t T, std::enable_if_t<!NotSupportQuery(T), bool>>
+std::unordered_set<std::string> ZeGraphExtWrappers<TableExtension>::getQueryResultFromSupportedLayers(
+ ze_result_t result,
+ ze_graph_query_network_handle_t& hGraphQueryNetwork) const {
+ // Get the size of query result
+ size_t size = 0;
+ result = _zeroInitStruct->getGraphDdiTable().pfnQueryNetworkGetSupportedLayers(hGraphQueryNetwork, &size, nullptr);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnQueryNetworkGetSupportedLayers get size of query result",
+ result,
+ _zeroInitStruct->getGraphDdiTable());
+
+ // Get the result data of query
+ std::vector<char> supportedLayers(size);
+ result = _zeroInitStruct->getGraphDdiTable().pfnQueryNetworkGetSupportedLayers(hGraphQueryNetwork,
+ &size,
+ supportedLayers.data());
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnQueryNetworkGetSupportedLayers get result data of query",
+ result,
+ _zeroInitStruct->getGraphDdiTable());
+
+ result = _zeroInitStruct->getGraphDdiTable().pfnQueryNetworkDestroy(hGraphQueryNetwork);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnQueryNetworkDestroy", result, _zeroInitStruct->getGraphDdiTable());
+
+ return parseQueryResult(supportedLayers);
+}
+
+template <ze_graph_ext_version_t TableExtension>
+std::unordered_set<std::string> ZeGraphExtWrappers<TableExtension>::queryGraph(
+ std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags) const {
+ return queryImpl(std::move(serializedIR), buildFlags);
+}
+
+// For ext version <1.5, calling pfnCreate api in _zeroInitStruct->getGraphDdiTable()
+template <ze_graph_ext_version_t TableExtension>
+template <ze_graph_ext_version_t T, std::enable_if_t<NotSupportGraph2(T), bool>>
+void ZeGraphExtWrappers<TableExtension>::createGraph(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags,
+ const uint32_t& /*flags*/,
+ ze_graph_handle_t* graph) const {
+ ze_graph_desc_t desc = {ZE_STRUCTURE_TYPE_GRAPH_DESC_PROPERTIES,
+ nullptr,
+ ZE_GRAPH_FORMAT_NGRAPH_LITE,
+ serializedIR.first,
+ serializedIR.second.get(),
+ buildFlags.c_str()};
+
+ _logger.debug("createGraph - performing pfnCreate");
+ // Create querynetwork handle
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnCreate(_zeroInitStruct->getContext(),
+ _zeroInitStruct->getDevice(),
+ &desc,
+ graph);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnCreate", result, _zeroInitStruct->getGraphDdiTable());
+}
+
+// For ext version >= 1.5, calling pfnCreate2 api in _zeroInitStruct->getGraphDdiTable()
+template <ze_graph_ext_version_t TableExtension>
+template <ze_graph_ext_version_t T, std::enable_if_t<!NotSupportGraph2(T), bool>>
+void ZeGraphExtWrappers<TableExtension>::createGraph(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags,
+ const uint32_t& flags,
+ ze_graph_handle_t* graph) const {
+ ze_graph_desc_2_t desc = {ZE_STRUCTURE_TYPE_GRAPH_DESC_PROPERTIES,
+ nullptr,
+ ZE_GRAPH_FORMAT_NGRAPH_LITE,
+ serializedIR.first,
+ serializedIR.second.get(),
+ buildFlags.c_str(),
+ flags};
+
+ _logger.debug("createGraph - performing pfnCreate2");
+ // Create querynetwork handle
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnCreate2(_zeroInitStruct->getContext(),
+ _zeroInitStruct->getDevice(),
+ &desc,
+ graph);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnCreate2", result, _zeroInitStruct->getGraphDdiTable());
+}
+
+template <ze_graph_ext_version_t TableExtension>
+ze_graph_handle_t ZeGraphExtWrappers<TableExtension>::getGraphHandle(
+ std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags,
+ const uint32_t& flags) const {
+ ze_graph_handle_t graphHandle;
+
+ _logger.info("compileIR Using extension version: %s", typeid(TableExtension).name());
+ createGraph(std::move(serializedIR), buildFlags, flags, &graphHandle);
+
+ return graphHandle;
+}
+
+template <ze_graph_ext_version_t TableExtension>
+ze_graph_handle_t ZeGraphExtWrappers<TableExtension>::getGraphHandle(const std::vector<uint8_t>& network) const {
+ ze_graph_handle_t graphHandle;
+
+ if (network.empty()) {
+ OPENVINO_THROW("Empty blob");
+ }
+
+ ze_graph_desc_t desc = {ZE_STRUCTURE_TYPE_GRAPH_DESC_PROPERTIES,
+ nullptr,
+ ZE_GRAPH_FORMAT_NATIVE,
+ network.size(),
+ network.data(),
+ nullptr};
+
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnCreate(_zeroInitStruct->getContext(),
+ _zeroInitStruct->getDevice(),
+ &desc,
+ &graphHandle);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnCreate", result, _zeroInitStruct->getGraphDdiTable());
+
+ return graphHandle;
+}
+
+/**
+ * @brief Extracts the I/O metadata from Level Zero specific structures and converts them into OpenVINO specific
+ * ones.
+ *
+ * @param arg The main Level Zero structure from which most metadata will be extracted.
+ * @param metadata The secondary Level Zero structure from which metadata will be extracted. More specifically, the
+ * argument is used for populating "shapeFromIRModel". Not providing this argument will lead to an empty value for
+ * the referenced attribute.
+ * @returns A descriptor object containing the metadata converted in OpenVINO specific structures.
+ */
+static IODescriptor getIODescriptor(const ze_graph_argument_properties_3_t& arg,
+ const std::optional<ze_graph_argument_metadata_t>& metadata) {
+ ov::element::Type_t precision = toOVElementType(arg.devicePrecision);
+ ov::Shape shapeFromCompiler, shapeFromIRModel;
+ std::unordered_set<std::string> outputTensorNames;
+
+ for (uint32_t id = 0; id < arg.associated_tensor_names_count; id++) {
+ outputTensorNames.insert(arg.associated_tensor_names[id]);
+ }
+ for (uint32_t id = 0; id < arg.dims_count; id++) {
+ shapeFromCompiler.push_back(arg.dims[id]);
+ }
+ if (metadata.has_value()) {
+ for (uint32_t id = 0; id < metadata->shape_size; id++) {
+ shapeFromIRModel.push_back(metadata->shape[id]);
+ }
+ }
+
+ // Flags will be used instead of indices for informing the type of the current entry
+ std::string nameFromCompiler = arg.name;
+ bool isStateInput = false;
+ bool isStateOutput = false;
+ bool isShapeTensor = false;
+ if (isStateInputName(nameFromCompiler)) {
+ nameFromCompiler = nameFromCompiler.substr(READVALUE_PREFIX.length());
+ isStateInput = true;
+ } else if (isStateOutputName(nameFromCompiler)) {
+ nameFromCompiler = nameFromCompiler.substr(ASSIGN_PREFIX.length());
+ isStateOutput = true;
+ } else if (isShapeTensorName(nameFromCompiler)) {
+ nameFromCompiler = nameFromCompiler.substr(SHAPE_TENSOR_PREFIX.length());
+ isShapeTensor = true;
+ }
+
+ return {std::move(nameFromCompiler),
+ precision,
+ std::move(shapeFromCompiler),
+ isStateInput,
+ isStateOutput,
+ isShapeTensor,
+ std::nullopt,
+ arg.debug_friendly_name,
+ std::move(outputTensorNames),
+ metadata.has_value() ? std::optional(shapeFromIRModel) : std::nullopt};
+}
+
+template <ze_graph_ext_version_t TableExtension>
+template <ze_graph_ext_version_t T, std::enable_if_t<NotSupportArgumentMetadata(T), bool>>
+void ZeGraphExtWrappers<TableExtension>::getMetadata(ze_graph_handle_t graphHandle,
+ uint32_t index,
+ std::vector<IODescriptor>& inputs,
+ std::vector<IODescriptor>& outputs) const {
+ ze_graph_argument_properties_3_t arg;
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetArgumentProperties3(graphHandle, index, &arg);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetArgumentProperties3", result, _zeroInitStruct->getGraphDdiTable());
+
+ switch (arg.type) {
+ case ZE_GRAPH_ARGUMENT_TYPE_INPUT: {
+ inputs.push_back(getIODescriptor(arg, std::nullopt));
+ } break;
+ case ZE_GRAPH_ARGUMENT_TYPE_OUTPUT: {
+ outputs.push_back(getIODescriptor(arg, std::nullopt));
+ } break;
+ default: {
+ OPENVINO_THROW("Invalid ze_graph_argument_type_t found in ze_graph_argument_properties_3_t object: ", arg.type);
+ }
+ }
+}
+
+template <ze_graph_ext_version_t TableExtension>
+template <ze_graph_ext_version_t T, std::enable_if_t<!NotSupportArgumentMetadata(T), bool>>
+void ZeGraphExtWrappers<TableExtension>::getMetadata(ze_graph_handle_t graphHandle,
+ uint32_t index,
+ std::vector<IODescriptor>& inputs,
+ std::vector<IODescriptor>& outputs) const {
+ ze_graph_argument_properties_3_t arg;
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetArgumentProperties3(graphHandle, index, &arg);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetArgumentProperties3", result, _zeroInitStruct->getGraphDdiTable());
+
+ std::optional<ze_graph_argument_metadata_t> optionalMetadata = std::nullopt;
+
+ if (!isStateInputName(arg.name) && !isStateOutputName(arg.name) && !isShapeTensorName(arg.name)) {
+ ze_graph_argument_metadata_t metadata;
+ result = _zeroInitStruct->getGraphDdiTable().pfnGraphGetArgumentMetadata(graphHandle, index, &metadata);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGraphGetArgumentMetadata", result, _zeroInitStruct->getGraphDdiTable());
+
+ optionalMetadata = std::optional(metadata);
+ }
+
+ switch (arg.type) {
+ case ZE_GRAPH_ARGUMENT_TYPE_INPUT: {
+ inputs.push_back(getIODescriptor(arg, optionalMetadata));
+ } break;
+ case ZE_GRAPH_ARGUMENT_TYPE_OUTPUT: {
+ outputs.push_back(getIODescriptor(arg, optionalMetadata));
+ } break;
+ default: {
+ OPENVINO_THROW("Invalid ze_graph_argument_type_t found in ze_graph_argument_properties_3_t object: ", arg.type);
+ }
+ }
+}
+
+template <ze_graph_ext_version_t TableExtension>
+NetworkMetadata ZeGraphExtWrappers<TableExtension>::getNetworkMeta(ze_graph_handle_t graphHandle) const {
+ ze_graph_properties_t graphProperties{};
+
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetProperties(graphHandle, &graphProperties);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetProperties", result, _zeroInitStruct->getGraphDdiTable());
+
+ NetworkMetadata meta;
+
+ for (uint32_t index = 0; index < graphProperties.numGraphArgs; ++index) {
+ getMetadata(graphHandle, index, meta.inputs, meta.outputs);
+ }
+ // TODO: support this information in CiD [track: E#33479]
+ meta.numStreams = 1;
+ meta.bindRelatedDescriptors();
+
+ return meta;
+}
+
+template class ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_2>;
+template class ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_3>;
+template class ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_4>;
+template class ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_5>;
+template class ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_6>;
+template class ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_7>;
+template class ZeGraphExtWrappers<ZE_GRAPH_EXT_VERSION_1_8>;
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/plugin/CMakeLists.txt b/src/plugins/intel_npu/src/plugin/CMakeLists.txt
index 2e80ed41f82..553311c1aa8 100644
--- a/src/plugins/intel_npu/src/plugin/CMakeLists.txt
+++ b/src/plugins/intel_npu/src/plugin/CMakeLists.txt
@@ -22,21 +22,11 @@ ov_add_plugin(NAME ${NPU_PLUGIN_TARGET}
set_target_properties(${TARGET_NAME} PROPERTIES INTERPROCEDURAL_OPTIMIZATION_RELEASE ${ENABLE_LTO})
ov_add_clang_format_target(${TARGET_NAME}_clang FOR_TARGETS ${TARGET_NAME})
-if(ENABLE_DRIVER_COMPILER_ADAPTER)
- target_compile_definitions(${TARGET_NAME} PRIVATE ENABLE_DRIVER_COMPILER_ADAPTER)
- target_link_libraries(${TARGET_NAME}
- PRIVATE
- openvino_npu_driver_compiler_adapter
- )
-endif()
-
-if(ENABLE_ZEROAPI_BACKEND)
- target_compile_definitions(${TARGET_NAME} PRIVATE ENABLE_ZEROAPI_BACKEND)
- target_link_libraries(${TARGET_NAME}
- PRIVATE
- openvino_npu_level_zero_backend
- )
-endif()
+target_link_libraries(${TARGET_NAME}
+ PRIVATE
+ openvino_npu_driver_compiler_adapter
+ openvino_npu_level_zero_backend
+)
if(ENABLE_IMD_BACKEND)
target_compile_definitions(${TARGET_NAME} PRIVATE ENABLE_IMD_BACKEND)
@@ -50,9 +40,6 @@ target_link_libraries(${TARGET_NAME}
PRIVATE
openvino::npu_al
openvino::npu_common
- openvino::npu_logger_utils
- openvino::runtime
- openvino::runtime::dev
)
target_include_directories(${TARGET_NAME}
@@ -61,13 +48,6 @@ target_include_directories(${TARGET_NAME}
PRIVATE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/>
)
-if(ENABLE_ZEROAPI_BACKEND)
- target_include_directories(${TARGET_NAME}
- SYSTEM PRIVATE
- $<TARGET_PROPERTY:LevelZero::LevelZero,INTERFACE_INCLUDE_DIRECTORIES>
- $<TARGET_PROPERTY:LevelZero::NPUExt,INTERFACE_INCLUDE_DIRECTORIES>
- )
-endif()
cross_compiled_file(${TARGET_NAME}
ARCH AVX2 ANY
diff --git a/src/plugins/intel_npu/src/plugin/include/compiled_model.hpp b/src/plugins/intel_npu/src/plugin/include/compiled_model.hpp
index 8b01b2246f1..caaec951a22 100644
--- a/src/plugins/intel_npu/src/plugin/include/compiled_model.hpp
+++ b/src/plugins/intel_npu/src/plugin/include/compiled_model.hpp
@@ -23,7 +23,7 @@ public:
* @param model The IR of the model to be compiled
* @param plugin Pointer towards the NPU plugin instance
* @param device Backend specific object through which inference requests can be created
- * @param compiler Module used for compiling the IR model.
+ * @param graph Object holding the graph handle along with distinct fields for metadata
* @param profiling Flag indicating if profiling was requested. Setting this to "true" will lead to storing the
* "compiler" parameter inside the newly created "CompiledModel".
* @param config Custom configuration object
@@ -31,25 +31,7 @@ public:
CompiledModel(const std::shared_ptr<const ov::Model>& model,
const std::shared_ptr<const ov::IPlugin>& plugin,
const std::shared_ptr<IDevice>& device,
- const ov::SoPtr<ICompiler>& compiler,
- const bool profiling,
- const Config& config);
-
- /**
- * @brief The constructor used by the "Plugin::import_model" method.
- * @param model The IR of the already compiled model
- * @param plugin Pointer towards the NPU plugin instance
- * @param networkDescription Object holding the compiled model within a buffer along with distinct fields for its
- * metadata
- * @param device Backend specific object through which inference requests can be created
- * @param compiler If set, the module will be stored inside the newly created "CompiledModel"
- * @param config Custom configuration object
- */
- CompiledModel(const std::shared_ptr<const ov::Model>& model,
- const std::shared_ptr<const ov::IPlugin>& plugin,
- const std::shared_ptr<const NetworkDescription>& networkDescription,
- const std::shared_ptr<IDevice>& device,
- const ov::SoPtr<ICompiler>& compiler,
+ const std::shared_ptr<IGraph>& graph,
const Config& config);
CompiledModel(const CompiledModel&) = delete;
@@ -62,11 +44,6 @@ public:
std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override;
- // For CID path mean it get the blob from compiler through pfnGetNativeBinary using
- // networkDescription->metadata.graphHandle.
-
- // For CIP path mean it get the blob from
- // networkDescription->compiledNetwork.
void export_model(std::ostream& stream) const override;
std::shared_ptr<const ov::Model> get_runtime_model() const override;
@@ -75,32 +52,26 @@ public:
ov::Any get_property(const std::string& name) const override;
- const std::shared_ptr<const NetworkDescription>& get_network_description() const override;
+ const std::shared_ptr<IGraph>& get_graph() const override;
const Config& get_config() const override;
- const ov::SoPtr<ICompiler>& get_compiler() const override;
-
private:
void initialize_properties();
void configure_stream_executors();
- void create_executor();
-
- std::shared_ptr<const NetworkDescription> _networkPtr;
const std::shared_ptr<const ov::Model> _model;
Config _config;
Logger _logger;
const std::shared_ptr<IDevice> _device;
- mutable std::shared_ptr<IExecutor> _executorPtr;
std::shared_ptr<ov::threading::ITaskExecutor> _resultExecutor;
// properties map: {name -> [supported, mutable, eval function]}
std::map<std::string, std::tuple<bool, ov::PropertyMutability, std::function<ov::Any(const Config&)>>> _properties;
std::vector<ov::PropertyName> _supportedProperties;
- const ov::SoPtr<ICompiler> _compiler;
+ std::shared_ptr<IGraph> _graph;
};
} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/plugin/include/compiler.hpp b/src/plugins/intel_npu/src/plugin/include/compiler.hpp
deleted file mode 100644
index 22f21ae2570..00000000000
--- a/src/plugins/intel_npu/src/plugin/include/compiler.hpp
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright (C) 2018-2024 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-// Compiler Factory
-
-#pragma once
-
-#include "backends.hpp"
-#include "intel_npu/icompiler.hpp"
-#include "intel_npu/npu_private_properties.hpp" // AL
-#include "intel_npu/utils/logger/logger.hpp"
-#include "openvino/runtime/so_ptr.hpp"
-
-namespace intel_npu {
-
-ov::SoPtr<ICompiler> createCompiler(std::shared_ptr<intel_npu::NPUBackends> npuBackends,
- ov::intel_npu::CompilerType compilerType);
-
-} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/plugin/include/plugin.hpp b/src/plugins/intel_npu/src/plugin/include/plugin.hpp
index b3ad816ff2f..c3c2daa525a 100644
--- a/src/plugins/intel_npu/src/plugin/include/plugin.hpp
+++ b/src/plugins/intel_npu/src/plugin/include/plugin.hpp
@@ -9,9 +9,7 @@
#include <string>
#include "backends.hpp"
-#include "intel_npu/common/npu.hpp"
#include "intel_npu/config/config.hpp"
-#include "intel_npu/icompiler.hpp"
#include "intel_npu/utils/logger/logger.hpp"
#include "metrics.hpp"
#include "openvino/runtime/iplugin.hpp"
@@ -54,7 +52,7 @@ public:
const ov::AnyMap& properties) const override;
private:
- ov::SoPtr<ICompiler> getCompiler(const Config& config) const;
+ std::unique_ptr<ICompilerAdapter> getCompiler(const Config& config) const;
std::shared_ptr<NPUBackends> _backends;
diff --git a/src/plugins/intel_npu/src/plugin/src/backends.cpp b/src/plugins/intel_npu/src/plugin/src/backends.cpp
index b528102a2b6..8507098bc85 100644
--- a/src/plugins/intel_npu/src/plugin/src/backends.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/backends.cpp
@@ -9,10 +9,7 @@
#include "intel_npu/common/device_helpers.hpp"
#include "intel_npu/config/common.hpp"
-
-#if defined(ENABLE_ZEROAPI_BACKEND)
-# include "zero_backend.hpp"
-#endif
+#include "zero_backend.hpp"
#if !defined(OPENVINO_STATIC_LIBRARY) && defined(ENABLE_IMD_BACKEND)
# include "openvino/util/file_util.hpp"
@@ -102,12 +99,10 @@ NPUBackends::NPUBackends(const std::vector<AvailableBackends>& backendRegistry,
}
#endif
-#if defined(ENABLE_ZEROAPI_BACKEND)
if (name == AvailableBackends::LEVEL_ZERO) {
const auto backend = ov::SoPtr<IEngineBackend>(std::make_shared<ZeroEngineBackend>(config));
registerBackend(backend, backendName);
}
-#endif
} catch (const std::exception& ex) {
_logger.warning("Got an error during backend '%s' loading : %s", backendName.c_str(), ex.what());
} catch (...) {
diff --git a/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp
index bae0cb545b3..77b0592e361 100644
--- a/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp
@@ -13,7 +13,6 @@
#include "intel_npu/config/compiler.hpp"
#include "intel_npu/config/config.hpp"
#include "intel_npu/config/runtime.hpp"
-#include "intel_npu/icompiler.hpp"
#include "openvino/pass/constant_folding.hpp"
#include "openvino/pass/manager.hpp"
#include "openvino/runtime/properties.hpp"
@@ -21,25 +20,6 @@
#include "openvino/runtime/threading/executor_manager.hpp"
#include "transformations/utils/utils.hpp"
-namespace {
-
-constexpr std::string_view NO_EXECUTOR_FOR_INFERENCE =
- "Can't create infer request due to create executor failed! Only exports can be made.";
-
-constexpr std::string_view NO_EXECUTOR_FOR_INFERENCE_NODEVICE =
- "Can't create infer request!\n"
- "Please make sure that the device is available. Only exports can be made.";
-
-std::uint32_t hash(const intel_npu::CompiledNetwork& blob) {
- std::uint32_t result = 1171117u;
- for (const uint8_t* it = blob.data; it != blob.data + blob.size; ++it) {
- result = ((result << 7) + result) + static_cast<uint32_t>(*it);
- }
- return result;
-}
-
-} // namespace
-
namespace intel_npu {
using intel_npu::envVarStrToBool;
@@ -47,92 +27,36 @@ using intel_npu::envVarStrToBool;
CompiledModel::CompiledModel(const std::shared_ptr<const ov::Model>& model,
const std::shared_ptr<const ov::IPlugin>& plugin,
const std::shared_ptr<IDevice>& device,
- const ov::SoPtr<ICompiler>& compiler,
- const bool profiling,
- const Config& config)
- : ICompiledModel(model, plugin),
- _model(model),
- _config(config),
- _logger("CompiledModel", config.get<LOG_LEVEL>()),
- _device(device),
- _compiler(compiler) {
- OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "CompiledModel::CompiledModel");
- OPENVINO_ASSERT(compiler != nullptr, "NPU CompiledModel: the pointer towards the compiler object is null");
-
- try {
- _logger.debug("performing compile and expecting a network description");
- _networkPtr = std::make_shared<const NetworkDescription>(_compiler->compile(model, config));
- } catch (const std::exception& ex) {
- OPENVINO_THROW(ex.what());
- } catch (...) {
- _logger.error("Unexpected exception");
- OPENVINO_THROW("NPU CompiledModel: got an unexpected exception from compiler");
- }
-
- OV_ITT_TASK_CHAIN(COMPILED_MODEL, itt::domains::NPUPlugin, "CompiledModel::CompiledModel", "initialize_properties");
- initialize_properties();
- configure_stream_executors();
-
- OV_ITT_TASK_NEXT(COMPILED_MODEL, "create_executor");
- create_executor();
-
- OV_ITT_TASK_SKIP(COMPILED_MODEL);
-}
-
-CompiledModel::CompiledModel(const std::shared_ptr<const ov::Model>& model,
- const std::shared_ptr<const ov::IPlugin>& plugin,
- const std::shared_ptr<const NetworkDescription>& networkDescription,
- const std::shared_ptr<IDevice>& device,
- const ov::SoPtr<ICompiler>& compiler,
+ const std::shared_ptr<IGraph>& graph,
const Config& config)
: ICompiledModel(model, plugin),
- _networkPtr(networkDescription),
_model(model),
_config(config),
_logger("CompiledModel", config.get<LOG_LEVEL>()),
_device(device),
- _compiler(compiler) {
+ _graph(graph) {
OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "CompiledModel::CompiledModel");
- OPENVINO_ASSERT(_networkPtr != nullptr,
- "NPU CompiledModel: the pointer towards the NetworkDescription object is null");
OV_ITT_TASK_CHAIN(COMPILED_MODEL, itt::domains::NPUPlugin, "CompiledModel::CompiledModel", "initialize_properties");
initialize_properties();
configure_stream_executors();
- OV_ITT_TASK_NEXT(COMPILED_MODEL, "create_executor");
- create_executor();
-
OV_ITT_TASK_SKIP(COMPILED_MODEL);
}
CompiledModel::~CompiledModel() {
_logger.debug("~CompiledModel()");
- // Call compiler to destroy graphHandle only if no executor created
- if (_executorPtr == nullptr) {
- _logger.debug("~CompiledModel() - _executorPtr is a nullptr, compiler release _executorPtr");
- _compiler->release(_networkPtr);
- }
}
std::shared_ptr<ov::IAsyncInferRequest> CompiledModel::create_infer_request() const {
OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "CompiledModel::create_infer_request");
- if (_executorPtr == nullptr && _device != nullptr) {
- _executorPtr = _device->createExecutor(_networkPtr, _config);
- }
-
- if (_executorPtr == nullptr) {
- if (_device != nullptr) {
- OPENVINO_THROW(NO_EXECUTOR_FOR_INFERENCE);
- } else {
- _logger.error("Can not find device!");
- OPENVINO_THROW(NO_EXECUTOR_FOR_INFERENCE_NODEVICE);
- }
+ if (!_config.get<CREATE_EXECUTOR>() || _config.get<DEFER_WEIGHTS_LOAD>()) {
+ _graph->initialize(_config);
}
const std::shared_ptr<SyncInferRequest>& syncInferRequest =
- _device->createInferRequest(shared_from_this(), _executorPtr, _config);
+ _device->createInferRequest(shared_from_this(), _config);
syncInferRequest->initialize_states();
return std::make_shared<AsyncInferRequest>(syncInferRequest,
@@ -149,19 +73,7 @@ std::shared_ptr<ov::ISyncInferRequest> CompiledModel::create_sync_infer_request(
void CompiledModel::export_model(std::ostream& stream) const {
_logger.debug("CompiledModel::export_model");
- const auto blob = _compiler->getCompiledNetwork(*_networkPtr);
- stream.write(reinterpret_cast<const char*>(blob.data), blob.size);
-
- if (!stream) {
- _logger.error("Write blob to stream failed. Blob is broken!");
- } else {
- if (_logger.level() >= ov::log::Level::INFO) {
- std::stringstream str;
- str << "Blob size: " << blob.size << ", hash: " << std::hex << hash(blob);
- _logger.info(str.str().c_str());
- }
- _logger.info("Write blob to stream successfully.");
- }
+ _graph->export_blob(stream);
}
std::shared_ptr<const ov::Model> CompiledModel::get_runtime_model() const {
@@ -184,9 +96,9 @@ void CompiledModel::set_property(const ov::AnyMap& properties) {
}
_config.update(config);
- if (_executorPtr != nullptr && config.find(ov::workload_type.name()) != config.end()) {
+ if (config.find(ov::workload_type.name()) != config.end()) {
const auto workloadType = properties.at(ov::workload_type.name()).as<ov::WorkloadType>();
- _executorPtr->setWorkloadType(workloadType);
+ _graph->set_workload_type(workloadType);
}
}
@@ -199,18 +111,14 @@ ov::Any CompiledModel::get_property(const std::string& name) const {
OPENVINO_THROW("Unsupported property ", name);
}
-const std::shared_ptr<const NetworkDescription>& CompiledModel::get_network_description() const {
- return _networkPtr;
+const std::shared_ptr<IGraph>& CompiledModel::get_graph() const {
+ return _graph;
}
const Config& CompiledModel::get_config() const {
return _config;
}
-const ov::SoPtr<ICompiler>& CompiledModel::get_compiler() const {
- return _compiler;
-}
-
void CompiledModel::configure_stream_executors() {
std::shared_ptr<ov::threading::ITaskExecutor> task_executor;
if (get_plugin()->get_property(ov::internal::exclusive_async_requests.name(), {}).as<bool>()) {
@@ -229,7 +137,7 @@ void CompiledModel::configure_stream_executors() {
}
set_task_executor(std::move(task_executor));
- const auto executorId = _networkPtr->metadata.name + "_NPUResultExecutor";
+ const auto executorId = _graph->get_metadata().name + "_NPUResultExecutor";
_resultExecutor = ov::threading::executor_manager()->get_executor(executorId);
}
@@ -268,8 +176,8 @@ void CompiledModel::initialize_properties() {
{true,
ov::PropertyMutability::RO,
[&](const Config&) {
- OPENVINO_ASSERT(_networkPtr != nullptr, "Missing network descriptor");
- return _networkPtr->metadata.name;
+ OPENVINO_ASSERT(_graph != nullptr, "Missing graph");
+ return _graph->get_metadata().name;
}}},
{ov::optimal_number_of_infer_requests.name(),
{true,
@@ -397,6 +305,12 @@ void CompiledModel::initialize_properties() {
[](const Config& config) {
return config.get<CREATE_EXECUTOR>();
}}},
+ {ov::intel_npu::defer_weights_load.name(),
+ {false,
+ ov::PropertyMutability::RO,
+ [](const Config& config) {
+ return config.get<DEFER_WEIGHTS_LOAD>();
+ }}},
{ov::intel_npu::batch_mode.name(),
{false,
ov::PropertyMutability::RO,
@@ -412,18 +326,4 @@ void CompiledModel::initialize_properties() {
}
}
-void CompiledModel::create_executor() {
- if (_config.get<CREATE_EXECUTOR>()) {
- _logger.info("Creating the executor inside the \"CompiledModel\" constructor");
-
- // If no device has been defined, the executor shall keep the default value of "nullptr". In this scenario,
- // only export operations will be allowed
- if (_device != nullptr) {
- _executorPtr = _device->createExecutor(_networkPtr, _config);
- }
- } else {
- _logger.info("Executor will not be created inside the \"CompiledModel\" constructor");
- }
-}
-
} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/plugin/src/compiler.cpp b/src/plugins/intel_npu/src/plugin/src/compiler.cpp
deleted file mode 100644
index 3e270e7ed45..00000000000
--- a/src/plugins/intel_npu/src/plugin/src/compiler.cpp
+++ /dev/null
@@ -1,101 +0,0 @@
-// Copyright (C) 2018-2024 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#include "compiler.hpp"
-
-#include "intel_npu/common/itt.hpp"
-#include "intel_npu/config/compiler.hpp"
-#include "intel_npu/npu_private_properties.hpp"
-#include "intel_npu/utils/logger/logger.hpp"
-
-#ifdef ENABLE_DRIVER_COMPILER_ADAPTER
-# include "driver_compiler_adapter.hpp"
-#endif
-
-#include <memory>
-#include <string>
-
-#include "openvino/util/file_util.hpp"
-#include "openvino/util/shared_object.hpp"
-
-using namespace intel_npu;
-
-namespace {
-
-std::shared_ptr<void> loadLibrary(const std::string& libpath) {
-#if defined(OPENVINO_ENABLE_UNICODE_PATH_SUPPORT) && defined(_WIN32)
- return ov::util::load_shared_object(ov::util::string_to_wstring(libpath).c_str());
-#else
- return ov::util::load_shared_object(libpath.c_str());
-#endif
-}
-
-std::shared_ptr<ICompiler> getCompiler(std::shared_ptr<void> so) {
- static constexpr auto CreateFuncName = "CreateNPUCompiler";
- auto symbol = ov::util::get_symbol(so, CreateFuncName);
-
- using CreateFuncT = void (*)(std::shared_ptr<ICompiler>&);
- const auto createFunc = reinterpret_cast<CreateFuncT>(symbol);
-
- std::shared_ptr<ICompiler> compilerPtr;
- createFunc(compilerPtr);
- return compilerPtr;
-}
-
-ov::SoPtr<ICompiler> loadCompiler(const std::string& libpath) {
- auto compilerSO = loadLibrary(libpath);
- auto compiler = getCompiler(compilerSO);
-
- return ov::SoPtr<ICompiler>(compiler, compilerSO);
-}
-
-ov::SoPtr<ICompiler> createCompilerAdapter(std::shared_ptr<NPUBackends> npuBackends, const Logger& log) {
- log.info("Driver compiler will be used.");
-#ifdef ENABLE_DRIVER_COMPILER_ADAPTER
- if (npuBackends->getBackendName() != "LEVEL0") {
- OPENVINO_THROW("NPU Compiler Adapter must be used with LEVEL0 backend");
- }
- const auto compilerInterface =
- std::make_shared<driverCompilerAdapter::LevelZeroCompilerAdapter>(npuBackends->getIEngineBackend()._ptr);
- return ov::SoPtr<ICompiler>(compilerInterface);
-#else
- OPENVINO_THROW("NPU Compiler Adapter is not enabled");
-#endif
-}
-
-ov::SoPtr<ICompiler> createNPUCompiler(const Logger& log) {
- log.info("MLIR compiler will be used.");
- std::string baseName = "npu_mlir_compiler";
- auto libPath = ov::util::make_plugin_library_name(ov::util::get_ov_lib_path(), baseName + OV_BUILD_POSTFIX);
- return loadCompiler(libPath);
-}
-
-ov::SoPtr<ICompiler> createCompilerImpl(std::shared_ptr<NPUBackends> npuBackends,
- ov::intel_npu::CompilerType compilerType,
- const Logger& log) {
- switch (compilerType) {
- case ov::intel_npu::CompilerType::MLIR:
- return createNPUCompiler(log);
- case ov::intel_npu::CompilerType::DRIVER:
- return createCompilerAdapter(std::move(npuBackends), log);
- default:
- OPENVINO_THROW("Invalid NPU_COMPILER_TYPE");
- }
-}
-
-} // namespace
-
-ov::SoPtr<ICompiler> intel_npu::createCompiler(std::shared_ptr<intel_npu::NPUBackends> npuBackends,
- ov::intel_npu::CompilerType compilerType) {
- OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "intel_npu::createCompiler");
- auto logger = Logger::global().clone("createCompiler");
- try {
- logger.debug("performing createCompilerImpl");
- return createCompilerImpl(std::move(npuBackends), compilerType, logger);
- } catch (const std::exception& ex) {
- OPENVINO_THROW("Got an error during compiler creation: ", ex.what());
- } catch (...) {
- OPENVINO_THROW("Got an unknown error during compiler creation");
- }
-}
diff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
index 7054f20809f..69537fa3c75 100644
--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
@@ -7,20 +7,23 @@
#include <fstream>
#include "compiled_model.hpp"
-#include "compiler.hpp"
+#include "driver_compiler_adapter.hpp"
#include "intel_npu/common/device_helpers.hpp"
+#include "intel_npu/common/igraph.hpp"
#include "intel_npu/common/itt.hpp"
#include "intel_npu/config/common.hpp"
#include "intel_npu/config/compiler.hpp"
#include "intel_npu/config/npuw.hpp"
#include "intel_npu/config/runtime.hpp"
+#include "intel_npu/utils/zero/zero_init.hpp"
#include "npuw/compiled_model.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/parameter.hpp"
#include "openvino/runtime/intel_npu/properties.hpp"
#include "openvino/runtime/properties.hpp"
+#include "plugin_compiler_adapter.hpp"
#include "remote_context.hpp"
-
+#include "zero_backend.hpp"
using namespace intel_npu;
@@ -547,6 +550,12 @@ Plugin::Plugin()
[](const Config& config) {
return config.get<CREATE_EXECUTOR>();
}}},
+ {ov::intel_npu::defer_weights_load.name(),
+ {false,
+ ov::PropertyMutability::RW,
+ [](const Config& config) {
+ return config.get<DEFER_WEIGHTS_LOAD>();
+ }}},
{ov::intel_npu::dynamic_shape_to_static.name(),
{false,
ov::PropertyMutability::RW,
@@ -690,17 +699,24 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<
}
}
+ auto original_model = model->clone();
+ auto compiler = getCompiler(localConfig);
+
OV_ITT_TASK_NEXT(PLUGIN_COMPILE_MODEL, "compile");
+ std::shared_ptr<intel_npu::IGraph> graph;
+ try {
+ _logger.debug("performing compile");
+ graph = compiler->compile(model, localConfig);
+ } catch (const std::exception& ex) {
+ OPENVINO_THROW(ex.what());
+ } catch (...) {
+ _logger.error("Unexpected exception");
+ OPENVINO_THROW("NPU plugin: got an unexpected exception from compiler");
+ }
std::shared_ptr<ov::ICompiledModel> compiledModel;
try {
- bool profiling = localConfig.get<PERF_COUNT>();
- compiledModel = std::make_shared<CompiledModel>(model,
- shared_from_this(),
- device,
- getCompiler(localConfig),
- profiling,
- localConfig);
+ compiledModel = std::make_shared<CompiledModel>(original_model, shared_from_this(), device, graph, localConfig);
} catch (const std::exception& ex) {
OPENVINO_THROW(ex.what());
} catch (...) {
@@ -767,19 +783,13 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& stream, c
}
_logger.debug("Successfully read %zu bytes into blob.", graphSize);
- auto meta = compiler->parse(blob, localConfig);
- meta.name = "net" + std::to_string(_compiledModelLoadCounter++);
-
- const std::shared_ptr<ov::Model> modelDummy = create_dummy_model(meta.inputs, meta.outputs);
+ auto graph = compiler->parse(std::move(blob), localConfig);
+ graph->update_network_name("net" + std::to_string(_compiledModelLoadCounter++));
- auto networkDescription = std::make_shared<const NetworkDescription>(std::move(blob), std::move(meta));
+ const std::shared_ptr<ov::Model> modelDummy =
+ create_dummy_model(graph->get_metadata().inputs, graph->get_metadata().outputs);
- compiledModel = std::make_shared<CompiledModel>(modelDummy,
- shared_from_this(),
- networkDescription,
- device,
- compiler,
- localConfig);
+ compiledModel = std::make_shared<CompiledModel>(modelDummy, shared_from_this(), device, graph, localConfig);
} catch (const std::exception& ex) {
OPENVINO_THROW("Can't import network: ", ex.what());
} catch (...) {
@@ -824,10 +834,38 @@ ov::SupportedOpsMap Plugin::query_model(const std::shared_ptr<const ov::Model>&
return supportedOpsMap;
}
-ov::SoPtr<ICompiler> Plugin::getCompiler(const Config& config) const {
+std::unique_ptr<ICompilerAdapter> Plugin::getCompiler(const Config& config) const {
auto compilerType = config.get<COMPILER_TYPE>();
_logger.debug("performing createCompiler");
- return createCompiler(_backends, compilerType);
+
+ switch (compilerType) {
+ case ov::intel_npu::CompilerType::MLIR: {
+ if (_backends->getBackendName() != "LEVEL0") {
+ return std::make_unique<PluginCompilerAdapter>(nullptr);
+ }
+
+ auto zeroBackend = std::dynamic_pointer_cast<ZeroEngineBackend>(_backends->getIEngineBackend()._ptr);
+ if (zeroBackend == nullptr) {
+ return std::make_unique<PluginCompilerAdapter>(nullptr);
+ }
+
+ return std::make_unique<PluginCompilerAdapter>(zeroBackend->getInitStruct());
+ }
+ case ov::intel_npu::CompilerType::DRIVER: {
+ if (_backends->getBackendName() != "LEVEL0") {
+ OPENVINO_THROW("NPU Compiler Adapter must be used with LEVEL0 backend");
+ }
+
+ auto zeroBackend = std::dynamic_pointer_cast<ZeroEngineBackend>(_backends->getIEngineBackend()._ptr);
+ if (!zeroBackend) {
+ OPENVINO_THROW("Failed to cast zeroBackend, zeroBackend is a nullptr");
+ }
+
+ return std::make_unique<DriverCompilerAdapter>(zeroBackend->getInitStruct());
+ }
+ default:
+ OPENVINO_THROW("Invalid NPU_COMPILER_TYPE");
+ }
}
std::atomic<int> Plugin::_compiledModelLoadCounter{1};
diff --git a/src/plugins/intel_npu/src/backend/include/zero_init.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_init.hpp
similarity index 95%
rename from src/plugins/intel_npu/src/backend/include/zero_init.hpp
rename to src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_init.hpp
index 28dea52ae06..94f2c4ce06e 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_init.hpp
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_init.hpp
@@ -5,14 +5,14 @@
#pragma once
#include <ze_api.h>
+#include <ze_command_queue_npu_ext.h>
#include <ze_graph_ext.h>
+#include <ze_intel_npu_uuid.h>
#include <memory>
#include "intel_npu/utils/logger/logger.hpp"
-#include "ze_command_queue_npu_ext.h"
-#include "ze_intel_npu_uuid.h"
-#include "zero_types.hpp"
+#include "intel_npu/utils/zero/zero_types.hpp"
namespace intel_npu {
/**
diff --git a/src/plugins/intel_npu/src/backend/include/zero_types.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_types.hpp
similarity index 99%
rename from src/plugins/intel_npu/src/backend/include/zero_types.hpp
rename to src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_types.hpp
index 43b97b7217f..032dd867306 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_types.hpp
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_types.hpp
@@ -11,8 +11,6 @@
#include <string_view>
-#include "intel_npu/config/runtime.hpp"
-
/**
* @brief Last version of the Command Queue functions used within plugin
*/
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_utils.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_utils.hpp
index 044fd1415c8..8883bb99dd1 100644
--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_utils.hpp
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_utils.hpp
@@ -8,13 +8,18 @@
#include <ze_api.h>
#include <ze_graph_ext.h>
-#include "intel_npu/config/runtime.hpp"
#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/zero/zero_api.hpp"
#include "intel_npu/utils/zero/zero_result.hpp"
#include "zero_types.hpp"
namespace intel_npu {
+struct ArgumentDescriptor {
+ ze_graph_argument_properties_3_t info;
+ uint32_t idx;
+};
+
namespace zeroUtils {
#define THROW_ON_FAIL_FOR_LEVELZERO_EXT(step, result, graph_ddi_table_ext) \
@@ -173,11 +178,29 @@ static inline std::size_t getSizeIOBytes(const ze_graph_argument_properties_3_t&
return size_in_bytes;
}
-static inline uint32_t findGroupOrdinal(
- const std::vector<ze_command_queue_group_properties_t>& command_group_properties,
- const ze_device_properties_t& properties) {
+static inline uint32_t findGroupOrdinal(ze_device_handle_t device_handle, const ze_device_properties_t& properties) {
auto log = Logger::global().clone("findGroupOrdinal");
+ std::vector<ze_command_queue_group_properties_t> command_group_properties;
+ uint32_t command_queue_group_count = 0;
+ // Discover all command queue groups
+ THROW_ON_FAIL_FOR_LEVELZERO(
+ "zeDeviceGetCommandQueueGroupProperties",
+ zeDeviceGetCommandQueueGroupProperties(device_handle, &command_queue_group_count, nullptr));
+
+ log.debug("ZeroDevice::ZeroDevice - resize command_queue_group_count");
+ command_group_properties.resize(command_queue_group_count);
+
+ for (auto& prop : command_group_properties) {
+ prop.stype = ZE_STRUCTURE_TYPE_COMMAND_QUEUE_GROUP_PROPERTIES;
+ prop.pNext = nullptr;
+ }
+
+ THROW_ON_FAIL_FOR_LEVELZERO("zeDeviceGetCommandQueueGroupProperties",
+ zeDeviceGetCommandQueueGroupProperties(device_handle,
+ &command_queue_group_count,
+ command_group_properties.data()));
+
if (properties.flags & ZE_DEVICE_PROPERTY_FLAG_INTEGRATED) {
for (uint32_t index = 0; index < command_group_properties.size(); ++index) {
const auto& flags = command_group_properties[index].flags;
diff --git a/src/plugins/intel_npu/src/backend/include/zero_wrappers.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_wrappers.hpp
similarity index 90%
rename from src/plugins/intel_npu/src/backend/include/zero_wrappers.hpp
rename to src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_wrappers.hpp
index 854bd88a7e4..afd6813a662 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_wrappers.hpp
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_wrappers.hpp
@@ -5,31 +5,19 @@
#pragma once
#include <ze_api.h>
-#include <ze_graph_ext.h>
#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/zero/zero_types.hpp"
#include "intel_npu/utils/zero/zero_utils.hpp"
-#include "zero_types.hpp"
namespace intel_npu {
class CommandList;
class CommandQueue;
-enum stage {
- UPLOAD,
- EXECUTE,
- READBACK,
-
- COUNT
-};
-
class EventPool {
public:
EventPool() = delete;
- EventPool(ze_device_handle_t device_handle,
- const ze_context_handle_t& context,
- uint32_t event_count,
- const Config& config);
+ EventPool(ze_device_handle_t device_handle, const ze_context_handle_t& context, uint32_t event_count);
EventPool(const EventPool&) = delete;
EventPool(EventPool&&) = delete;
EventPool& operator=(const EventPool&) = delete;
@@ -48,7 +36,7 @@ private:
class Event {
public:
Event() = delete;
- Event(const ze_event_pool_handle_t& event_pool, uint32_t event_index, const Config& config);
+ Event(const ze_event_pool_handle_t& event_pool, uint32_t event_index);
Event(const Event&) = delete;
Event(Event&&) = delete;
Event& operator=(const Event&) = delete;
@@ -74,7 +62,6 @@ public:
CommandList(const ze_device_handle_t& device_handle,
const ze_context_handle_t& context,
ze_graph_dditable_ext_curr_t& graph_ddi_table_ext,
- const Config& config,
const uint32_t& group_ordinal,
bool mtci_is_supported = false);
CommandList(const CommandList&) = delete;
@@ -109,7 +96,7 @@ private:
class Fence {
public:
Fence() = delete;
- Fence(const CommandQueue& command_queue, const Config& config);
+ Fence(const CommandQueue& command_queue);
Fence(const Fence&) = delete;
Fence(Fence&&) = delete;
Fence& operator=(const Fence&) = delete;
@@ -135,7 +122,7 @@ public:
const ze_context_handle_t& context,
const ze_command_queue_priority_t& priority,
ze_command_queue_npu_dditable_ext_curr_t& command_queue_npu_dditable_ext,
- const Config& config,
+ bool turbo,
const uint32_t& group_ordinal);
CommandQueue(const CommandQueue&) = delete;
CommandQueue(CommandQueue&&) = delete;
diff --git a/src/plugins/intel_npu/src/utils/src/CMakeLists.txt b/src/plugins/intel_npu/src/utils/src/CMakeLists.txt
index 5cda27e6246..0274a7f43ec 100644
--- a/src/plugins/intel_npu/src/utils/src/CMakeLists.txt
+++ b/src/plugins/intel_npu/src/utils/src/CMakeLists.txt
@@ -3,6 +3,7 @@
#
add_subdirectory(logger)
-if(ENABLE_ZEROAPI_BACKEND)
+
+if(ENABLE_NPU_PLUGIN_ENGINE)
add_subdirectory(zero)
endif()
diff --git a/src/plugins/intel_npu/src/utils/src/zero/CMakeLists.txt b/src/plugins/intel_npu/src/utils/src/zero/CMakeLists.txt
index 7e99bcf0a46..f1e81267dc2 100644
--- a/src/plugins/intel_npu/src/utils/src/zero/CMakeLists.txt
+++ b/src/plugins/intel_npu/src/utils/src/zero/CMakeLists.txt
@@ -2,26 +2,50 @@
# SPDX-License-Identifier: Apache-2.0
#
-set(TARGET_NAME openvino_npu_zero_result_parser)
+set(TARGET_NAME openvino_npu_zero_utils)
file(GLOB_RECURSE SOURCES *.cpp)
+source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${SOURCES})
add_library(${TARGET_NAME} STATIC ${SOURCES})
set_target_properties(
${TARGET_NAME} PROPERTIES INTERPROCEDURAL_OPTIMIZATION_RELEASE ${ENABLE_LTO})
ov_add_clang_format_target(${TARGET_NAME}_clang FOR_TARGETS ${TARGET_NAME})
-target_include_directories(
- ${TARGET_NAME}
+add_library(openvino::npu_zero_utils ALIAS ${TARGET_NAME})
+set_target_properties(${TARGET_NAME} PROPERTIES EXPORT_NAME npu_zero_utils)
+
+target_include_directories(${TARGET_NAME}
PUBLIC
$<TARGET_PROPERTY:LevelZero::LevelZero,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:LevelZero::NPUExt,INTERFACE_INCLUDE_DIRECTORIES>
$<BUILD_INTERFACE:${NPU_UTILS_SOURCE_DIR}/include>)
+
target_link_libraries(
${TARGET_NAME}
- PRIVATE openvino::runtime openvino::runtime::dev)
+ PUBLIC openvino::runtime openvino::runtime::dev)
+
#
# targets install
#
-ov_install_static_lib(${TARGET_NAME} ${NPU_INTERNAL_COMPONENT})
+ov_install_static_lib(${TARGET_NAME} ${NPU_PLUGIN_COMPONENT})
+
+ov_developer_package_export_targets(TARGET openvino::npu_zero_utils
+ INSTALL_INCLUDE_DIRECTORIES
+ $<BUILD_INTERFACE:${NPU_UTILS_SOURCE_DIR}/include>)
+
+if(TARGET ze_loader)
+ ov_developer_package_export_targets(TARGET ze_loader)
+ ov_developer_package_export_targets(TARGET utils)
+ ov_developer_package_export_targets(TARGET level-zero-ext)
+
+ ov_install_static_lib(ze_loader ${NPU_PLUGIN_COMPONENT})
+ ov_install_static_lib(utils ${NPU_PLUGIN_COMPONENT})
+ ov_install_static_lib(level-zero-ext ${NPU_PLUGIN_COMPONENT})
+
+ # Support tests to run with ze_loader
+ install(TARGETS ze_loader
+ RUNTIME DESTINATION tests COMPONENT tests EXCLUDE_FROM_ALL
+ LIBRARY DESTINATION tests COMPONENT tests EXCLUDE_FROM_ALL)
+endif()
diff --git a/src/plugins/intel_npu/src/backend/src/zero_init.cpp b/src/plugins/intel_npu/src/utils/src/zero/zero_init.cpp
similarity index 98%
rename from src/plugins/intel_npu/src/backend/src/zero_init.cpp
rename to src/plugins/intel_npu/src/utils/src/zero/zero_init.cpp
index 827450718ed..ac6e3c2306f 100644
--- a/src/plugins/intel_npu/src/backend/src/zero_init.cpp
+++ b/src/plugins/intel_npu/src/utils/src/zero/zero_init.cpp
@@ -2,20 +2,20 @@
// SPDX-License-Identifier: Apache-2.0
//
-#include "zero_init.hpp"
+#include "intel_npu/utils/zero/zero_init.hpp"
+
+#include <ze_command_queue_npu_ext.h>
#include <regex>
-#include "intel_npu/common/itt.hpp"
#include "intel_npu/utils/zero/zero_api.hpp"
#include "intel_npu/utils/zero/zero_utils.hpp"
-#include "ze_api.h"
-#include "ze_command_queue_npu_ext.h"
#ifdef _WIN32
namespace {
constexpr uint32_t WIN_DRIVER_NO_MCL_SUPPORT = 2688;
} // namespace
+
#endif
namespace intel_npu {
@@ -54,7 +54,6 @@ static std::tuple<uint32_t, std::string> queryDriverExtensionVersion(
}
ZeroInitStructsHolder::ZeroInitStructsHolder() : log("NPUZeroInitStructsHolder", Logger::global().level()) {
- OV_ITT_SCOPED_TASK(itt::domains::LevelZeroBackend, "ZeroInitStructsHolder::ZeroInitStructsHolder");
log.debug("ZeroInitStructsHolder - performing zeInit on VPU only");
THROW_ON_FAIL_FOR_LEVELZERO("zeInit", zeInit(ZE_INIT_FLAG_VPU_ONLY));
diff --git a/src/plugins/intel_npu/src/backend/src/zero_wrappers.cpp b/src/plugins/intel_npu/src/utils/src/zero/zero_wrappers.cpp
similarity index 91%
rename from src/plugins/intel_npu/src/backend/src/zero_wrappers.cpp
rename to src/plugins/intel_npu/src/utils/src/zero/zero_wrappers.cpp
index 2de6cb2d3c4..32a497552fc 100644
--- a/src/plugins/intel_npu/src/backend/src/zero_wrappers.cpp
+++ b/src/plugins/intel_npu/src/utils/src/zero/zero_wrappers.cpp
@@ -2,19 +2,14 @@
// SPDX-License-Identifier: Apache-2.0
//
-#include "zero_wrappers.hpp"
+#include "intel_npu/utils/zero/zero_wrappers.hpp"
-#include "intel_npu/config/common.hpp"
#include "intel_npu/utils/zero/zero_api.hpp"
-#include "zero_types.hpp"
namespace intel_npu {
-EventPool::EventPool(ze_device_handle_t device_handle,
- const ze_context_handle_t& context,
- uint32_t event_count,
- const Config& config)
- : _log("EventPool", config.get<LOG_LEVEL>()) {
+EventPool::EventPool(ze_device_handle_t device_handle, const ze_context_handle_t& context, uint32_t event_count)
+ : _log("EventPool", Logger::global().level()) {
ze_event_pool_desc_t event_pool_desc = {ZE_STRUCTURE_TYPE_EVENT_POOL_DESC,
nullptr,
ZE_EVENT_POOL_FLAG_HOST_VISIBLE,
@@ -29,8 +24,7 @@ EventPool::~EventPool() {
}
}
-Event::Event(const ze_event_pool_handle_t& event_pool, uint32_t event_index, const Config& config)
- : _log("Event", config.get<LOG_LEVEL>()) {
+Event::Event(const ze_event_pool_handle_t& event_pool, uint32_t event_index) : _log("Event", Logger::global().level()) {
ze_event_desc_t event_desc = {ZE_STRUCTURE_TYPE_EVENT_DESC, nullptr, event_index, 0, 0};
THROW_ON_FAIL_FOR_LEVELZERO("zeEventCreate", zeEventCreate(event_pool, &event_desc, &_handle));
}
@@ -62,12 +56,11 @@ Event::~Event() {
CommandList::CommandList(const ze_device_handle_t& device_handle,
const ze_context_handle_t& context,
ze_graph_dditable_ext_curr_t& graph_ddi_table_ext,
- const Config& config,
const uint32_t& group_ordinal,
bool mtci_is_supported)
: _context(context),
_graph_ddi_table_ext(graph_ddi_table_ext),
- _log("CommandList", config.get<LOG_LEVEL>()) {
+ _log("CommandList", Logger::global().level()) {
ze_mutable_command_list_exp_desc_t mutable_desc = {ZE_STRUCTURE_TYPE_MUTABLE_COMMAND_LIST_EXP_DESC, nullptr, 0};
ze_command_list_desc_t desc = {ZE_STRUCTURE_TYPE_COMMAND_LIST_DESC, &mutable_desc, group_ordinal, 0};
THROW_ON_FAIL_FOR_LEVELZERO("zeCommandListCreate", zeCommandListCreate(_context, device_handle, &desc, &_handle));
@@ -132,22 +125,23 @@ CommandQueue::CommandQueue(const ze_device_handle_t& device_handle,
const ze_context_handle_t& context,
const ze_command_queue_priority_t& priority,
ze_command_queue_npu_dditable_ext_curr_t& command_queue_npu_dditable_ext,
- const Config& config,
+ bool turbo,
const uint32_t& group_ordinal)
: _context(context),
_command_queue_npu_dditable_ext(command_queue_npu_dditable_ext),
- _log("CommandQueue", config.get<LOG_LEVEL>()) {
+ _log("CommandQueue", Logger::global().level()) {
ze_command_queue_desc_t queue_desc =
{ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC, nullptr, group_ordinal, 0, 0, ZE_COMMAND_QUEUE_MODE_DEFAULT, priority};
- if (config.has<TURBO>()) {
+
+ if (turbo) {
if (_command_queue_npu_dditable_ext.version()) {
- bool turbo = config.get<TURBO>();
ze_command_queue_desc_npu_ext_t turbo_cfg = {ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC_NPU_EXT, nullptr, turbo};
queue_desc.pNext = &turbo_cfg;
} else {
OPENVINO_THROW("Turbo is not supported by the current driver");
}
}
+
THROW_ON_FAIL_FOR_LEVELZERO("zeCommandQueueCreate",
zeCommandQueueCreate(_context, device_handle, &queue_desc, &_handle));
}
@@ -176,7 +170,7 @@ CommandQueue::~CommandQueue() {
}
}
-Fence::Fence(const CommandQueue& command_queue, const Config& config) : _log("Fence", config.get<LOG_LEVEL>()) {
+Fence::Fence(const CommandQueue& command_queue) : _log("Fence", Logger::global().level()) {
ze_fence_desc_t fence_desc = {ZE_STRUCTURE_TYPE_FENCE_DESC, nullptr, 0};
THROW_ON_FAIL_FOR_LEVELZERO("zeFenceCreate", zeFenceCreate(command_queue.handle(), &fence_desc, &_handle));
}
diff --git a/src/plugins/intel_npu/tests/functional/CMakeLists.txt b/src/plugins/intel_npu/tests/functional/CMakeLists.txt
index eac8166b02b..2771d8cb3ef 100644
--- a/src/plugins/intel_npu/tests/functional/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/functional/CMakeLists.txt
@@ -14,13 +14,11 @@ set(EXCLUDED_FUNC_TESTS_DIR "")
set(OPTIONAL_FUNC_TESTS_INCLUDES "")
set(OPTIONAL_FUNC_TESTS_LIBS "")
-if(ENABLE_DRIVER_COMPILER_ADAPTER)
- list(APPEND OPTIONAL_FUNC_TESTS_INCLUDES
- "${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/compiler/include")
+list(APPEND OPTIONAL_FUNC_TESTS_INCLUDES
+ "${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/compiler_adapter/include")
- list(APPEND OPTIONAL_FUNC_TESTS_LIBS openvino_npu_driver_compiler_adapter
- openvino_npu_level_zero_backend openvino_npu_zero_result_parser)
-endif()
+list(APPEND OPTIONAL_FUNC_TESTS_LIBS openvino_npu_driver_compiler_adapter
+ openvino_npu_level_zero_backend openvino_npu_zero_utils)
ov_add_test_target(
NAME
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npu_driver_compiler_adapter/custom_stream.cpp b/src/plugins/intel_npu/tests/functional/behavior/npu_driver_compiler_adapter/custom_stream.cpp
index 3950caa379c..ec032696511 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npu_driver_compiler_adapter/custom_stream.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npu_driver_compiler_adapter/custom_stream.cpp
@@ -8,15 +8,16 @@
#include "common/functions.h"
#include "common/npu_test_env_cfg.hpp"
#include "common_test_utils/node_builders/constant.hpp"
-#include "graph_transformations.hpp"
#include "intel_npu/config/common.hpp"
+#include "ir_serializer.hpp"
#include "openvino/opsets/opset11.hpp"
+
using CompilationParams = std::tuple<std::string, // Device name
ov::AnyMap // Config
>;
-using IRSerializer = intel_npu::driverCompilerAdapter::IRSerializer;
+using IRSerializer = intel_npu::driver_compiler_utils::IRSerializer;
namespace ov::test::behavior {
diff --git a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/compile_and_infer.cpp b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/compile_and_infer.cpp
index 5d308c34405..38c1838bfa4 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/compile_and_infer.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/compile_and_infer.cpp
@@ -27,8 +27,8 @@ INSTANTIATE_TEST_SUITE_P(compatibility_smoke_BehaviorTests,
::testing::Combine(::testing::Values(getConstantGraph(ov::element::f32)),
::testing::Values(ov::test::utils::DEVICE_NPU),
::testing::ValuesIn(std::vector<ov::AnyMap>{
- {ov::intel_npu::create_executor(0)},
- {ov::intel_npu::create_executor(1)}})),
+ {ov::intel_npu::defer_weights_load(true)},
+ {ov::intel_npu::defer_weights_load(false)}})),
ov::test::utils::appendPlatformTypeTestName<OVCompileAndInferRequestTurbo>);
} // namespace
diff --git a/src/plugins/intel_npu/tests/functional/behavior/work_with_devices.hpp b/src/plugins/intel_npu/tests/functional/behavior/work_with_devices.hpp
index 27ced4337c4..ea50ede9f8b 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/work_with_devices.hpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/work_with_devices.hpp
@@ -54,7 +54,7 @@ TEST_P(TestCompiledModelNPU, samePlatformProduceTheSameBlob) {
SKIP_IF_CURRENT_TEST_IS_DISABLED() {
std::string platform = ov::test::utils::getTestsPlatformFromEnvironmentOr("3720");
- configuration[ov::intel_npu::create_executor.name()] = "0";
+ configuration[ov::intel_npu::defer_weights_load.name()] = true;
auto configuration1 = configuration;
configuration1[ov::intel_npu::platform.name()] = platform;
const auto& ov_model1 = buildSingleLayerSoftMaxNetwork();
diff --git a/src/plugins/intel_npu/tests/functional/internal/overload/compile_and_infer.hpp b/src/plugins/intel_npu/tests/functional/internal/overload/compile_and_infer.hpp
index 49475e7008f..e06ac84b6ab 100644
--- a/src/plugins/intel_npu/tests/functional/internal/overload/compile_and_infer.hpp
+++ b/src/plugins/intel_npu/tests/functional/internal/overload/compile_and_infer.hpp
@@ -11,10 +11,10 @@
#include "base/ov_behavior_test_utils.hpp"
#include "intel_npu/config/common.hpp"
#include "intel_npu/npu_private_properties.hpp"
+#include "intel_npu/utils/zero/zero_init.hpp"
#include "openvino/core/except.hpp"
#include "openvino/opsets/opset8.hpp"
#include "openvino/runtime/properties.hpp"
-#include "zero_init.hpp"
namespace ov {
namespace test {
@@ -159,7 +159,7 @@ TEST_P(OVCompileAndInferRequest, CompiledModelWorkloadType) {
}
TEST_P(OVCompileAndInferRequest, CompiledModelWorkloadTypeDelayedExecutor) {
- configuration[intel_npu::create_executor.name()] = 0;
+ configuration[intel_npu::defer_weights_load.name()] = true;
OV_ASSERT_NO_THROW(execNet = core->compile_model(function, target_device, configuration));
ov::AnyMap modelConfiguration;
modelConfiguration[workload_type.name()] = WorkloadType::DEFAULT;
@@ -233,8 +233,8 @@ TEST_P(OVCompileAndInferRequestTurbo, CompiledModelTurbo) {
OV_ASSERT_NO_THROW(req.wait());
ASSERT_TRUE(is_called);
} else {
- auto cr_ex = configuration.find(intel_npu::create_executor.name());
- if (cr_ex->second.as<int64_t>() == 1) {
+ auto cr_ex = configuration.find(intel_npu::defer_weights_load.name());
+ if (cr_ex->second.as<bool>() == false) {
OV_EXPECT_THROW_HAS_SUBSTRING(core->compile_model(function, target_device, configuration),
ov::Exception,
"Turbo is not supported by the current driver");
diff --git a/src/plugins/intel_npu/tests/functional/internal/overload/compiled_model/property.cpp b/src/plugins/intel_npu/tests/functional/internal/overload/compiled_model/property.cpp
index 9b9bd74373c..ad30e5b5338 100644
--- a/src/plugins/intel_npu/tests/functional/internal/overload/compiled_model/property.cpp
+++ b/src/plugins/intel_npu/tests/functional/internal/overload/compiled_model/property.cpp
@@ -130,7 +130,7 @@ std::vector<std::pair<std::string, ov::Any>> plugin_internal_mutable_properties
{ov::intel_npu::stepping.name(), ov::Any(4)},
{ov::intel_npu::dpu_groups.name(), ov::Any(2)},
{ov::intel_npu::use_elf_compiler_backend.name(), ov::Any(ov::intel_npu::ElfCompilerBackend::YES)},
- {ov::intel_npu::create_executor.name(), ov::Any(0)},
+ {ov::intel_npu::defer_weights_load.name(), ov::Any(true)},
};
std::vector<std::pair<std::string, ov::Any>> plugin_public_immutable_properties = {
diff --git a/src/plugins/intel_npu/tests/functional/shared_tests_instances/behavior/compiled_model/properties.cpp b/src/plugins/intel_npu/tests/functional/shared_tests_instances/behavior/compiled_model/properties.cpp
index 89a98cce009..99fb4c749ce 100644
--- a/src/plugins/intel_npu/tests/functional/shared_tests_instances/behavior/compiled_model/properties.cpp
+++ b/src/plugins/intel_npu/tests/functional/shared_tests_instances/behavior/compiled_model/properties.cpp
@@ -48,7 +48,7 @@ const std::vector<std::pair<std::string, ov::Any>> compiledModelProperties = {
{ov::intel_npu::tiles.name(), ov::Any(2)},
{ov::intel_npu::profiling_type.name(), ov::Any(ov::intel_npu::ProfilingType::INFER)},
{ov::intel_npu::use_elf_compiler_backend.name(), ov::Any(ov::intel_npu::ElfCompilerBackend::NO)},
- {ov::intel_npu::create_executor.name(), ov::Any(2)}};
+ {ov::intel_npu::defer_weights_load.name(), ov::Any(false)}};
const std::string& expectedModelName = []() -> std::string {
return ov::test::behavior::getDefaultNGraphFunctionForTheDevice()->get_friendly_name();
diff --git a/src/plugins/intel_npu/thirdparty/CMakeLists.txt b/src/plugins/intel_npu/thirdparty/CMakeLists.txt
index 9edd3a95666..8fbf9183236 100644
--- a/src/plugins/intel_npu/thirdparty/CMakeLists.txt
+++ b/src/plugins/intel_npu/thirdparty/CMakeLists.txt
@@ -6,11 +6,10 @@
# zeroApi
#
-if(ENABLE_ZEROAPI_BACKEND)
+if(ENABLE_NPU_PLUGIN_ENGINE)
add_library(level-zero-ext INTERFACE)
set_property(TARGET level-zero-ext APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/level-zero-ext/>)
add_library(LevelZero::NPUExt ALIAS level-zero-ext)
- install(TARGETS level-zero-ext EXPORT "${PROJECT_NAME}Targets")
endif()
#